httplib.h 685 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724
  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, const Headers &headers, DownloadProgress progress = nullptr);
  1830. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1831. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1832. Result Head(const std::string &path);
  1833. Result Head(const std::string &path, const Headers &headers);
  1834. Result Post(const std::string &path);
  1835. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1836. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, 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, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1840. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, const Params &params);
  1842. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1843. Result Post(const std::string &path, const Headers &headers);
  1844. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1845. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, 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, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1848. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1849. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1850. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1851. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1852. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1855. Result Put(const std::string &path);
  1856. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1857. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, 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, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1861. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, const Params &params);
  1863. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1864. Result Put(const std::string &path, const Headers &headers);
  1865. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1866. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, 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, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1869. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1870. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1872. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1873. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1876. Result Patch(const std::string &path);
  1877. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1878. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, 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, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1882. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, const Params &params);
  1884. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1885. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1886. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1887. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1888. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, 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, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1890. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1891. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1893. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1894. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1897. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1898. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1899. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1900. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1901. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1902. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1903. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1904. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1905. Result Options(const std::string &path);
  1906. Result Options(const std::string &path, const Headers &headers);
  1907. // clang-format on
  1908. // Streaming API: Open a stream for reading response body incrementally
  1909. // Socket ownership is transferred to StreamHandle for true streaming
  1910. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1911. StreamHandle open_stream(const std::string &method, const std::string &path,
  1912. const Params &params = {},
  1913. const Headers &headers = {},
  1914. const std::string &body = {},
  1915. const std::string &content_type = {});
  1916. bool send(Request &req, Response &res, Error &error);
  1917. Result send(const Request &req);
  1918. void stop();
  1919. std::string host() const;
  1920. int port() const;
  1921. size_t is_socket_open() const;
  1922. socket_t socket() const;
  1923. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1924. void set_default_headers(Headers headers);
  1925. void
  1926. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1927. void set_address_family(int family);
  1928. void set_tcp_nodelay(bool on);
  1929. void set_ipv6_v6only(bool on);
  1930. void set_socket_options(SocketOptions socket_options);
  1931. void set_connection_timeout(time_t sec, time_t usec = 0);
  1932. template <class Rep, class Period>
  1933. void
  1934. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1935. void set_read_timeout(time_t sec, time_t usec = 0);
  1936. template <class Rep, class Period>
  1937. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1938. void set_write_timeout(time_t sec, time_t usec = 0);
  1939. template <class Rep, class Period>
  1940. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1941. void set_max_timeout(time_t msec);
  1942. template <class Rep, class Period>
  1943. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1944. void set_basic_auth(const std::string &username, const std::string &password);
  1945. void set_bearer_token_auth(const std::string &token);
  1946. void set_keep_alive(bool on);
  1947. void set_follow_location(bool on);
  1948. void set_path_encode(bool on);
  1949. void set_compress(bool on);
  1950. void set_decompress(bool on);
  1951. void set_payload_max_length(size_t length);
  1952. void set_interface(const std::string &intf);
  1953. void set_proxy(const std::string &host, int port);
  1954. void set_proxy_basic_auth(const std::string &username,
  1955. const std::string &password);
  1956. void set_proxy_bearer_token_auth(const std::string &token);
  1957. void set_no_proxy(const std::vector<std::string> &patterns);
  1958. void set_logger(Logger logger);
  1959. void set_error_logger(ErrorLogger error_logger);
  1960. protected:
  1961. struct Socket {
  1962. socket_t sock = INVALID_SOCKET;
  1963. // For Mbed TLS compatibility: start_time for request timeout tracking
  1964. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1965. bool is_open() const { return sock != INVALID_SOCKET; }
  1966. #ifdef CPPHTTPLIB_SSL_ENABLED
  1967. tls::session_t ssl = nullptr;
  1968. #endif
  1969. };
  1970. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1971. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1972. virtual bool setup_proxy_connection(
  1973. Socket &socket,
  1974. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1975. Response &res, bool &success, Error &error);
  1976. bool is_proxy_enabled_for_host(const std::string &host) const;
  1977. // All of:
  1978. // shutdown_ssl
  1979. // shutdown_socket
  1980. // close_socket
  1981. // disconnect
  1982. // should ONLY be called when socket_mutex_ is locked, and only when
  1983. // no other thread is using the socket.
  1984. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1985. void shutdown_socket(Socket &socket) const;
  1986. void close_socket(Socket &socket);
  1987. void disconnect(bool gracefully);
  1988. bool process_request(Stream &strm, Request &req, Response &res,
  1989. bool close_connection, Error &error);
  1990. bool write_content_with_provider(Stream &strm, const Request &req,
  1991. Error &error) const;
  1992. void copy_settings(const ClientImpl &rhs);
  1993. void output_log(const Request &req, const Response &res) const;
  1994. void output_error_log(const Error &err, const Request *req) const;
  1995. // Socket endpoint information
  1996. const std::string host_;
  1997. const int port_;
  1998. // Current open socket
  1999. Socket socket_;
  2000. mutable std::mutex socket_mutex_;
  2001. std::recursive_mutex request_mutex_;
  2002. // These are all protected under socket_mutex
  2003. size_t socket_requests_in_flight_ = 0;
  2004. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2005. bool socket_should_be_closed_when_request_is_done_ = false;
  2006. // Hostname-IP map
  2007. std::map<std::string, std::string> addr_map_;
  2008. // Default headers
  2009. Headers default_headers_;
  2010. // Header writer
  2011. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2012. detail::write_headers;
  2013. // Settings
  2014. std::string client_cert_path_;
  2015. std::string client_key_path_;
  2016. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2017. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2018. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2019. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2020. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2021. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2022. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2023. std::string basic_auth_username_;
  2024. std::string basic_auth_password_;
  2025. std::string bearer_token_auth_token_;
  2026. bool keep_alive_ = false;
  2027. bool follow_location_ = false;
  2028. bool path_encode_ = true;
  2029. int address_family_ = AF_UNSPEC;
  2030. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2031. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2032. SocketOptions socket_options_ = nullptr;
  2033. bool compress_ = false;
  2034. bool decompress_ = true;
  2035. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2036. bool has_payload_max_length_ = false;
  2037. std::string interface_;
  2038. std::string proxy_host_;
  2039. int proxy_port_ = -1;
  2040. std::string proxy_basic_auth_username_;
  2041. std::string proxy_basic_auth_password_;
  2042. std::string proxy_bearer_token_auth_token_;
  2043. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2044. mutable detail::NormalizedTarget host_normalized_;
  2045. mutable bool host_normalized_valid_ = false;
  2046. mutable std::mutex logger_mutex_;
  2047. Logger logger_;
  2048. ErrorLogger error_logger_;
  2049. private:
  2050. bool send_(Request &req, Response &res, Error &error);
  2051. Result send_(Request &&req);
  2052. socket_t create_client_socket(Error &error) const;
  2053. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2054. bool skip_100_continue = true) const;
  2055. bool write_request(Stream &strm, Request &req, bool close_connection,
  2056. Error &error, bool skip_body = false);
  2057. bool write_request_body(Stream &strm, Request &req, Error &error);
  2058. void prepare_default_headers(Request &r, bool for_stream,
  2059. const std::string &ct);
  2060. bool redirect(Request &req, Response &res, Error &error);
  2061. bool create_redirect_client(const std::string &scheme,
  2062. const std::string &host, int port, Request &req,
  2063. Response &res, const std::string &path,
  2064. const std::string &location, Error &error);
  2065. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2066. bool handle_request(Stream &strm, Request &req, Response &res,
  2067. bool close_connection, Error &error);
  2068. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2069. Request &req, const char *body, size_t content_length,
  2070. ContentProvider content_provider,
  2071. ContentProviderWithoutLength content_provider_without_length,
  2072. const std::string &content_type, ContentReceiver content_receiver,
  2073. Error &error);
  2074. Result send_with_content_provider_and_receiver(
  2075. const std::string &method, const std::string &path,
  2076. const Headers &headers, const char *body, size_t content_length,
  2077. ContentProvider content_provider,
  2078. ContentProviderWithoutLength content_provider_without_length,
  2079. const std::string &content_type, ContentReceiver content_receiver,
  2080. UploadProgress progress);
  2081. ContentProviderWithoutLength get_multipart_content_provider(
  2082. const std::string &boundary, const UploadFormDataItems &items,
  2083. const FormDataProviderItems &provider_items) const;
  2084. virtual bool
  2085. process_socket(const Socket &socket,
  2086. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2087. std::function<bool(Stream &strm)> callback);
  2088. virtual bool is_ssl() const;
  2089. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2090. #ifdef CPPHTTPLIB_SSL_ENABLED
  2091. public:
  2092. void set_digest_auth(const std::string &username,
  2093. const std::string &password);
  2094. void set_proxy_digest_auth(const std::string &username,
  2095. const std::string &password);
  2096. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2097. const std::string &ca_cert_dir_path = std::string());
  2098. void enable_server_certificate_verification(bool enabled);
  2099. void enable_server_hostname_verification(bool enabled);
  2100. void enable_system_ca(bool enabled);
  2101. protected:
  2102. std::string digest_auth_username_;
  2103. std::string digest_auth_password_;
  2104. std::string proxy_digest_auth_username_;
  2105. std::string proxy_digest_auth_password_;
  2106. std::string ca_cert_file_path_;
  2107. std::string ca_cert_dir_path_;
  2108. bool server_certificate_verification_ = true;
  2109. bool server_hostname_verification_ = true;
  2110. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2111. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2112. int last_ssl_error_ = 0;
  2113. uint64_t last_backend_error_ = 0;
  2114. #endif
  2115. };
  2116. class Client {
  2117. public:
  2118. // Universal interface
  2119. explicit Client(const std::string &scheme_host_port);
  2120. explicit Client(const std::string &scheme_host_port,
  2121. const std::string &client_cert_path,
  2122. const std::string &client_key_path);
  2123. // HTTP only interface
  2124. explicit Client(const std::string &host, int port);
  2125. explicit Client(const std::string &host, int port,
  2126. const std::string &client_cert_path,
  2127. const std::string &client_key_path);
  2128. Client(Client &&) = default;
  2129. Client &operator=(Client &&) = default;
  2130. ~Client();
  2131. bool is_valid() const;
  2132. // clang-format off
  2133. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2134. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2135. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2136. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2137. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2138. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2139. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2142. Result Head(const std::string &path);
  2143. Result Head(const std::string &path, const Headers &headers);
  2144. Result Post(const std::string &path);
  2145. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2146. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2147. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2150. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, const Params &params);
  2152. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Headers &headers);
  2154. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2156. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2157. 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);
  2158. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2159. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2160. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2161. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2163. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2165. Result Put(const std::string &path);
  2166. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2167. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2168. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, const Params &params);
  2173. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Headers &headers);
  2175. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2177. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2178. 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);
  2179. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2180. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2181. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2182. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2184. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2186. Result Patch(const std::string &path);
  2187. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2188. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2189. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, const Params &params);
  2194. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Headers &headers);
  2196. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2198. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2199. 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);
  2200. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2201. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2202. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2203. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2205. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2207. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2208. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2209. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2210. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2211. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2212. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2213. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2215. Result Options(const std::string &path);
  2216. Result Options(const std::string &path, const Headers &headers);
  2217. // clang-format on
  2218. // Streaming API: Open a stream for reading response body incrementally
  2219. // Socket ownership is transferred to StreamHandle for true streaming
  2220. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2221. ClientImpl::StreamHandle open_stream(const std::string &method,
  2222. const std::string &path,
  2223. const Params &params = {},
  2224. const Headers &headers = {},
  2225. const std::string &body = {},
  2226. const std::string &content_type = {});
  2227. bool send(Request &req, Response &res, Error &error);
  2228. Result send(const Request &req);
  2229. void stop();
  2230. std::string host() const;
  2231. int port() const;
  2232. size_t is_socket_open() const;
  2233. socket_t socket() const;
  2234. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2235. void set_default_headers(Headers headers);
  2236. void
  2237. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2238. void set_address_family(int family);
  2239. void set_tcp_nodelay(bool on);
  2240. void set_socket_options(SocketOptions socket_options);
  2241. void set_connection_timeout(time_t sec, time_t usec = 0);
  2242. template <class Rep, class Period>
  2243. void
  2244. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2245. void set_read_timeout(time_t sec, time_t usec = 0);
  2246. template <class Rep, class Period>
  2247. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2248. void set_write_timeout(time_t sec, time_t usec = 0);
  2249. template <class Rep, class Period>
  2250. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2251. void set_max_timeout(time_t msec);
  2252. template <class Rep, class Period>
  2253. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2254. void set_basic_auth(const std::string &username, const std::string &password);
  2255. void set_bearer_token_auth(const std::string &token);
  2256. void set_keep_alive(bool on);
  2257. void set_follow_location(bool on);
  2258. void set_path_encode(bool on);
  2259. void set_compress(bool on);
  2260. void set_decompress(bool on);
  2261. void set_payload_max_length(size_t length);
  2262. void set_interface(const std::string &intf);
  2263. void set_proxy(const std::string &host, int port);
  2264. void set_proxy_basic_auth(const std::string &username,
  2265. const std::string &password);
  2266. void set_proxy_bearer_token_auth(const std::string &token);
  2267. void set_no_proxy(const std::vector<std::string> &patterns);
  2268. void set_logger(Logger logger);
  2269. void set_error_logger(ErrorLogger error_logger);
  2270. private:
  2271. std::unique_ptr<ClientImpl> cli_;
  2272. #ifdef CPPHTTPLIB_SSL_ENABLED
  2273. public:
  2274. void set_digest_auth(const std::string &username,
  2275. const std::string &password);
  2276. void set_proxy_digest_auth(const std::string &username,
  2277. const std::string &password);
  2278. void enable_server_certificate_verification(bool enabled);
  2279. void enable_server_hostname_verification(bool enabled);
  2280. void enable_system_ca(bool enabled);
  2281. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2282. const std::string &ca_cert_dir_path = std::string());
  2283. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2284. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2285. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2286. void set_session_verifier(
  2287. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2288. tls::ctx_t tls_context() const;
  2289. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2290. void enable_windows_certificate_verification(bool enabled);
  2291. #endif
  2292. private:
  2293. bool is_ssl_ = false;
  2294. #endif
  2295. };
  2296. #ifdef CPPHTTPLIB_SSL_ENABLED
  2297. class SSLServer : public Server {
  2298. public:
  2299. SSLServer(const char *cert_path, const char *private_key_path,
  2300. const char *client_ca_cert_file_path = nullptr,
  2301. const char *client_ca_cert_dir_path = nullptr,
  2302. const char *private_key_password = nullptr);
  2303. struct PemMemory {
  2304. const char *cert_pem;
  2305. size_t cert_pem_len;
  2306. const char *key_pem;
  2307. size_t key_pem_len;
  2308. const char *client_ca_pem;
  2309. size_t client_ca_pem_len;
  2310. const char *private_key_password;
  2311. };
  2312. explicit SSLServer(const PemMemory &pem);
  2313. // The callback receives the ctx_t handle which can be cast to the
  2314. // appropriate backend type (SSL_CTX* for OpenSSL,
  2315. // tls::impl::MbedTlsContext* for Mbed TLS)
  2316. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2317. ~SSLServer() override;
  2318. bool is_valid() const override;
  2319. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2320. const char *client_ca_pem = nullptr,
  2321. const char *password = nullptr);
  2322. tls::ctx_t tls_context() const { return ctx_; }
  2323. int ssl_last_error() const { return last_ssl_error_; }
  2324. private:
  2325. bool process_and_close_socket(socket_t sock) override;
  2326. tls::ctx_t ctx_ = nullptr;
  2327. std::mutex ctx_mutex_;
  2328. int last_ssl_error_ = 0;
  2329. };
  2330. class SSLClient final : public ClientImpl {
  2331. public:
  2332. explicit SSLClient(const std::string &host);
  2333. explicit SSLClient(const std::string &host, int port);
  2334. explicit SSLClient(const std::string &host, int port,
  2335. const std::string &client_cert_path,
  2336. const std::string &client_key_path,
  2337. const std::string &private_key_password = std::string());
  2338. struct PemMemory {
  2339. const char *cert_pem;
  2340. size_t cert_pem_len;
  2341. const char *key_pem;
  2342. size_t key_pem_len;
  2343. const char *private_key_password;
  2344. };
  2345. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2346. ~SSLClient() override;
  2347. bool is_valid() const override;
  2348. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2349. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2350. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2351. // Post-handshake session verifier (backend-independent)
  2352. void set_session_verifier(
  2353. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2354. tls::ctx_t tls_context() const { return ctx_; }
  2355. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2356. void enable_windows_certificate_verification(bool enabled);
  2357. #endif
  2358. private:
  2359. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2360. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2361. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2362. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2363. bool
  2364. process_socket(const Socket &socket,
  2365. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2366. std::function<bool(Stream &strm)> callback) override;
  2367. bool is_ssl() const override;
  2368. bool setup_proxy_connection(
  2369. Socket &socket,
  2370. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2371. Response &res, bool &success, Error &error) override;
  2372. bool connect_with_proxy(
  2373. Socket &sock,
  2374. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2375. Response &res, bool &success, Error &error);
  2376. bool initialize_ssl(Socket &socket, Error &error);
  2377. void init_ctx();
  2378. void reset_ctx_on_error();
  2379. bool load_certs();
  2380. tls::ctx_t ctx_ = nullptr;
  2381. std::mutex ctx_mutex_;
  2382. std::once_flag initialize_cert_;
  2383. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2384. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2385. // Used to keep custom CA configuration exclusive with system CA loading.
  2386. bool ca_cert_store_set_ = false;
  2387. long verify_result_ = 0;
  2388. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2389. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2390. bool enable_windows_cert_verification_ = true;
  2391. #endif
  2392. friend class ClientImpl;
  2393. };
  2394. #endif // CPPHTTPLIB_SSL_ENABLED
  2395. namespace detail {
  2396. template <typename T, typename U>
  2397. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2398. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2399. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2400. duration - std::chrono::seconds(sec))
  2401. .count();
  2402. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2403. }
  2404. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2405. return N - 1;
  2406. }
  2407. inline bool is_numeric(const std::string &str) {
  2408. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2409. }
  2410. inline size_t get_header_value_u64(const Headers &headers,
  2411. const std::string &key, size_t def,
  2412. size_t id, bool &is_invalid_value) {
  2413. is_invalid_value = false;
  2414. auto rng = headers.equal_range(key);
  2415. auto it = rng.first;
  2416. std::advance(it, static_cast<ssize_t>(id));
  2417. if (it != rng.second) {
  2418. if (is_numeric(it->second)) {
  2419. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2420. } else {
  2421. is_invalid_value = true;
  2422. }
  2423. }
  2424. return def;
  2425. }
  2426. inline size_t get_header_value_u64(const Headers &headers,
  2427. const std::string &key, size_t def,
  2428. size_t id) {
  2429. auto dummy = false;
  2430. return get_header_value_u64(headers, key, def, id, dummy);
  2431. }
  2432. } // namespace detail
  2433. template <class Rep, class Period>
  2434. inline Server &
  2435. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2436. detail::duration_to_sec_and_usec(
  2437. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2438. return *this;
  2439. }
  2440. template <class Rep, class Period>
  2441. inline Server &
  2442. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2443. detail::duration_to_sec_and_usec(
  2444. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2445. return *this;
  2446. }
  2447. template <class Rep, class Period>
  2448. inline Server &
  2449. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2450. detail::duration_to_sec_and_usec(
  2451. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2452. return *this;
  2453. }
  2454. template <class Rep, class Period>
  2455. inline void ClientImpl::set_connection_timeout(
  2456. const std::chrono::duration<Rep, Period> &duration) {
  2457. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2458. set_connection_timeout(sec, usec);
  2459. });
  2460. }
  2461. template <class Rep, class Period>
  2462. inline void ClientImpl::set_read_timeout(
  2463. const std::chrono::duration<Rep, Period> &duration) {
  2464. detail::duration_to_sec_and_usec(
  2465. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2466. }
  2467. template <class Rep, class Period>
  2468. inline void ClientImpl::set_write_timeout(
  2469. const std::chrono::duration<Rep, Period> &duration) {
  2470. detail::duration_to_sec_and_usec(
  2471. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2472. }
  2473. template <class Rep, class Period>
  2474. inline void ClientImpl::set_max_timeout(
  2475. const std::chrono::duration<Rep, Period> &duration) {
  2476. auto msec =
  2477. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2478. set_max_timeout(msec);
  2479. }
  2480. template <class Rep, class Period>
  2481. inline void Client::set_connection_timeout(
  2482. const std::chrono::duration<Rep, Period> &duration) {
  2483. cli_->set_connection_timeout(duration);
  2484. }
  2485. template <class Rep, class Period>
  2486. inline void
  2487. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2488. cli_->set_read_timeout(duration);
  2489. }
  2490. template <class Rep, class Period>
  2491. inline void
  2492. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2493. cli_->set_write_timeout(duration);
  2494. }
  2495. inline void Client::set_max_timeout(time_t msec) {
  2496. cli_->set_max_timeout(msec);
  2497. }
  2498. template <class Rep, class Period>
  2499. inline void
  2500. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2501. cli_->set_max_timeout(duration);
  2502. }
  2503. /*
  2504. * Forward declarations and types that will be part of the .h file if split into
  2505. * .h + .cc.
  2506. */
  2507. std::string hosted_at(const std::string &hostname);
  2508. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2509. // JavaScript-style URL encoding/decoding functions
  2510. std::string encode_uri_component(const std::string &value);
  2511. std::string encode_uri(const std::string &value);
  2512. std::string decode_uri_component(const std::string &value);
  2513. std::string decode_uri(const std::string &value);
  2514. // RFC 3986 compliant URL component encoding/decoding functions
  2515. std::string encode_path_component(const std::string &component);
  2516. std::string decode_path_component(const std::string &component);
  2517. std::string encode_query_component(const std::string &component,
  2518. bool space_as_plus = true);
  2519. std::string decode_query_component(const std::string &component,
  2520. bool plus_as_space = true);
  2521. std::string sanitize_filename(const std::string &filename);
  2522. std::string append_query_params(const std::string &path, const Params &params);
  2523. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2524. std::pair<std::string, std::string>
  2525. make_basic_authentication_header(const std::string &username,
  2526. const std::string &password,
  2527. bool is_proxy = false);
  2528. namespace detail {
  2529. #if defined(_WIN32)
  2530. inline std::wstring u8string_to_wstring(const char *s) {
  2531. if (!s) { return std::wstring(); }
  2532. auto len = static_cast<int>(strlen(s));
  2533. if (!len) { return std::wstring(); }
  2534. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2535. if (!wlen) { return std::wstring(); }
  2536. std::wstring ws;
  2537. ws.resize(wlen);
  2538. wlen = ::MultiByteToWideChar(
  2539. CP_UTF8, 0, s, len,
  2540. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2541. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2542. return ws;
  2543. }
  2544. #endif
  2545. struct FileStat {
  2546. FileStat(const std::string &path);
  2547. bool is_file() const;
  2548. bool is_dir() const;
  2549. time_t mtime() const;
  2550. size_t size() const;
  2551. private:
  2552. #if defined(_WIN32)
  2553. struct _stat st_;
  2554. #else
  2555. struct stat st_;
  2556. #endif
  2557. int ret_ = -1;
  2558. };
  2559. std::string make_host_and_port_string(const std::string &host, int port,
  2560. bool is_ssl);
  2561. std::string trim_copy(const std::string &s);
  2562. void divide(
  2563. const char *data, std::size_t size, char d,
  2564. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2565. fn);
  2566. void divide(
  2567. const std::string &str, char d,
  2568. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2569. fn);
  2570. void split(const char *b, const char *e, char d,
  2571. std::function<void(const char *, const char *)> fn);
  2572. void split(const char *b, const char *e, char d, size_t m,
  2573. std::function<void(const char *, const char *)> fn);
  2574. bool process_client_socket(
  2575. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2576. time_t write_timeout_sec, time_t write_timeout_usec,
  2577. time_t max_timeout_msec,
  2578. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2579. std::function<bool(Stream &)> callback);
  2580. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2581. int port, int address_family, bool tcp_nodelay,
  2582. bool ipv6_v6only, SocketOptions socket_options,
  2583. time_t connection_timeout_sec,
  2584. time_t connection_timeout_usec,
  2585. time_t read_timeout_sec, time_t read_timeout_usec,
  2586. time_t write_timeout_sec,
  2587. time_t write_timeout_usec,
  2588. const std::string &intf, Error &error);
  2589. const char *get_header_value(const Headers &headers, const std::string &key,
  2590. const char *def, size_t id);
  2591. std::string params_to_query_str(const Params &params);
  2592. void parse_query_text(const char *data, std::size_t size, Params &params);
  2593. void parse_query_text(const std::string &s, Params &params);
  2594. bool parse_multipart_boundary(const std::string &content_type,
  2595. std::string &boundary);
  2596. bool parse_range_header(const std::string &s, Ranges &ranges);
  2597. bool parse_accept_header(const std::string &s,
  2598. std::vector<std::string> &content_types);
  2599. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2600. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2601. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2602. EncodingType encoding_type(const Request &req, const Response &res);
  2603. class BufferStream final : public Stream {
  2604. public:
  2605. BufferStream() = default;
  2606. ~BufferStream() override = default;
  2607. bool is_readable() const override;
  2608. bool wait_readable() const override;
  2609. bool wait_writable() const override;
  2610. ssize_t read(char *ptr, size_t size) override;
  2611. ssize_t write(const char *ptr, size_t size) override;
  2612. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2613. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2614. socket_t socket() const override;
  2615. time_t duration() const override;
  2616. const std::string &get_buffer() const;
  2617. private:
  2618. std::string buffer;
  2619. size_t position = 0;
  2620. };
  2621. class compressor {
  2622. public:
  2623. virtual ~compressor() = default;
  2624. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2625. virtual bool compress(const char *data, size_t data_length, bool last,
  2626. Callback callback) = 0;
  2627. };
  2628. class decompressor {
  2629. public:
  2630. virtual ~decompressor() = default;
  2631. virtual bool is_valid() const = 0;
  2632. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2633. virtual bool decompress(const char *data, size_t data_length,
  2634. Callback callback) = 0;
  2635. };
  2636. class nocompressor final : public compressor {
  2637. public:
  2638. ~nocompressor() override = default;
  2639. bool compress(const char *data, size_t data_length, bool /*last*/,
  2640. Callback callback) override;
  2641. };
  2642. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2643. class gzip_compressor final : public compressor {
  2644. public:
  2645. gzip_compressor();
  2646. ~gzip_compressor() override;
  2647. bool compress(const char *data, size_t data_length, bool last,
  2648. Callback callback) override;
  2649. private:
  2650. bool is_valid_ = false;
  2651. z_stream strm_;
  2652. };
  2653. class gzip_decompressor final : public decompressor {
  2654. public:
  2655. gzip_decompressor();
  2656. ~gzip_decompressor() override;
  2657. bool is_valid() const override;
  2658. bool decompress(const char *data, size_t data_length,
  2659. Callback callback) override;
  2660. private:
  2661. bool is_valid_ = false;
  2662. z_stream strm_;
  2663. };
  2664. #endif
  2665. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2666. class brotli_compressor final : public compressor {
  2667. public:
  2668. brotli_compressor();
  2669. ~brotli_compressor();
  2670. bool compress(const char *data, size_t data_length, bool last,
  2671. Callback callback) override;
  2672. private:
  2673. BrotliEncoderState *state_ = nullptr;
  2674. };
  2675. class brotli_decompressor final : public decompressor {
  2676. public:
  2677. brotli_decompressor();
  2678. ~brotli_decompressor();
  2679. bool is_valid() const override;
  2680. bool decompress(const char *data, size_t data_length,
  2681. Callback callback) override;
  2682. private:
  2683. BrotliDecoderResult decoder_r;
  2684. BrotliDecoderState *decoder_s = nullptr;
  2685. };
  2686. #endif
  2687. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2688. class zstd_compressor : public compressor {
  2689. public:
  2690. zstd_compressor();
  2691. ~zstd_compressor();
  2692. bool compress(const char *data, size_t data_length, bool last,
  2693. Callback callback) override;
  2694. private:
  2695. ZSTD_CCtx *ctx_ = nullptr;
  2696. };
  2697. class zstd_decompressor : public decompressor {
  2698. public:
  2699. zstd_decompressor();
  2700. ~zstd_decompressor();
  2701. bool is_valid() const override;
  2702. bool decompress(const char *data, size_t data_length,
  2703. Callback callback) override;
  2704. private:
  2705. ZSTD_DCtx *ctx_ = nullptr;
  2706. };
  2707. #endif
  2708. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2709. // to store data. The call can set memory on stack for performance.
  2710. class stream_line_reader {
  2711. public:
  2712. stream_line_reader(Stream &strm, char *fixed_buffer,
  2713. size_t fixed_buffer_size);
  2714. const char *ptr() const;
  2715. size_t size() const;
  2716. bool end_with_crlf() const;
  2717. bool getline();
  2718. private:
  2719. void append(char c);
  2720. Stream &strm_;
  2721. char *fixed_buffer_;
  2722. const size_t fixed_buffer_size_;
  2723. size_t fixed_buffer_used_size_ = 0;
  2724. std::string growable_buffer_;
  2725. };
  2726. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2727. const Headers &src_headers);
  2728. struct ChunkedDecoder {
  2729. Stream &strm;
  2730. size_t chunk_remaining = 0;
  2731. bool finished = false;
  2732. char line_buf[64];
  2733. size_t last_chunk_total = 0;
  2734. size_t last_chunk_offset = 0;
  2735. explicit ChunkedDecoder(Stream &s);
  2736. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2737. size_t &out_chunk_total);
  2738. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2739. };
  2740. class mmap {
  2741. public:
  2742. mmap(const char *path);
  2743. ~mmap();
  2744. bool open(const char *path);
  2745. void close();
  2746. bool is_open() const;
  2747. size_t size() const;
  2748. const char *data() const;
  2749. private:
  2750. #if defined(_WIN32)
  2751. HANDLE hFile_ = NULL;
  2752. HANDLE hMapping_ = NULL;
  2753. #else
  2754. int fd_ = -1;
  2755. #endif
  2756. size_t size_ = 0;
  2757. void *addr_ = nullptr;
  2758. bool is_open_empty_file = false;
  2759. };
  2760. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2761. namespace fields {
  2762. bool is_token_char(char c);
  2763. bool is_token(const std::string &s);
  2764. bool is_field_name(const std::string &s);
  2765. bool is_vchar(char c);
  2766. bool is_obs_text(char c);
  2767. bool is_field_vchar(char c);
  2768. bool is_field_content(const std::string &s);
  2769. bool is_field_value(const std::string &s);
  2770. } // namespace fields
  2771. } // namespace detail
  2772. /*
  2773. * TLS Abstraction Layer Declarations
  2774. */
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. // TLS abstraction layer - backend-specific type declarations
  2777. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2778. namespace tls {
  2779. namespace impl {
  2780. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2781. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2782. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2783. struct MbedTlsContext {
  2784. mbedtls_ssl_config conf;
  2785. mbedtls_entropy_context entropy;
  2786. mbedtls_ctr_drbg_context ctr_drbg;
  2787. mbedtls_x509_crt ca_chain;
  2788. mbedtls_x509_crt own_cert;
  2789. mbedtls_pk_context own_key;
  2790. bool is_server = false;
  2791. bool verify_client = false;
  2792. bool has_verify_callback = false;
  2793. MbedTlsContext();
  2794. ~MbedTlsContext();
  2795. MbedTlsContext(const MbedTlsContext &) = delete;
  2796. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2797. };
  2798. } // namespace impl
  2799. } // namespace tls
  2800. #endif
  2801. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2802. namespace tls {
  2803. namespace impl {
  2804. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2805. // This struct is accessible via tls::impl for use in SSL context
  2806. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2807. struct WolfSSLContext {
  2808. WOLFSSL_CTX *ctx = nullptr;
  2809. bool is_server = false;
  2810. bool verify_client = false;
  2811. bool has_verify_callback = false;
  2812. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2813. WolfSSLContext();
  2814. ~WolfSSLContext();
  2815. WolfSSLContext(const WolfSSLContext &) = delete;
  2816. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2817. };
  2818. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2819. struct WolfSSLCAStore {
  2820. std::string pem_data;
  2821. };
  2822. } // namespace impl
  2823. } // namespace tls
  2824. #endif
  2825. #endif // CPPHTTPLIB_SSL_ENABLED
  2826. namespace stream {
  2827. class Result {
  2828. public:
  2829. Result();
  2830. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2831. Result(Result &&other) noexcept;
  2832. Result &operator=(Result &&other) noexcept;
  2833. Result(const Result &) = delete;
  2834. Result &operator=(const Result &) = delete;
  2835. // Response info
  2836. bool is_valid() const;
  2837. explicit operator bool() const;
  2838. int status() const;
  2839. const Headers &headers() const;
  2840. std::string get_header_value(const std::string &key,
  2841. const char *def = "") const;
  2842. bool has_header(const std::string &key) const;
  2843. Error error() const;
  2844. Error read_error() const;
  2845. bool has_read_error() const;
  2846. // Stream reading
  2847. bool next();
  2848. const char *data() const;
  2849. size_t size() const;
  2850. std::string read_all();
  2851. private:
  2852. ClientImpl::StreamHandle handle_;
  2853. std::string buffer_;
  2854. size_t current_size_ = 0;
  2855. size_t chunk_size_;
  2856. bool finished_ = false;
  2857. };
  2858. // GET
  2859. template <typename ClientType>
  2860. inline Result Get(ClientType &cli, const std::string &path,
  2861. size_t chunk_size = 8192) {
  2862. return Result{cli.open_stream("GET", path), chunk_size};
  2863. }
  2864. template <typename ClientType>
  2865. inline Result Get(ClientType &cli, const std::string &path,
  2866. const Headers &headers, size_t chunk_size = 8192) {
  2867. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2868. }
  2869. template <typename ClientType>
  2870. inline Result Get(ClientType &cli, const std::string &path,
  2871. const Params &params, size_t chunk_size = 8192) {
  2872. return Result{cli.open_stream("GET", path, params), chunk_size};
  2873. }
  2874. template <typename ClientType>
  2875. inline Result Get(ClientType &cli, const std::string &path,
  2876. const Params &params, const Headers &headers,
  2877. size_t chunk_size = 8192) {
  2878. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2879. }
  2880. // POST
  2881. template <typename ClientType>
  2882. inline Result Post(ClientType &cli, const std::string &path,
  2883. const std::string &body, const std::string &content_type,
  2884. size_t chunk_size = 8192) {
  2885. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2886. chunk_size};
  2887. }
  2888. template <typename ClientType>
  2889. inline Result Post(ClientType &cli, const std::string &path,
  2890. const Headers &headers, const std::string &body,
  2891. const std::string &content_type, size_t chunk_size = 8192) {
  2892. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2893. chunk_size};
  2894. }
  2895. template <typename ClientType>
  2896. inline Result Post(ClientType &cli, const std::string &path,
  2897. const Params &params, const std::string &body,
  2898. const std::string &content_type, size_t chunk_size = 8192) {
  2899. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2900. chunk_size};
  2901. }
  2902. template <typename ClientType>
  2903. inline Result Post(ClientType &cli, const std::string &path,
  2904. const Params &params, const Headers &headers,
  2905. const std::string &body, const std::string &content_type,
  2906. size_t chunk_size = 8192) {
  2907. return Result{
  2908. cli.open_stream("POST", path, params, headers, body, content_type),
  2909. chunk_size};
  2910. }
  2911. // PUT
  2912. template <typename ClientType>
  2913. inline Result Put(ClientType &cli, const std::string &path,
  2914. const std::string &body, const std::string &content_type,
  2915. size_t chunk_size = 8192) {
  2916. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2917. chunk_size};
  2918. }
  2919. template <typename ClientType>
  2920. inline Result Put(ClientType &cli, const std::string &path,
  2921. const Headers &headers, const std::string &body,
  2922. const std::string &content_type, size_t chunk_size = 8192) {
  2923. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2924. chunk_size};
  2925. }
  2926. template <typename ClientType>
  2927. inline Result Put(ClientType &cli, const std::string &path,
  2928. const Params &params, const std::string &body,
  2929. const std::string &content_type, size_t chunk_size = 8192) {
  2930. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2931. chunk_size};
  2932. }
  2933. template <typename ClientType>
  2934. inline Result Put(ClientType &cli, const std::string &path,
  2935. const Params &params, const Headers &headers,
  2936. const std::string &body, const std::string &content_type,
  2937. size_t chunk_size = 8192) {
  2938. return Result{
  2939. cli.open_stream("PUT", path, params, headers, body, content_type),
  2940. chunk_size};
  2941. }
  2942. // PATCH
  2943. template <typename ClientType>
  2944. inline Result Patch(ClientType &cli, const std::string &path,
  2945. const std::string &body, const std::string &content_type,
  2946. size_t chunk_size = 8192) {
  2947. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2948. chunk_size};
  2949. }
  2950. template <typename ClientType>
  2951. inline Result Patch(ClientType &cli, const std::string &path,
  2952. const Headers &headers, const std::string &body,
  2953. const std::string &content_type, size_t chunk_size = 8192) {
  2954. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2955. chunk_size};
  2956. }
  2957. template <typename ClientType>
  2958. inline Result Patch(ClientType &cli, const std::string &path,
  2959. const Params &params, const std::string &body,
  2960. const std::string &content_type, size_t chunk_size = 8192) {
  2961. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2962. chunk_size};
  2963. }
  2964. template <typename ClientType>
  2965. inline Result Patch(ClientType &cli, const std::string &path,
  2966. const Params &params, const Headers &headers,
  2967. const std::string &body, const std::string &content_type,
  2968. size_t chunk_size = 8192) {
  2969. return Result{
  2970. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2971. chunk_size};
  2972. }
  2973. // DELETE
  2974. template <typename ClientType>
  2975. inline Result Delete(ClientType &cli, const std::string &path,
  2976. size_t chunk_size = 8192) {
  2977. return Result{cli.open_stream("DELETE", path), chunk_size};
  2978. }
  2979. template <typename ClientType>
  2980. inline Result Delete(ClientType &cli, const std::string &path,
  2981. const Headers &headers, size_t chunk_size = 8192) {
  2982. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2983. }
  2984. template <typename ClientType>
  2985. inline Result Delete(ClientType &cli, const std::string &path,
  2986. const std::string &body, const std::string &content_type,
  2987. size_t chunk_size = 8192) {
  2988. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2989. chunk_size};
  2990. }
  2991. template <typename ClientType>
  2992. inline Result Delete(ClientType &cli, const std::string &path,
  2993. const Headers &headers, const std::string &body,
  2994. const std::string &content_type,
  2995. size_t chunk_size = 8192) {
  2996. return Result{
  2997. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2998. chunk_size};
  2999. }
  3000. template <typename ClientType>
  3001. inline Result Delete(ClientType &cli, const std::string &path,
  3002. const Params &params, size_t chunk_size = 8192) {
  3003. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3004. }
  3005. template <typename ClientType>
  3006. inline Result Delete(ClientType &cli, const std::string &path,
  3007. const Params &params, const Headers &headers,
  3008. size_t chunk_size = 8192) {
  3009. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3010. }
  3011. template <typename ClientType>
  3012. inline Result Delete(ClientType &cli, const std::string &path,
  3013. const Params &params, const std::string &body,
  3014. const std::string &content_type,
  3015. size_t chunk_size = 8192) {
  3016. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3017. chunk_size};
  3018. }
  3019. template <typename ClientType>
  3020. inline Result Delete(ClientType &cli, const std::string &path,
  3021. const Params &params, const Headers &headers,
  3022. const std::string &body, const std::string &content_type,
  3023. size_t chunk_size = 8192) {
  3024. return Result{
  3025. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3026. chunk_size};
  3027. }
  3028. // HEAD
  3029. template <typename ClientType>
  3030. inline Result Head(ClientType &cli, const std::string &path,
  3031. size_t chunk_size = 8192) {
  3032. return Result{cli.open_stream("HEAD", path), chunk_size};
  3033. }
  3034. template <typename ClientType>
  3035. inline Result Head(ClientType &cli, const std::string &path,
  3036. const Headers &headers, size_t chunk_size = 8192) {
  3037. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3038. }
  3039. template <typename ClientType>
  3040. inline Result Head(ClientType &cli, const std::string &path,
  3041. const Params &params, size_t chunk_size = 8192) {
  3042. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3043. }
  3044. template <typename ClientType>
  3045. inline Result Head(ClientType &cli, const std::string &path,
  3046. const Params &params, const Headers &headers,
  3047. size_t chunk_size = 8192) {
  3048. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3049. }
  3050. // OPTIONS
  3051. template <typename ClientType>
  3052. inline Result Options(ClientType &cli, const std::string &path,
  3053. size_t chunk_size = 8192) {
  3054. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3055. }
  3056. template <typename ClientType>
  3057. inline Result Options(ClientType &cli, const std::string &path,
  3058. const Headers &headers, size_t chunk_size = 8192) {
  3059. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3060. }
  3061. template <typename ClientType>
  3062. inline Result Options(ClientType &cli, const std::string &path,
  3063. const Params &params, size_t chunk_size = 8192) {
  3064. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3065. }
  3066. template <typename ClientType>
  3067. inline Result Options(ClientType &cli, const std::string &path,
  3068. const Params &params, const Headers &headers,
  3069. size_t chunk_size = 8192) {
  3070. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3071. }
  3072. } // namespace stream
  3073. namespace sse {
  3074. struct SSEMessage {
  3075. std::string event; // Event type (default: "message")
  3076. std::string data; // Event payload
  3077. std::string id; // Event ID for Last-Event-ID header
  3078. SSEMessage();
  3079. void clear();
  3080. };
  3081. class SSEClient {
  3082. public:
  3083. using MessageHandler = std::function<void(const SSEMessage &)>;
  3084. using ErrorHandler = std::function<void(Error)>;
  3085. using OpenHandler = std::function<void()>;
  3086. SSEClient(Client &client, const std::string &path);
  3087. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3088. ~SSEClient();
  3089. SSEClient(const SSEClient &) = delete;
  3090. SSEClient &operator=(const SSEClient &) = delete;
  3091. // Event handlers
  3092. SSEClient &on_message(MessageHandler handler);
  3093. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3094. SSEClient &on_open(OpenHandler handler);
  3095. SSEClient &on_error(ErrorHandler handler);
  3096. SSEClient &set_reconnect_interval(int ms);
  3097. SSEClient &set_max_reconnect_attempts(int n);
  3098. // Update headers (thread-safe)
  3099. SSEClient &set_headers(const Headers &headers);
  3100. // State accessors
  3101. bool is_connected() const;
  3102. const std::string &last_event_id() const;
  3103. // Blocking start - runs event loop with auto-reconnect
  3104. void start();
  3105. // Non-blocking start - runs in background thread
  3106. void start_async();
  3107. // Stop the client (thread-safe)
  3108. void stop();
  3109. private:
  3110. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3111. void run_event_loop();
  3112. void dispatch_event(const SSEMessage &msg);
  3113. bool should_reconnect(int count) const;
  3114. void wait_for_reconnect();
  3115. // Client and path
  3116. Client &client_;
  3117. std::string path_;
  3118. Headers headers_;
  3119. mutable std::mutex headers_mutex_;
  3120. // Callbacks
  3121. MessageHandler on_message_;
  3122. std::map<std::string, MessageHandler> event_handlers_;
  3123. OpenHandler on_open_;
  3124. ErrorHandler on_error_;
  3125. // Configuration
  3126. int reconnect_interval_ms_ = 3000;
  3127. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3128. // State
  3129. std::atomic<bool> running_{false};
  3130. std::atomic<bool> connected_{false};
  3131. std::string last_event_id_;
  3132. // Async support
  3133. std::thread async_thread_;
  3134. };
  3135. } // namespace sse
  3136. namespace ws {
  3137. enum class Opcode : uint8_t {
  3138. Continuation = 0x0,
  3139. Text = 0x1,
  3140. Binary = 0x2,
  3141. Close = 0x8,
  3142. Ping = 0x9,
  3143. Pong = 0xA,
  3144. };
  3145. enum class CloseStatus : uint16_t {
  3146. Normal = 1000,
  3147. GoingAway = 1001,
  3148. ProtocolError = 1002,
  3149. UnsupportedData = 1003,
  3150. NoStatus = 1005,
  3151. Abnormal = 1006,
  3152. InvalidPayload = 1007,
  3153. PolicyViolation = 1008,
  3154. MessageTooBig = 1009,
  3155. MandatoryExtension = 1010,
  3156. InternalError = 1011,
  3157. };
  3158. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3159. class WebSocket {
  3160. public:
  3161. WebSocket(const WebSocket &) = delete;
  3162. WebSocket &operator=(const WebSocket &) = delete;
  3163. ~WebSocket();
  3164. ReadResult read(std::string &msg);
  3165. bool send(const std::string &data);
  3166. bool send(const char *data, size_t len);
  3167. void close(CloseStatus status = CloseStatus::Normal,
  3168. const std::string &reason = "");
  3169. const Request &request() const;
  3170. bool is_open() const;
  3171. private:
  3172. friend class httplib::Server;
  3173. friend class WebSocketClient;
  3174. WebSocket(
  3175. Stream &strm, const Request &req, bool is_server,
  3176. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3177. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3178. : strm_(strm), req_(req), is_server_(is_server),
  3179. ping_interval_sec_(ping_interval_sec),
  3180. max_missed_pongs_(max_missed_pongs) {
  3181. start_heartbeat();
  3182. }
  3183. WebSocket(
  3184. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3185. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3186. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3187. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3188. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3189. max_missed_pongs_(max_missed_pongs) {
  3190. start_heartbeat();
  3191. }
  3192. void start_heartbeat();
  3193. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3194. Stream &strm_;
  3195. std::unique_ptr<Stream> owned_strm_;
  3196. Request req_;
  3197. bool is_server_;
  3198. time_t ping_interval_sec_;
  3199. int max_missed_pongs_;
  3200. int unacked_pings_ = 0;
  3201. std::atomic<bool> closed_{false};
  3202. std::mutex write_mutex_;
  3203. std::thread ping_thread_;
  3204. std::mutex ping_mutex_;
  3205. std::condition_variable ping_cv_;
  3206. };
  3207. class WebSocketClient {
  3208. public:
  3209. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3210. const Headers &headers = {});
  3211. ~WebSocketClient();
  3212. WebSocketClient(const WebSocketClient &) = delete;
  3213. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3214. bool is_valid() const;
  3215. bool connect();
  3216. ReadResult read(std::string &msg);
  3217. bool send(const std::string &data);
  3218. bool send(const char *data, size_t len);
  3219. void close(CloseStatus status = CloseStatus::Normal,
  3220. const std::string &reason = "");
  3221. bool is_open() const;
  3222. const std::string &subprotocol() const;
  3223. void set_read_timeout(time_t sec, time_t usec = 0);
  3224. void set_write_timeout(time_t sec, time_t usec = 0);
  3225. void set_websocket_ping_interval(time_t sec);
  3226. void set_websocket_max_missed_pongs(int count);
  3227. void set_tcp_nodelay(bool on);
  3228. void set_address_family(int family);
  3229. void set_ipv6_v6only(bool on);
  3230. void set_socket_options(SocketOptions socket_options);
  3231. void set_connection_timeout(time_t sec, time_t usec = 0);
  3232. void set_interface(const std::string &intf);
  3233. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. void set_ca_cert_path(const std::string &path);
  3236. void set_ca_cert_store(tls::ca_store_t store);
  3237. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3238. void enable_server_certificate_verification(bool enabled);
  3239. void enable_system_ca(bool enabled);
  3240. #endif
  3241. private:
  3242. void shutdown_and_close();
  3243. bool create_stream(std::unique_ptr<Stream> &strm);
  3244. std::string host_;
  3245. int port_;
  3246. std::string path_;
  3247. Headers headers_;
  3248. std::string subprotocol_;
  3249. bool is_valid_ = false;
  3250. socket_t sock_ = INVALID_SOCKET;
  3251. std::unique_ptr<WebSocket> ws_;
  3252. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3253. time_t read_timeout_usec_ = 0;
  3254. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3255. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3256. time_t websocket_ping_interval_sec_ =
  3257. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3258. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3259. int address_family_ = AF_UNSPEC;
  3260. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3261. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3262. SocketOptions socket_options_ = nullptr;
  3263. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3264. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3265. std::string interface_;
  3266. // Hostname-IP map
  3267. std::map<std::string, std::string> addr_map_;
  3268. #ifdef CPPHTTPLIB_SSL_ENABLED
  3269. bool is_ssl_ = false;
  3270. tls::ctx_t tls_ctx_ = nullptr;
  3271. tls::session_t tls_session_ = nullptr;
  3272. std::string ca_cert_file_path_;
  3273. bool custom_ca_loaded_ = false;
  3274. bool certs_loaded_ = false;
  3275. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3276. bool server_certificate_verification_ = true;
  3277. #endif
  3278. };
  3279. namespace impl {
  3280. bool is_valid_utf8(const std::string &s);
  3281. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3282. bool &fin, bool expect_masked, size_t max_len);
  3283. } // namespace impl
  3284. } // namespace ws
  3285. // ----------------------------------------------------------------------------
  3286. /*
  3287. * Implementation that will be part of the .cc file if split into .h + .cc.
  3288. */
  3289. namespace stream {
  3290. // stream::Result implementations
  3291. inline Result::Result() : chunk_size_(8192) {}
  3292. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3293. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3294. inline Result::Result(Result &&other) noexcept
  3295. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3296. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3297. finished_(other.finished_) {
  3298. other.current_size_ = 0;
  3299. other.finished_ = true;
  3300. }
  3301. inline Result &Result::operator=(Result &&other) noexcept {
  3302. if (this != &other) {
  3303. handle_ = std::move(other.handle_);
  3304. buffer_ = std::move(other.buffer_);
  3305. current_size_ = other.current_size_;
  3306. chunk_size_ = other.chunk_size_;
  3307. finished_ = other.finished_;
  3308. other.current_size_ = 0;
  3309. other.finished_ = true;
  3310. }
  3311. return *this;
  3312. }
  3313. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3314. inline Result::operator bool() const { return is_valid(); }
  3315. inline int Result::status() const {
  3316. return handle_.response ? handle_.response->status : -1;
  3317. }
  3318. inline const Headers &Result::headers() const {
  3319. static const Headers empty_headers;
  3320. return handle_.response ? handle_.response->headers : empty_headers;
  3321. }
  3322. inline std::string Result::get_header_value(const std::string &key,
  3323. const char *def) const {
  3324. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3325. }
  3326. inline bool Result::has_header(const std::string &key) const {
  3327. return handle_.response ? handle_.response->has_header(key) : false;
  3328. }
  3329. inline Error Result::error() const { return handle_.error; }
  3330. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3331. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3332. inline bool Result::next() {
  3333. if (!handle_.is_valid() || finished_) { return false; }
  3334. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3335. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3336. if (n > 0) {
  3337. current_size_ = static_cast<size_t>(n);
  3338. return true;
  3339. }
  3340. current_size_ = 0;
  3341. finished_ = true;
  3342. return false;
  3343. }
  3344. inline const char *Result::data() const { return buffer_.data(); }
  3345. inline size_t Result::size() const { return current_size_; }
  3346. inline std::string Result::read_all() {
  3347. std::string result;
  3348. while (next()) {
  3349. result.append(data(), size());
  3350. }
  3351. return result;
  3352. }
  3353. } // namespace stream
  3354. namespace sse {
  3355. // SSEMessage implementations
  3356. inline SSEMessage::SSEMessage() : event("message") {}
  3357. inline void SSEMessage::clear() {
  3358. event = "message";
  3359. data.clear();
  3360. id.clear();
  3361. }
  3362. // SSEClient implementations
  3363. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3364. : client_(client), path_(path) {}
  3365. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3366. const Headers &headers)
  3367. : client_(client), path_(path), headers_(headers) {}
  3368. inline SSEClient::~SSEClient() { stop(); }
  3369. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3370. on_message_ = std::move(handler);
  3371. return *this;
  3372. }
  3373. inline SSEClient &SSEClient::on_event(const std::string &type,
  3374. MessageHandler handler) {
  3375. event_handlers_[type] = std::move(handler);
  3376. return *this;
  3377. }
  3378. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3379. on_open_ = std::move(handler);
  3380. return *this;
  3381. }
  3382. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3383. on_error_ = std::move(handler);
  3384. return *this;
  3385. }
  3386. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3387. reconnect_interval_ms_ = ms;
  3388. return *this;
  3389. }
  3390. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3391. max_reconnect_attempts_ = n;
  3392. return *this;
  3393. }
  3394. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3395. std::lock_guard<std::mutex> lock(headers_mutex_);
  3396. headers_ = headers;
  3397. return *this;
  3398. }
  3399. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3400. inline const std::string &SSEClient::last_event_id() const {
  3401. return last_event_id_;
  3402. }
  3403. inline void SSEClient::start() {
  3404. running_.store(true);
  3405. run_event_loop();
  3406. }
  3407. inline void SSEClient::start_async() {
  3408. running_.store(true);
  3409. async_thread_ = std::thread([this]() { run_event_loop(); });
  3410. }
  3411. inline void SSEClient::stop() {
  3412. running_.store(false);
  3413. client_.stop(); // Cancel any pending operations
  3414. if (async_thread_.joinable()) { async_thread_.join(); }
  3415. }
  3416. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3417. int &retry_ms) {
  3418. // Blank line signals end of event
  3419. if (line.empty() || line == "\r") { return true; }
  3420. // Lines starting with ':' are comments (ignored)
  3421. if (!line.empty() && line[0] == ':') { return false; }
  3422. // Find the colon separator
  3423. auto colon_pos = line.find(':');
  3424. if (colon_pos == std::string::npos) {
  3425. // Line with no colon is treated as field name with empty value
  3426. return false;
  3427. }
  3428. auto field = line.substr(0, colon_pos);
  3429. std::string value;
  3430. // Value starts after colon, skip optional single space
  3431. if (colon_pos + 1 < line.size()) {
  3432. auto value_start = colon_pos + 1;
  3433. if (line[value_start] == ' ') { value_start++; }
  3434. value = line.substr(value_start);
  3435. // Remove trailing \r if present
  3436. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3437. }
  3438. // Handle known fields
  3439. if (field == "event") {
  3440. msg.event = value;
  3441. } else if (field == "data") {
  3442. // Multiple data lines are concatenated with newlines
  3443. if (!msg.data.empty()) { msg.data += "\n"; }
  3444. msg.data += value;
  3445. } else if (field == "id") {
  3446. // Empty id is valid (clears the last event ID)
  3447. msg.id = value;
  3448. } else if (field == "retry") {
  3449. // Parse retry interval in milliseconds
  3450. {
  3451. int v = 0;
  3452. auto res =
  3453. detail::from_chars(value.data(), value.data() + value.size(), v);
  3454. if (res.ec == std::errc{}) { retry_ms = v; }
  3455. }
  3456. }
  3457. // Unknown fields are ignored per SSE spec
  3458. return false;
  3459. }
  3460. inline void SSEClient::run_event_loop() {
  3461. auto reconnect_count = 0;
  3462. while (running_.load()) {
  3463. // Build headers, including Last-Event-ID if we have one
  3464. Headers request_headers;
  3465. {
  3466. std::lock_guard<std::mutex> lock(headers_mutex_);
  3467. request_headers = headers_;
  3468. }
  3469. if (!last_event_id_.empty()) {
  3470. request_headers.emplace("Last-Event-ID", last_event_id_);
  3471. }
  3472. // Open streaming connection
  3473. auto result = stream::Get(client_, path_, request_headers);
  3474. // Connection error handling
  3475. if (!result) {
  3476. connected_.store(false);
  3477. if (on_error_) { on_error_(result.error()); }
  3478. if (!should_reconnect(reconnect_count)) { break; }
  3479. wait_for_reconnect();
  3480. reconnect_count++;
  3481. continue;
  3482. }
  3483. if (result.status() != StatusCode::OK_200) {
  3484. connected_.store(false);
  3485. if (on_error_) { on_error_(Error::Connection); }
  3486. // For certain errors, don't reconnect.
  3487. // Note: 401 is intentionally absent so that handlers can refresh
  3488. // credentials via set_headers() and let the client reconnect.
  3489. if (result.status() == StatusCode::NoContent_204 ||
  3490. result.status() == StatusCode::NotFound_404 ||
  3491. result.status() == StatusCode::Forbidden_403) {
  3492. break;
  3493. }
  3494. if (!should_reconnect(reconnect_count)) { break; }
  3495. wait_for_reconnect();
  3496. reconnect_count++;
  3497. continue;
  3498. }
  3499. // Connection successful
  3500. connected_.store(true);
  3501. reconnect_count = 0;
  3502. if (on_open_) { on_open_(); }
  3503. // Event receiving loop
  3504. std::string buffer;
  3505. SSEMessage current_msg;
  3506. while (running_.load() && result.next()) {
  3507. buffer.append(result.data(), result.size());
  3508. // Process complete lines in the buffer
  3509. size_t line_start = 0;
  3510. size_t newline_pos;
  3511. while ((newline_pos = buffer.find('\n', line_start)) !=
  3512. std::string::npos) {
  3513. auto line = buffer.substr(line_start, newline_pos - line_start);
  3514. line_start = newline_pos + 1;
  3515. // Parse the line and check if event is complete
  3516. auto event_complete =
  3517. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3518. if (event_complete && !current_msg.data.empty()) {
  3519. // Update last_event_id for reconnection
  3520. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3521. // Dispatch event to appropriate handler
  3522. dispatch_event(current_msg);
  3523. current_msg.clear();
  3524. }
  3525. }
  3526. // Keep unprocessed data in buffer
  3527. buffer.erase(0, line_start);
  3528. }
  3529. // Connection ended
  3530. connected_.store(false);
  3531. if (!running_.load()) { break; }
  3532. // Check for read errors
  3533. if (result.has_read_error()) {
  3534. if (on_error_) { on_error_(result.read_error()); }
  3535. }
  3536. if (!should_reconnect(reconnect_count)) { break; }
  3537. wait_for_reconnect();
  3538. reconnect_count++;
  3539. }
  3540. connected_.store(false);
  3541. }
  3542. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3543. // Check for specific event type handler first
  3544. auto it = event_handlers_.find(msg.event);
  3545. if (it != event_handlers_.end()) {
  3546. it->second(msg);
  3547. return;
  3548. }
  3549. // Fall back to generic message handler
  3550. if (on_message_) { on_message_(msg); }
  3551. }
  3552. inline bool SSEClient::should_reconnect(int count) const {
  3553. if (!running_.load()) { return false; }
  3554. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3555. return count < max_reconnect_attempts_;
  3556. }
  3557. inline void SSEClient::wait_for_reconnect() {
  3558. // Use small increments to check running_ flag frequently
  3559. auto waited = 0;
  3560. while (running_.load() && waited < reconnect_interval_ms_) {
  3561. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3562. waited += 100;
  3563. }
  3564. }
  3565. } // namespace sse
  3566. #ifdef CPPHTTPLIB_SSL_ENABLED
  3567. /*
  3568. * TLS abstraction layer - internal function declarations
  3569. * These are implementation details and not part of the public API.
  3570. */
  3571. namespace tls {
  3572. // Client context
  3573. ctx_t create_client_context();
  3574. void free_context(ctx_t ctx);
  3575. bool set_min_version(ctx_t ctx, Version version);
  3576. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3577. bool load_ca_file(ctx_t ctx, const char *file_path);
  3578. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3579. bool load_system_certs(ctx_t ctx);
  3580. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3581. const char *password);
  3582. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3583. const char *key_path, const char *password);
  3584. // Server context
  3585. ctx_t create_server_context();
  3586. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3587. const char *password);
  3588. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3589. const char *key_path, const char *password);
  3590. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3591. void set_verify_client(ctx_t ctx, bool require);
  3592. // Session management
  3593. session_t create_session(ctx_t ctx, socket_t sock);
  3594. void free_session(session_t session);
  3595. bool set_sni(session_t session, const char *hostname);
  3596. bool set_hostname(session_t session, const char *hostname);
  3597. // Handshake (non-blocking capable)
  3598. TlsError connect(session_t session);
  3599. TlsError accept(session_t session);
  3600. // Handshake with timeout (blocking until timeout)
  3601. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3602. time_t timeout_usec, TlsError *err);
  3603. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3604. time_t timeout_usec, TlsError *err);
  3605. // I/O (non-blocking capable)
  3606. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3607. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3608. int pending(const_session_t session);
  3609. void shutdown(session_t session, bool graceful);
  3610. // Connection state
  3611. bool is_peer_closed(session_t session, socket_t sock);
  3612. // Certificate verification
  3613. cert_t get_peer_cert(const_session_t session);
  3614. void free_cert(cert_t cert);
  3615. bool verify_hostname(cert_t cert, const char *hostname);
  3616. uint64_t hostname_mismatch_code();
  3617. long get_verify_result(const_session_t session);
  3618. // Certificate introspection
  3619. std::string get_cert_subject_cn(cert_t cert);
  3620. std::string get_cert_issuer_name(cert_t cert);
  3621. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3622. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3623. std::string get_cert_serial(cert_t cert);
  3624. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3625. const char *get_sni(const_session_t session);
  3626. // CA store management
  3627. ca_store_t create_ca_store(const char *pem, size_t len);
  3628. void free_ca_store(ca_store_t store);
  3629. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3630. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3631. std::vector<std::string> get_ca_names(ctx_t ctx);
  3632. // Dynamic certificate update (for servers)
  3633. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3634. const char *password);
  3635. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3636. // Certificate verification callback
  3637. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3638. long get_verify_error(const_session_t session);
  3639. std::string verify_error_string(long error_code);
  3640. // TlsError information
  3641. uint64_t peek_error();
  3642. uint64_t get_error();
  3643. std::string error_string(uint64_t code);
  3644. } // namespace tls
  3645. #endif // CPPHTTPLIB_SSL_ENABLED
  3646. /*
  3647. * Group 1: detail namespace - Non-SSL utilities
  3648. */
  3649. namespace detail {
  3650. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3651. const void *optval, socklen_t optlen) {
  3652. return setsockopt(sock, level, optname,
  3653. #ifdef _WIN32
  3654. reinterpret_cast<const char *>(optval),
  3655. #else
  3656. optval,
  3657. #endif
  3658. optlen) == 0;
  3659. }
  3660. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3661. time_t sec, time_t usec) {
  3662. #ifdef _WIN32
  3663. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3664. #else
  3665. timeval timeout;
  3666. timeout.tv_sec = static_cast<long>(sec);
  3667. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3668. #endif
  3669. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3670. }
  3671. inline bool is_hex(char c, int &v) {
  3672. if (is_ascii_digit(c)) {
  3673. v = c - '0';
  3674. return true;
  3675. } else if ('A' <= c && c <= 'F') {
  3676. v = c - 'A' + 10;
  3677. return true;
  3678. } else if ('a' <= c && c <= 'f') {
  3679. v = c - 'a' + 10;
  3680. return true;
  3681. }
  3682. return false;
  3683. }
  3684. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3685. int &val) {
  3686. if (i >= s.size()) { return false; }
  3687. val = 0;
  3688. for (; cnt; i++, cnt--) {
  3689. if (!s[i]) { return false; }
  3690. auto v = 0;
  3691. if (is_hex(s[i], v)) {
  3692. val = val * 16 + v;
  3693. } else {
  3694. return false;
  3695. }
  3696. }
  3697. return true;
  3698. }
  3699. inline std::string from_i_to_hex(size_t n) {
  3700. static const auto charset = "0123456789abcdef";
  3701. std::string ret;
  3702. do {
  3703. ret = charset[n & 15] + ret;
  3704. n >>= 4;
  3705. } while (n > 0);
  3706. return ret;
  3707. }
  3708. inline std::string compute_etag(const FileStat &fs) {
  3709. if (!fs.is_file()) { return std::string(); }
  3710. // If mtime cannot be determined (negative value indicates an error
  3711. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3712. // value like 0 could collide with a real file that legitimately has
  3713. // mtime == 0 (epoch) and lead to misleading validators.
  3714. auto mtime_raw = fs.mtime();
  3715. if (mtime_raw < 0) { return std::string(); }
  3716. auto mtime = static_cast<size_t>(mtime_raw);
  3717. auto size = fs.size();
  3718. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3719. from_i_to_hex(size) + "\"";
  3720. }
  3721. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3722. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3723. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3724. inline std::string file_mtime_to_http_date(time_t mtime) {
  3725. if (mtime < 0) { return std::string(); }
  3726. struct tm tm_buf;
  3727. #ifdef _WIN32
  3728. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3729. #else
  3730. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3731. #endif
  3732. char buf[64];
  3733. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3734. return std::string();
  3735. }
  3736. return std::string(buf);
  3737. }
  3738. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3739. inline time_t parse_http_date(const std::string &date_str) {
  3740. struct tm tm_buf;
  3741. // Create a classic locale object once for all parsing attempts
  3742. const std::locale classic_locale = std::locale::classic();
  3743. // Try to parse using std::get_time (C++11, cross-platform)
  3744. auto try_parse = [&](const char *fmt) -> bool {
  3745. std::istringstream ss(date_str);
  3746. ss.imbue(classic_locale);
  3747. memset(&tm_buf, 0, sizeof(tm_buf));
  3748. ss >> std::get_time(&tm_buf, fmt);
  3749. return !ss.fail();
  3750. };
  3751. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3752. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3753. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3754. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3755. // asctime format: "Sun Nov 6 08:49:37 1994"
  3756. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3757. return static_cast<time_t>(-1);
  3758. }
  3759. }
  3760. }
  3761. #ifdef _WIN32
  3762. return _mkgmtime(&tm_buf);
  3763. #elif defined _AIX
  3764. return mktime(&tm_buf);
  3765. #else
  3766. return timegm(&tm_buf);
  3767. #endif
  3768. }
  3769. inline bool is_weak_etag(const std::string &s) {
  3770. // Check if the string is a weak ETag (starts with 'W/"')
  3771. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3772. }
  3773. inline bool is_strong_etag(const std::string &s) {
  3774. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3775. // chars)
  3776. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3777. }
  3778. inline size_t to_utf8(int code, char *buff) {
  3779. if (code < 0x0080) {
  3780. buff[0] = static_cast<char>(code & 0x7F);
  3781. return 1;
  3782. } else if (code < 0x0800) {
  3783. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3784. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3785. return 2;
  3786. } else if (code < 0xD800) {
  3787. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3788. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3789. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3790. return 3;
  3791. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3792. return 0;
  3793. } else if (code < 0x10000) {
  3794. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3795. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3796. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3797. return 3;
  3798. } else if (code < 0x110000) {
  3799. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3800. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3801. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3802. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3803. return 4;
  3804. }
  3805. // NOTREACHED
  3806. return 0;
  3807. }
  3808. } // namespace detail
  3809. namespace ws {
  3810. namespace impl {
  3811. inline bool is_valid_utf8(const std::string &s) {
  3812. size_t i = 0;
  3813. auto n = s.size();
  3814. while (i < n) {
  3815. auto c = static_cast<unsigned char>(s[i]);
  3816. size_t len;
  3817. uint32_t cp;
  3818. if (c < 0x80) {
  3819. i++;
  3820. continue;
  3821. } else if ((c & 0xE0) == 0xC0) {
  3822. len = 2;
  3823. cp = c & 0x1F;
  3824. } else if ((c & 0xF0) == 0xE0) {
  3825. len = 3;
  3826. cp = c & 0x0F;
  3827. } else if ((c & 0xF8) == 0xF0) {
  3828. len = 4;
  3829. cp = c & 0x07;
  3830. } else {
  3831. return false;
  3832. }
  3833. if (i + len > n) { return false; }
  3834. for (size_t j = 1; j < len; j++) {
  3835. auto b = static_cast<unsigned char>(s[i + j]);
  3836. if ((b & 0xC0) != 0x80) { return false; }
  3837. cp = (cp << 6) | (b & 0x3F);
  3838. }
  3839. // Overlong encoding check
  3840. if (len == 2 && cp < 0x80) { return false; }
  3841. if (len == 3 && cp < 0x800) { return false; }
  3842. if (len == 4 && cp < 0x10000) { return false; }
  3843. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3844. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3845. if (cp > 0x10FFFF) { return false; }
  3846. i += len;
  3847. }
  3848. return true;
  3849. }
  3850. } // namespace impl
  3851. } // namespace ws
  3852. namespace detail {
  3853. // NOTE: This code came up with the following stackoverflow post:
  3854. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3855. inline std::string base64_encode(const std::string &in) {
  3856. static const auto lookup =
  3857. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3858. std::string out;
  3859. out.reserve(in.size());
  3860. // Unsigned: the accumulator is never masked, so with a signed int the
  3861. // `val << 8` below overflows once enough bytes are folded in (undefined
  3862. // behaviour before C++20). Only the low bits are ever emitted, so the
  3863. // wrap-around of an unsigned accumulator does not affect the output.
  3864. uint32_t val = 0;
  3865. auto valb = -6;
  3866. for (auto c : in) {
  3867. val = (val << 8) + static_cast<uint8_t>(c);
  3868. valb += 8;
  3869. while (valb >= 0) {
  3870. out.push_back(lookup[(val >> valb) & 0x3F]);
  3871. valb -= 6;
  3872. }
  3873. }
  3874. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3875. while (out.size() % 4) {
  3876. out.push_back('=');
  3877. }
  3878. return out;
  3879. }
  3880. inline std::string sha1(const std::string &input) {
  3881. // RFC 3174 SHA-1 implementation
  3882. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3883. return (x << n) | (x >> (32 - n));
  3884. };
  3885. uint32_t h0 = 0x67452301;
  3886. uint32_t h1 = 0xEFCDAB89;
  3887. uint32_t h2 = 0x98BADCFE;
  3888. uint32_t h3 = 0x10325476;
  3889. uint32_t h4 = 0xC3D2E1F0;
  3890. // Pre-processing: adding padding bits
  3891. std::string msg = input;
  3892. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3893. msg.push_back(static_cast<char>(0x80u));
  3894. while (msg.size() % 64 != 56) {
  3895. msg.push_back(0);
  3896. }
  3897. // Append original length in bits as 64-bit big-endian
  3898. for (int i = 56; i >= 0; i -= 8) {
  3899. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3900. }
  3901. // Process each 512-bit chunk
  3902. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3903. uint32_t w[80];
  3904. for (size_t i = 0; i < 16; i++) {
  3905. w[i] =
  3906. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3907. << 24) |
  3908. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3909. << 16) |
  3910. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3911. << 8) |
  3912. (static_cast<uint32_t>(
  3913. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3914. }
  3915. for (int i = 16; i < 80; i++) {
  3916. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3917. }
  3918. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3919. for (int i = 0; i < 80; i++) {
  3920. uint32_t f, k;
  3921. if (i < 20) {
  3922. f = (b & c) | ((~b) & d);
  3923. k = 0x5A827999;
  3924. } else if (i < 40) {
  3925. f = b ^ c ^ d;
  3926. k = 0x6ED9EBA1;
  3927. } else if (i < 60) {
  3928. f = (b & c) | (b & d) | (c & d);
  3929. k = 0x8F1BBCDC;
  3930. } else {
  3931. f = b ^ c ^ d;
  3932. k = 0xCA62C1D6;
  3933. }
  3934. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3935. e = d;
  3936. d = c;
  3937. c = left_rotate(b, 30);
  3938. b = a;
  3939. a = temp;
  3940. }
  3941. h0 += a;
  3942. h1 += b;
  3943. h2 += c;
  3944. h3 += d;
  3945. h4 += e;
  3946. }
  3947. // Produce the final hash as a 20-byte binary string
  3948. std::string hash(20, '\0');
  3949. for (size_t i = 0; i < 4; i++) {
  3950. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3951. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3952. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3953. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3954. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3955. }
  3956. return hash;
  3957. }
  3958. inline std::string websocket_accept_key(const std::string &client_key) {
  3959. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3960. return base64_encode(sha1(client_key + magic));
  3961. }
  3962. inline bool is_websocket_upgrade(const Request &req) {
  3963. if (req.method != "GET") { return false; }
  3964. // Check Upgrade: websocket (case-insensitive)
  3965. auto upgrade_it = req.headers.find("Upgrade");
  3966. if (upgrade_it == req.headers.end()) { return false; }
  3967. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3968. if (upgrade_val != "websocket") { return false; }
  3969. // Check Connection header contains "Upgrade"
  3970. auto connection_it = req.headers.find("Connection");
  3971. if (connection_it == req.headers.end()) { return false; }
  3972. auto connection_val = case_ignore::to_lower(connection_it->second);
  3973. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3974. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3975. // RFC 6455 Section 4.2.1
  3976. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3977. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3978. return false;
  3979. }
  3980. static const std::string b64chars =
  3981. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3982. for (size_t i = 0; i < 22; i++) {
  3983. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3984. }
  3985. // Check Sec-WebSocket-Version: 13
  3986. auto version = req.get_header_value("Sec-WebSocket-Version");
  3987. if (version != "13") { return false; }
  3988. return true;
  3989. }
  3990. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3991. const char *data, size_t len, bool fin,
  3992. bool mask) {
  3993. // First byte: FIN + opcode
  3994. uint8_t header[2];
  3995. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3996. (static_cast<uint8_t>(opcode) & 0x0F));
  3997. // Second byte: MASK + payload length
  3998. if (len < 126) {
  3999. header[1] = static_cast<uint8_t>(len);
  4000. if (mask) { header[1] |= 0x80; }
  4001. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4002. } else if (len <= 0xFFFF) {
  4003. header[1] = 126;
  4004. if (mask) { header[1] |= 0x80; }
  4005. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4006. uint8_t ext[2];
  4007. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4008. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4009. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4010. } else {
  4011. header[1] = 127;
  4012. if (mask) { header[1] |= 0x80; }
  4013. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4014. uint8_t ext[8];
  4015. for (int i = 7; i >= 0; i--) {
  4016. ext[7 - i] =
  4017. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4018. }
  4019. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4020. }
  4021. if (mask) {
  4022. // Generate random mask key
  4023. thread_local std::mt19937 rng(std::random_device{}());
  4024. uint8_t mask_key[4];
  4025. auto r = rng();
  4026. std::memcpy(mask_key, &r, 4);
  4027. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4028. // Write masked payload in chunks
  4029. const size_t chunk_size = 4096;
  4030. std::vector<char> buf((std::min)(len, chunk_size));
  4031. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4032. size_t n = (std::min)(chunk_size, len - offset);
  4033. for (size_t i = 0; i < n; i++) {
  4034. buf[i] =
  4035. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4036. }
  4037. if (strm.write(buf.data(), n) < 0) { return false; }
  4038. }
  4039. } else {
  4040. if (len > 0) {
  4041. if (strm.write(data, len) < 0) { return false; }
  4042. }
  4043. }
  4044. return true;
  4045. }
  4046. } // namespace detail
  4047. namespace ws {
  4048. namespace impl {
  4049. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4050. std::string &payload, bool &fin,
  4051. bool expect_masked, size_t max_len) {
  4052. // Read first 2 bytes
  4053. uint8_t header[2];
  4054. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4055. fin = (header[0] & 0x80) != 0;
  4056. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4057. if (header[0] & 0x70) { return false; }
  4058. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4059. bool masked = (header[1] & 0x80) != 0;
  4060. uint64_t payload_len = header[1] & 0x7F;
  4061. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4062. // MUST have a payload length of 125 bytes or less
  4063. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4064. if (is_control) {
  4065. if (!fin) { return false; }
  4066. if (payload_len > 125) { return false; }
  4067. }
  4068. if (masked != expect_masked) { return false; }
  4069. // Extended payload length
  4070. if (payload_len == 126) {
  4071. uint8_t ext[2];
  4072. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4073. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4074. } else if (payload_len == 127) {
  4075. uint8_t ext[8];
  4076. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4077. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4078. if (ext[0] & 0x80) { return false; }
  4079. payload_len = 0;
  4080. for (int i = 0; i < 8; i++) {
  4081. payload_len = (payload_len << 8) | ext[i];
  4082. }
  4083. }
  4084. if (payload_len > max_len) { return false; }
  4085. // Read mask key if present
  4086. uint8_t mask_key[4] = {0};
  4087. if (masked) {
  4088. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4089. }
  4090. // Read payload
  4091. payload.resize(static_cast<size_t>(payload_len));
  4092. if (payload_len > 0) {
  4093. size_t total_read = 0;
  4094. while (total_read < payload_len) {
  4095. auto n = strm.read(&payload[total_read],
  4096. static_cast<size_t>(payload_len - total_read));
  4097. if (n <= 0) { return false; }
  4098. total_read += static_cast<size_t>(n);
  4099. }
  4100. }
  4101. // Unmask if needed
  4102. if (masked) {
  4103. for (size_t i = 0; i < payload.size(); i++) {
  4104. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4105. }
  4106. }
  4107. return true;
  4108. }
  4109. } // namespace impl
  4110. } // namespace ws
  4111. namespace detail {
  4112. inline bool is_valid_path(const std::string &path) {
  4113. size_t level = 0;
  4114. size_t i = 0;
  4115. // Skip slash
  4116. while (i < path.size() && path[i] == '/') {
  4117. i++;
  4118. }
  4119. while (i < path.size()) {
  4120. // Read component
  4121. auto beg = i;
  4122. while (i < path.size() && path[i] != '/') {
  4123. if (path[i] == '\0') {
  4124. return false;
  4125. } else if (path[i] == '\\') {
  4126. return false;
  4127. }
  4128. i++;
  4129. }
  4130. auto len = i - beg;
  4131. assert(len > 0);
  4132. if (!path.compare(beg, len, ".")) {
  4133. ;
  4134. } else if (!path.compare(beg, len, "..")) {
  4135. if (level == 0) { return false; }
  4136. level--;
  4137. } else {
  4138. level++;
  4139. }
  4140. // Skip slash
  4141. while (i < path.size() && path[i] == '/') {
  4142. i++;
  4143. }
  4144. }
  4145. return true;
  4146. }
  4147. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4148. #if defined(_WIN32)
  4149. char buf[_MAX_PATH];
  4150. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4151. resolved = buf;
  4152. #elif defined(PATH_MAX)
  4153. char buf[PATH_MAX];
  4154. if (realpath(path, buf) == nullptr) { return false; }
  4155. resolved = buf;
  4156. #else
  4157. auto buf = realpath(path, nullptr);
  4158. auto guard = scope_exit([&]() { std::free(buf); });
  4159. if (buf == nullptr) { return false; }
  4160. resolved = buf;
  4161. #endif
  4162. return true;
  4163. }
  4164. inline bool is_path_within_base(const std::string &resolved_path,
  4165. const std::string &resolved_base) {
  4166. #if defined(_WIN32)
  4167. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4168. resolved_base.size()) == 0;
  4169. #else
  4170. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4171. resolved_base.size()) == 0;
  4172. #endif
  4173. }
  4174. inline FileStat::FileStat(const std::string &path) {
  4175. #if defined(_WIN32)
  4176. auto wpath = u8string_to_wstring(path.c_str());
  4177. ret_ = _wstat(wpath.c_str(), &st_);
  4178. #else
  4179. ret_ = stat(path.c_str(), &st_);
  4180. #endif
  4181. }
  4182. inline bool FileStat::is_file() const {
  4183. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4184. }
  4185. inline bool FileStat::is_dir() const {
  4186. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4187. }
  4188. inline time_t FileStat::mtime() const {
  4189. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4190. : static_cast<time_t>(-1);
  4191. }
  4192. inline size_t FileStat::size() const {
  4193. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4194. }
  4195. inline std::string encode_path(const std::string &s) {
  4196. std::string result;
  4197. result.reserve(s.size());
  4198. for (size_t i = 0; s[i]; i++) {
  4199. switch (s[i]) {
  4200. case ' ': result += "%20"; break;
  4201. case '+': result += "%2B"; break;
  4202. case '\r': result += "%0D"; break;
  4203. case '\n': result += "%0A"; break;
  4204. case '\'': result += "%27"; break;
  4205. case ',': result += "%2C"; break;
  4206. // case ':': result += "%3A"; break; // ok? probably...
  4207. case ';': result += "%3B"; break;
  4208. default:
  4209. auto c = static_cast<uint8_t>(s[i]);
  4210. if (c >= 0x80) {
  4211. result += '%';
  4212. char hex[4];
  4213. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4214. assert(len == 2);
  4215. result.append(hex, static_cast<size_t>(len));
  4216. } else {
  4217. result += s[i];
  4218. }
  4219. break;
  4220. }
  4221. }
  4222. return result;
  4223. }
  4224. inline std::string file_extension(const std::string &path) {
  4225. std::smatch m;
  4226. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4227. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4228. return std::string();
  4229. }
  4230. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4231. template <typename T>
  4232. inline bool parse_header(const char *beg, const char *end, T fn);
  4233. template <typename T>
  4234. inline bool parse_header(const char *beg, const char *end, T fn) {
  4235. // Skip trailing spaces and tabs.
  4236. while (beg < end && is_space_or_tab(end[-1])) {
  4237. end--;
  4238. }
  4239. auto p = beg;
  4240. while (p < end && *p != ':') {
  4241. p++;
  4242. }
  4243. auto name = std::string(beg, p);
  4244. if (!detail::fields::is_field_name(name)) { return false; }
  4245. if (p == end) { return false; }
  4246. auto key_end = p;
  4247. if (*p++ != ':') { return false; }
  4248. while (p < end && is_space_or_tab(*p)) {
  4249. p++;
  4250. }
  4251. if (p <= end) {
  4252. auto key_len = key_end - beg;
  4253. if (!key_len) { return false; }
  4254. auto key = std::string(beg, key_end);
  4255. auto val = std::string(p, end);
  4256. if (!detail::fields::is_field_value(val)) { return false; }
  4257. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4258. // percent-decoded by the recipient. Applications that need to interpret a
  4259. // value as a URI component should call httplib::decode_uri_component()
  4260. // (or decode_path_component()) explicitly.
  4261. fn(key, val);
  4262. return true;
  4263. }
  4264. return false;
  4265. }
  4266. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4267. const Headers &src_headers) {
  4268. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4269. // transfer coding is complete when a chunk with a chunk-size of zero is
  4270. // received, possibly followed by a trailer section, and finally terminated by
  4271. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4272. //
  4273. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4274. // doesn't care for the existence of the final CRLF. In other words, it seems
  4275. // to be ok whether the final CRLF exists or not in the chunked data.
  4276. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4277. //
  4278. // According to the reference code in RFC 9112, cpp-httplib now allows
  4279. // chunked transfer coding data without the final CRLF.
  4280. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4281. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4282. "transfer-encoding",
  4283. "content-length",
  4284. "host",
  4285. "authorization",
  4286. "www-authenticate",
  4287. "proxy-authenticate",
  4288. "proxy-authorization",
  4289. "cookie",
  4290. "set-cookie",
  4291. "cache-control",
  4292. "expect",
  4293. "max-forwards",
  4294. "pragma",
  4295. "range",
  4296. "te",
  4297. "age",
  4298. "expires",
  4299. "date",
  4300. "location",
  4301. "retry-after",
  4302. "vary",
  4303. "warning",
  4304. "content-encoding",
  4305. "content-type",
  4306. "content-range",
  4307. "trailer"};
  4308. case_ignore::unordered_set<std::string> declared_trailers;
  4309. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4310. if (trailer_header && std::strlen(trailer_header)) {
  4311. auto len = std::strlen(trailer_header);
  4312. split(trailer_header, trailer_header + len, ',',
  4313. [&](const char *b, const char *e) {
  4314. const char *kbeg = b;
  4315. const char *kend = e;
  4316. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4317. ++kbeg;
  4318. }
  4319. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4320. --kend;
  4321. }
  4322. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4323. if (!key.empty() &&
  4324. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4325. declared_trailers.insert(key);
  4326. }
  4327. });
  4328. }
  4329. size_t trailer_header_count = 0;
  4330. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4331. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4332. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4333. constexpr auto line_terminator_len = 2;
  4334. auto line_beg = line_reader.ptr();
  4335. auto line_end =
  4336. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4337. if (!parse_header(line_beg, line_end,
  4338. [&](const std::string &key, const std::string &val) {
  4339. if (declared_trailers.find(key) !=
  4340. declared_trailers.end()) {
  4341. dest.emplace(key, val);
  4342. trailer_header_count++;
  4343. }
  4344. })) {
  4345. return false;
  4346. }
  4347. if (!line_reader.getline()) { return false; }
  4348. }
  4349. return true;
  4350. }
  4351. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4352. size_t right) {
  4353. while (b + left < e && is_space_or_tab(b[left])) {
  4354. left++;
  4355. }
  4356. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4357. right--;
  4358. }
  4359. return std::make_pair(left, right);
  4360. }
  4361. inline std::string trim_copy(const std::string &s) {
  4362. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4363. return s.substr(r.first, r.second - r.first);
  4364. }
  4365. inline std::string trim_double_quotes_copy(const std::string &s) {
  4366. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4367. return s.substr(1, s.size() - 2);
  4368. }
  4369. return s;
  4370. }
  4371. inline void
  4372. divide(const char *data, std::size_t size, char d,
  4373. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4374. fn) {
  4375. const auto it = std::find(data, data + size, d);
  4376. const auto found = static_cast<std::size_t>(it != data + size);
  4377. const auto lhs_data = data;
  4378. const auto lhs_size = static_cast<std::size_t>(it - data);
  4379. const auto rhs_data = it + found;
  4380. const auto rhs_size = size - lhs_size - found;
  4381. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4382. }
  4383. inline void
  4384. divide(const std::string &str, char d,
  4385. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4386. fn) {
  4387. divide(str.data(), str.size(), d, std::move(fn));
  4388. }
  4389. inline void split(const char *b, const char *e, char d,
  4390. std::function<void(const char *, const char *)> fn) {
  4391. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4392. }
  4393. inline void split(const char *b, const char *e, char d, size_t m,
  4394. std::function<void(const char *, const char *)> fn) {
  4395. size_t i = 0;
  4396. size_t beg = 0;
  4397. size_t count = 1;
  4398. while (e ? (b + i < e) : (b[i] != '\0')) {
  4399. if (b[i] == d && count < m) {
  4400. auto r = trim(b, e, beg, i);
  4401. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4402. beg = i + 1;
  4403. count++;
  4404. }
  4405. i++;
  4406. }
  4407. if (i) {
  4408. auto r = trim(b, e, beg, i);
  4409. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4410. }
  4411. }
  4412. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4413. std::function<bool(const char *, const char *)> fn) {
  4414. size_t i = 0;
  4415. size_t beg = 0;
  4416. size_t count = 1;
  4417. while (e ? (b + i < e) : (b[i] != '\0')) {
  4418. if (b[i] == d && count < m) {
  4419. auto r = trim(b, e, beg, i);
  4420. if (r.first < r.second) {
  4421. auto found = fn(&b[r.first], &b[r.second]);
  4422. if (found) { return true; }
  4423. }
  4424. beg = i + 1;
  4425. count++;
  4426. }
  4427. i++;
  4428. }
  4429. if (i) {
  4430. auto r = trim(b, e, beg, i);
  4431. if (r.first < r.second) {
  4432. auto found = fn(&b[r.first], &b[r.second]);
  4433. if (found) { return true; }
  4434. }
  4435. }
  4436. return false;
  4437. }
  4438. inline bool split_find(const char *b, const char *e, char d,
  4439. std::function<bool(const char *, const char *)> fn) {
  4440. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4441. std::move(fn));
  4442. }
  4443. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4444. size_t fixed_buffer_size)
  4445. : strm_(strm), fixed_buffer_(fixed_buffer),
  4446. fixed_buffer_size_(fixed_buffer_size) {}
  4447. inline const char *stream_line_reader::ptr() const {
  4448. if (growable_buffer_.empty()) {
  4449. return fixed_buffer_;
  4450. } else {
  4451. return growable_buffer_.data();
  4452. }
  4453. }
  4454. inline size_t stream_line_reader::size() const {
  4455. if (growable_buffer_.empty()) {
  4456. return fixed_buffer_used_size_;
  4457. } else {
  4458. return growable_buffer_.size();
  4459. }
  4460. }
  4461. inline bool stream_line_reader::end_with_crlf() const {
  4462. auto end = ptr() + size();
  4463. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4464. }
  4465. inline bool stream_line_reader::getline() {
  4466. fixed_buffer_used_size_ = 0;
  4467. growable_buffer_.clear();
  4468. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4469. char prev_byte = 0;
  4470. #endif
  4471. for (size_t i = 0;; i++) {
  4472. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4473. // Treat exceptionally long lines as an error to
  4474. // prevent infinite loops/memory exhaustion
  4475. return false;
  4476. }
  4477. char byte;
  4478. auto n = strm_.read(&byte, 1);
  4479. if (n < 0) {
  4480. return false;
  4481. } else if (n == 0) {
  4482. if (i == 0) {
  4483. return false;
  4484. } else {
  4485. break;
  4486. }
  4487. }
  4488. append(byte);
  4489. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4490. if (byte == '\n') { break; }
  4491. #else
  4492. if (prev_byte == '\r' && byte == '\n') { break; }
  4493. prev_byte = byte;
  4494. #endif
  4495. }
  4496. return true;
  4497. }
  4498. inline void stream_line_reader::append(char c) {
  4499. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4500. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4501. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4502. } else {
  4503. if (growable_buffer_.empty()) {
  4504. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4505. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4506. }
  4507. growable_buffer_ += c;
  4508. }
  4509. }
  4510. inline mmap::mmap(const char *path) { open(path); }
  4511. inline mmap::~mmap() { close(); }
  4512. inline bool mmap::open(const char *path) {
  4513. close();
  4514. #if defined(_WIN32)
  4515. auto wpath = u8string_to_wstring(path);
  4516. if (wpath.empty()) { return false; }
  4517. hFile_ =
  4518. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4519. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4520. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4521. LARGE_INTEGER size{};
  4522. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4523. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4524. // See:
  4525. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4526. if (static_cast<ULONGLONG>(size.QuadPart) >
  4527. (std::numeric_limits<decltype(size_)>::max)()) {
  4528. // `size_t` might be 32-bits, on 32-bits Windows.
  4529. return false;
  4530. }
  4531. size_ = static_cast<size_t>(size.QuadPart);
  4532. hMapping_ =
  4533. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4534. // Special treatment for an empty file...
  4535. if (hMapping_ == NULL && size_ == 0) {
  4536. close();
  4537. is_open_empty_file = true;
  4538. return true;
  4539. }
  4540. if (hMapping_ == NULL) {
  4541. close();
  4542. return false;
  4543. }
  4544. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4545. if (addr_ == nullptr) {
  4546. close();
  4547. return false;
  4548. }
  4549. #else
  4550. fd_ = ::open(path, O_RDONLY);
  4551. if (fd_ == -1) { return false; }
  4552. struct stat sb;
  4553. if (fstat(fd_, &sb) == -1) {
  4554. close();
  4555. return false;
  4556. }
  4557. size_ = static_cast<size_t>(sb.st_size);
  4558. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4559. // Special treatment for an empty file...
  4560. if (addr_ == MAP_FAILED && size_ == 0) {
  4561. close();
  4562. is_open_empty_file = true;
  4563. return false;
  4564. }
  4565. #endif
  4566. return true;
  4567. }
  4568. inline bool mmap::is_open() const {
  4569. return is_open_empty_file ? true : addr_ != nullptr;
  4570. }
  4571. inline size_t mmap::size() const { return size_; }
  4572. inline const char *mmap::data() const {
  4573. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4574. }
  4575. inline void mmap::close() {
  4576. #if defined(_WIN32)
  4577. if (addr_) {
  4578. ::UnmapViewOfFile(addr_);
  4579. addr_ = nullptr;
  4580. }
  4581. if (hMapping_) {
  4582. ::CloseHandle(hMapping_);
  4583. hMapping_ = NULL;
  4584. }
  4585. if (hFile_ != INVALID_HANDLE_VALUE) {
  4586. ::CloseHandle(hFile_);
  4587. hFile_ = INVALID_HANDLE_VALUE;
  4588. }
  4589. is_open_empty_file = false;
  4590. #else
  4591. if (addr_ != nullptr) {
  4592. munmap(addr_, size_);
  4593. addr_ = nullptr;
  4594. }
  4595. if (fd_ != -1) {
  4596. ::close(fd_);
  4597. fd_ = -1;
  4598. }
  4599. #endif
  4600. size_ = 0;
  4601. }
  4602. inline int close_socket(socket_t sock) noexcept {
  4603. #ifdef _WIN32
  4604. return closesocket(sock);
  4605. #else
  4606. return close(sock);
  4607. #endif
  4608. }
  4609. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4610. ssize_t res = 0;
  4611. while (true) {
  4612. res = fn();
  4613. if (res < 0 && errno == EINTR) {
  4614. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4615. continue;
  4616. }
  4617. break;
  4618. }
  4619. return res;
  4620. }
  4621. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4622. return handle_EINTR([&]() {
  4623. return recv(sock,
  4624. #ifdef _WIN32
  4625. static_cast<char *>(ptr), static_cast<int>(size),
  4626. #else
  4627. ptr, size,
  4628. #endif
  4629. flags);
  4630. });
  4631. }
  4632. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4633. int flags) {
  4634. return handle_EINTR([&]() {
  4635. return send(sock,
  4636. #ifdef _WIN32
  4637. static_cast<const char *>(ptr), static_cast<int>(size),
  4638. #else
  4639. ptr, size,
  4640. #endif
  4641. flags);
  4642. });
  4643. }
  4644. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4645. #ifdef _WIN32
  4646. return ::WSAPoll(fds, nfds, timeout);
  4647. #else
  4648. return ::poll(fds, nfds, timeout);
  4649. #endif
  4650. }
  4651. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4652. time_t usec) {
  4653. struct pollfd pfd;
  4654. pfd.fd = sock;
  4655. pfd.events = events;
  4656. pfd.revents = 0;
  4657. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4658. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4659. }
  4660. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4661. return select_impl(sock, POLLIN, sec, usec);
  4662. }
  4663. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4664. return select_impl(sock, POLLOUT, sec, usec);
  4665. }
  4666. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4667. time_t usec) {
  4668. struct pollfd pfd_read;
  4669. pfd_read.fd = sock;
  4670. pfd_read.events = POLLIN | POLLOUT;
  4671. pfd_read.revents = 0;
  4672. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4673. auto poll_res =
  4674. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4675. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4676. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4677. auto error = 0;
  4678. socklen_t len = sizeof(error);
  4679. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4680. reinterpret_cast<char *>(&error), &len);
  4681. auto successful = res >= 0 && !error;
  4682. return successful ? Error::Success : Error::Connection;
  4683. }
  4684. return Error::Connection;
  4685. }
  4686. inline bool is_socket_alive(socket_t sock) {
  4687. const auto val = detail::select_read(sock, 0, 0);
  4688. if (val == 0) {
  4689. return true;
  4690. } else if (val < 0 && errno == EBADF) {
  4691. return false;
  4692. }
  4693. char buf[1];
  4694. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4695. }
  4696. class SocketStream final : public Stream {
  4697. public:
  4698. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4699. time_t write_timeout_sec, time_t write_timeout_usec,
  4700. time_t max_timeout_msec = 0,
  4701. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4702. (std::chrono::steady_clock::time_point::min)());
  4703. ~SocketStream() override;
  4704. bool is_readable() const override;
  4705. bool wait_readable() const override;
  4706. bool wait_writable() const override;
  4707. bool is_peer_alive() const override;
  4708. ssize_t read(char *ptr, size_t size) override;
  4709. ssize_t write(const char *ptr, size_t size) override;
  4710. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4711. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4712. socket_t socket() const override;
  4713. time_t duration() const override;
  4714. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4715. private:
  4716. socket_t sock_;
  4717. time_t read_timeout_sec_;
  4718. time_t read_timeout_usec_;
  4719. time_t write_timeout_sec_;
  4720. time_t write_timeout_usec_;
  4721. time_t max_timeout_msec_;
  4722. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4723. std::vector<char> read_buff_;
  4724. size_t read_buff_off_ = 0;
  4725. size_t read_buff_content_size_ = 0;
  4726. static const size_t read_buff_size_ = 1024l * 4;
  4727. };
  4728. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4729. time_t keep_alive_timeout_sec) {
  4730. using namespace std::chrono;
  4731. const auto interval_usec =
  4732. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4733. // Avoid expensive `steady_clock::now()` call for the first time
  4734. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4735. const auto start = steady_clock::now() - microseconds{interval_usec};
  4736. const auto timeout = seconds{keep_alive_timeout_sec};
  4737. while (true) {
  4738. if (svr_sock == INVALID_SOCKET) {
  4739. break; // Server socket is closed
  4740. }
  4741. auto val = select_read(sock, 0, interval_usec);
  4742. if (val < 0) {
  4743. break; // Ssocket error
  4744. } else if (val == 0) {
  4745. if (steady_clock::now() - start > timeout) {
  4746. break; // Timeout
  4747. }
  4748. } else {
  4749. return true; // Ready for read
  4750. }
  4751. }
  4752. return false;
  4753. }
  4754. template <typename T>
  4755. inline bool
  4756. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4757. size_t keep_alive_max_count,
  4758. time_t keep_alive_timeout_sec, T callback) {
  4759. assert(keep_alive_max_count > 0);
  4760. auto ret = false;
  4761. auto count = keep_alive_max_count;
  4762. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4763. auto close_connection = count == 1;
  4764. auto connection_closed = false;
  4765. ret = callback(close_connection, connection_closed);
  4766. if (!ret || connection_closed) { break; }
  4767. count--;
  4768. }
  4769. return ret;
  4770. }
  4771. template <typename T>
  4772. inline bool
  4773. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4774. size_t keep_alive_max_count,
  4775. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4776. time_t read_timeout_usec, time_t write_timeout_sec,
  4777. time_t write_timeout_usec, T callback) {
  4778. return process_server_socket_core(
  4779. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4780. [&](bool close_connection, bool &connection_closed) {
  4781. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4782. write_timeout_sec, write_timeout_usec);
  4783. return callback(strm, close_connection, connection_closed);
  4784. });
  4785. }
  4786. inline bool process_client_socket(
  4787. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4788. time_t write_timeout_sec, time_t write_timeout_usec,
  4789. time_t max_timeout_msec,
  4790. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4791. std::function<bool(Stream &)> callback) {
  4792. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4793. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4794. start_time);
  4795. return callback(strm);
  4796. }
  4797. inline int shutdown_socket(socket_t sock) noexcept {
  4798. #ifdef _WIN32
  4799. return shutdown(sock, SD_BOTH);
  4800. #else
  4801. return shutdown(sock, SHUT_RDWR);
  4802. #endif
  4803. }
  4804. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4805. if (s.size() > 1 && s[0] == '\0') {
  4806. auto ret = s;
  4807. ret[0] = '@';
  4808. return ret;
  4809. }
  4810. return s;
  4811. }
  4812. inline std::string
  4813. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4814. if (s.size() > 1 && s[0] == '@') {
  4815. auto ret = s;
  4816. ret[0] = '\0';
  4817. return ret;
  4818. }
  4819. return s;
  4820. }
  4821. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4822. const struct addrinfo *hints,
  4823. struct addrinfo **res, time_t timeout_sec) {
  4824. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4825. if (timeout_sec <= 0) {
  4826. // No timeout specified, use standard getaddrinfo
  4827. return getaddrinfo(node, service, hints, res);
  4828. }
  4829. #ifdef _WIN32
  4830. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4831. OVERLAPPED overlapped = {};
  4832. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4833. if (!event) { return EAI_FAIL; }
  4834. overlapped.hEvent = event;
  4835. PADDRINFOEXW result_addrinfo = nullptr;
  4836. HANDLE cancel_handle = nullptr;
  4837. ADDRINFOEXW hints_ex = {};
  4838. if (hints) {
  4839. hints_ex.ai_flags = hints->ai_flags;
  4840. hints_ex.ai_family = hints->ai_family;
  4841. hints_ex.ai_socktype = hints->ai_socktype;
  4842. hints_ex.ai_protocol = hints->ai_protocol;
  4843. }
  4844. auto wnode = u8string_to_wstring(node);
  4845. auto wservice = u8string_to_wstring(service);
  4846. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4847. hints ? &hints_ex : nullptr, &result_addrinfo,
  4848. nullptr, &overlapped, nullptr, &cancel_handle);
  4849. if (ret == WSA_IO_PENDING) {
  4850. auto wait_result =
  4851. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4852. if (wait_result == WAIT_TIMEOUT) {
  4853. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4854. ::CloseHandle(event);
  4855. return EAI_AGAIN;
  4856. }
  4857. DWORD bytes_returned;
  4858. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4859. &bytes_returned, FALSE)) {
  4860. ::CloseHandle(event);
  4861. return ::WSAGetLastError();
  4862. }
  4863. }
  4864. ::CloseHandle(event);
  4865. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4866. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4867. return 0;
  4868. }
  4869. return ret;
  4870. #elif TARGET_OS_MAC && defined(__clang__)
  4871. if (!node) { return EAI_NONAME; }
  4872. // macOS implementation using CFHost API for asynchronous DNS resolution
  4873. CFStringRef hostname_ref = CFStringCreateWithCString(
  4874. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4875. if (!hostname_ref) { return EAI_MEMORY; }
  4876. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4877. CFRelease(hostname_ref);
  4878. if (!host_ref) { return EAI_MEMORY; }
  4879. // Set up context for callback
  4880. struct CFHostContext {
  4881. bool completed = false;
  4882. bool success = false;
  4883. CFArrayRef addresses = nullptr;
  4884. std::mutex mutex;
  4885. std::condition_variable cv;
  4886. } context;
  4887. CFHostClientContext client_context;
  4888. memset(&client_context, 0, sizeof(client_context));
  4889. client_context.info = &context;
  4890. // Set callback
  4891. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4892. const CFStreamError *error, void *info) {
  4893. auto ctx = static_cast<CFHostContext *>(info);
  4894. std::lock_guard<std::mutex> lock(ctx->mutex);
  4895. if (error && error->error != 0) {
  4896. ctx->success = false;
  4897. } else {
  4898. Boolean hasBeenResolved;
  4899. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4900. if (ctx->addresses && hasBeenResolved) {
  4901. CFRetain(ctx->addresses);
  4902. ctx->success = true;
  4903. } else {
  4904. ctx->success = false;
  4905. }
  4906. }
  4907. ctx->completed = true;
  4908. ctx->cv.notify_one();
  4909. };
  4910. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4911. CFRelease(host_ref);
  4912. return EAI_SYSTEM;
  4913. }
  4914. // Schedule on run loop
  4915. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4916. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4917. // Start resolution
  4918. CFStreamError stream_error;
  4919. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4920. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4921. CFRelease(host_ref);
  4922. return EAI_FAIL;
  4923. }
  4924. // Wait for completion with timeout
  4925. auto timeout_time =
  4926. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4927. bool timed_out = false;
  4928. {
  4929. std::unique_lock<std::mutex> lock(context.mutex);
  4930. while (!context.completed) {
  4931. auto now = std::chrono::steady_clock::now();
  4932. if (now >= timeout_time) {
  4933. timed_out = true;
  4934. break;
  4935. }
  4936. // Run the runloop for a short time
  4937. lock.unlock();
  4938. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4939. lock.lock();
  4940. }
  4941. }
  4942. // Clean up
  4943. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4944. CFHostSetClient(host_ref, nullptr, nullptr);
  4945. if (timed_out || !context.completed) {
  4946. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4947. CFRelease(host_ref);
  4948. return EAI_AGAIN;
  4949. }
  4950. if (!context.success || !context.addresses) {
  4951. CFRelease(host_ref);
  4952. return EAI_NODATA;
  4953. }
  4954. // Convert CFArray to addrinfo
  4955. CFIndex count = CFArrayGetCount(context.addresses);
  4956. if (count == 0) {
  4957. CFRelease(context.addresses);
  4958. CFRelease(host_ref);
  4959. return EAI_NODATA;
  4960. }
  4961. struct addrinfo *result_addrinfo = nullptr;
  4962. struct addrinfo **current = &result_addrinfo;
  4963. for (CFIndex i = 0; i < count; i++) {
  4964. CFDataRef addr_data =
  4965. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4966. if (!addr_data) continue;
  4967. const struct sockaddr *sockaddr_ptr =
  4968. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4969. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4970. // Allocate addrinfo structure
  4971. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4972. if (!*current) {
  4973. freeaddrinfo(result_addrinfo);
  4974. CFRelease(context.addresses);
  4975. CFRelease(host_ref);
  4976. return EAI_MEMORY;
  4977. }
  4978. memset(*current, 0, sizeof(struct addrinfo));
  4979. // Set up addrinfo fields
  4980. (*current)->ai_family = sockaddr_ptr->sa_family;
  4981. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4982. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4983. (*current)->ai_addrlen = sockaddr_len;
  4984. // Copy sockaddr
  4985. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4986. if (!(*current)->ai_addr) {
  4987. freeaddrinfo(result_addrinfo);
  4988. CFRelease(context.addresses);
  4989. CFRelease(host_ref);
  4990. return EAI_MEMORY;
  4991. }
  4992. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4993. // Set port if service is specified
  4994. if (service && *service) {
  4995. int port = 0;
  4996. if (parse_port(service, strlen(service), port)) {
  4997. if (sockaddr_ptr->sa_family == AF_INET) {
  4998. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4999. ->sin_port = htons(static_cast<uint16_t>(port));
  5000. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5001. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5002. ->sin6_port = htons(static_cast<uint16_t>(port));
  5003. }
  5004. }
  5005. }
  5006. current = &((*current)->ai_next);
  5007. }
  5008. CFRelease(context.addresses);
  5009. CFRelease(host_ref);
  5010. *res = result_addrinfo;
  5011. return 0;
  5012. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5013. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5014. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5015. // the resolver worker still references the stack-local gaicb. The cancel
  5016. // path therefore waits (gai_suspend with no timeout) for the worker to
  5017. // actually finish before letting the stack frame go. The trade-off is that
  5018. // a wedged DNS server can hold this thread for the system resolver timeout
  5019. // (~30s by default) past the caller's connection timeout.
  5020. struct gaicb request {};
  5021. struct gaicb *requests[1] = {&request};
  5022. struct sigevent sevp {};
  5023. struct timespec timeout {
  5024. timeout_sec, 0
  5025. };
  5026. request.ar_name = node;
  5027. request.ar_service = service;
  5028. request.ar_request = hints;
  5029. sevp.sigev_notify = SIGEV_NONE;
  5030. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5031. if (rc != 0) { return rc; }
  5032. auto cleanup = scope_exit([&] {
  5033. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5034. });
  5035. int wait_result = gai_suspend(requests, 1, &timeout);
  5036. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5037. int gai_result = gai_error(&request);
  5038. if (gai_result == 0) {
  5039. *res = request.ar_result;
  5040. request.ar_result = nullptr;
  5041. return 0;
  5042. }
  5043. return gai_result;
  5044. }
  5045. gai_cancel(&request);
  5046. while (gai_error(&request) == EAI_INPROGRESS) {
  5047. gai_suspend(requests, 1, nullptr);
  5048. }
  5049. return wait_result;
  5050. #else
  5051. // Fallback implementation using thread-based timeout for other Unix systems.
  5052. struct GetAddrInfoState {
  5053. ~GetAddrInfoState() {
  5054. if (info) { freeaddrinfo(info); }
  5055. }
  5056. std::mutex mutex;
  5057. std::condition_variable result_cv;
  5058. bool completed = false;
  5059. int result = EAI_SYSTEM;
  5060. std::string node;
  5061. std::string service;
  5062. struct addrinfo hints;
  5063. struct addrinfo *info = nullptr;
  5064. };
  5065. // Allocate on the heap, so the resolver thread can keep using the data.
  5066. auto state = std::make_shared<GetAddrInfoState>();
  5067. if (node) { state->node = node; }
  5068. state->service = service;
  5069. state->hints = *hints;
  5070. std::thread resolve_thread([state]() {
  5071. auto thread_result =
  5072. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5073. &state->info);
  5074. std::lock_guard<std::mutex> lock(state->mutex);
  5075. state->result = thread_result;
  5076. state->completed = true;
  5077. state->result_cv.notify_one();
  5078. });
  5079. // Wait for completion or timeout
  5080. std::unique_lock<std::mutex> lock(state->mutex);
  5081. auto finished =
  5082. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5083. [&] { return state->completed; });
  5084. if (finished) {
  5085. // Operation completed within timeout
  5086. resolve_thread.join();
  5087. *res = state->info;
  5088. state->info = nullptr; // Pass ownership to caller
  5089. return state->result;
  5090. } else {
  5091. // Timeout occurred
  5092. resolve_thread.detach(); // Let the thread finish in background
  5093. return EAI_AGAIN; // Return timeout error
  5094. }
  5095. #endif
  5096. #else
  5097. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5098. return getaddrinfo(node, service, hints, res);
  5099. #endif
  5100. }
  5101. template <typename BindOrConnect>
  5102. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5103. int address_family, int socket_flags, bool tcp_nodelay,
  5104. bool ipv6_v6only, SocketOptions socket_options,
  5105. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5106. // Get address info
  5107. const char *node = nullptr;
  5108. struct addrinfo hints;
  5109. struct addrinfo *result;
  5110. memset(&hints, 0, sizeof(struct addrinfo));
  5111. hints.ai_socktype = SOCK_STREAM;
  5112. hints.ai_protocol = IPPROTO_IP;
  5113. if (!ip.empty()) {
  5114. node = ip.c_str();
  5115. // Ask getaddrinfo to convert IP in c-string to address
  5116. hints.ai_family = AF_UNSPEC;
  5117. hints.ai_flags = AI_NUMERICHOST;
  5118. } else {
  5119. if (!host.empty()) { node = host.c_str(); }
  5120. hints.ai_family = address_family;
  5121. hints.ai_flags = socket_flags;
  5122. }
  5123. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5124. if (hints.ai_family == AF_UNIX) {
  5125. const auto addrlen = host.length();
  5126. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5127. #ifdef SOCK_CLOEXEC
  5128. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5129. hints.ai_protocol);
  5130. #else
  5131. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5132. #endif
  5133. if (sock != INVALID_SOCKET) {
  5134. sockaddr_un addr{};
  5135. addr.sun_family = AF_UNIX;
  5136. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5137. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5138. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5139. hints.ai_addrlen = static_cast<socklen_t>(
  5140. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5141. #ifndef SOCK_CLOEXEC
  5142. #ifndef _WIN32
  5143. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5144. #endif
  5145. #endif
  5146. if (socket_options) { socket_options(sock); }
  5147. #ifdef _WIN32
  5148. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5149. // remove the option.
  5150. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5151. #endif
  5152. bool dummy;
  5153. if (!bind_or_connect(sock, hints, dummy)) {
  5154. close_socket(sock);
  5155. sock = INVALID_SOCKET;
  5156. }
  5157. }
  5158. return sock;
  5159. }
  5160. #endif
  5161. auto service = std::to_string(port);
  5162. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5163. timeout_sec)) {
  5164. #if defined __linux__ && !defined __ANDROID__
  5165. res_init();
  5166. #endif
  5167. return INVALID_SOCKET;
  5168. }
  5169. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5170. for (auto rp = result; rp; rp = rp->ai_next) {
  5171. // Create a socket
  5172. #ifdef _WIN32
  5173. auto sock =
  5174. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5175. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5176. /**
  5177. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5178. * and above the socket creation fails on older Windows Systems.
  5179. *
  5180. * Let's try to create a socket the old way in this case.
  5181. *
  5182. * Reference:
  5183. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5184. *
  5185. * WSA_FLAG_NO_HANDLE_INHERIT:
  5186. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5187. * SP1, and later
  5188. *
  5189. */
  5190. if (sock == INVALID_SOCKET) {
  5191. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5192. }
  5193. #else
  5194. #ifdef SOCK_CLOEXEC
  5195. auto sock =
  5196. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5197. #else
  5198. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5199. #endif
  5200. #endif
  5201. if (sock == INVALID_SOCKET) { continue; }
  5202. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5203. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5204. close_socket(sock);
  5205. continue;
  5206. }
  5207. #endif
  5208. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5209. if (rp->ai_family == AF_INET6) {
  5210. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5211. }
  5212. if (socket_options) { socket_options(sock); }
  5213. // bind or connect
  5214. auto quit = false;
  5215. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5216. close_socket(sock);
  5217. if (quit) { break; }
  5218. }
  5219. return INVALID_SOCKET;
  5220. }
  5221. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5222. #ifdef _WIN32
  5223. auto flags = nonblocking ? 1UL : 0UL;
  5224. ioctlsocket(sock, FIONBIO, &flags);
  5225. #else
  5226. auto flags = fcntl(sock, F_GETFL, 0);
  5227. fcntl(sock, F_SETFL,
  5228. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5229. #endif
  5230. }
  5231. inline bool is_connection_error() {
  5232. #ifdef _WIN32
  5233. return WSAGetLastError() != WSAEWOULDBLOCK;
  5234. #else
  5235. return errno != EINPROGRESS;
  5236. #endif
  5237. }
  5238. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5239. struct addrinfo hints;
  5240. struct addrinfo *result;
  5241. memset(&hints, 0, sizeof(struct addrinfo));
  5242. hints.ai_family = AF_UNSPEC;
  5243. hints.ai_socktype = SOCK_STREAM;
  5244. hints.ai_protocol = 0;
  5245. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5246. return false;
  5247. }
  5248. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5249. auto ret = false;
  5250. for (auto rp = result; rp; rp = rp->ai_next) {
  5251. const auto &ai = *rp;
  5252. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5253. ret = true;
  5254. break;
  5255. }
  5256. }
  5257. return ret;
  5258. }
  5259. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5260. #define USE_IF2IP
  5261. #endif
  5262. #ifdef USE_IF2IP
  5263. inline std::string if2ip(int address_family, const std::string &ifn) {
  5264. struct ifaddrs *ifap;
  5265. getifaddrs(&ifap);
  5266. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5267. std::string addr_candidate;
  5268. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5269. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5270. (AF_UNSPEC == address_family ||
  5271. ifa->ifa_addr->sa_family == address_family)) {
  5272. if (ifa->ifa_addr->sa_family == AF_INET) {
  5273. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5274. char buf[INET_ADDRSTRLEN];
  5275. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5276. return std::string(buf, INET_ADDRSTRLEN);
  5277. }
  5278. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5279. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5280. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5281. char buf[INET6_ADDRSTRLEN] = {};
  5282. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5283. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5284. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5285. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5286. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5287. } else {
  5288. return std::string(buf, INET6_ADDRSTRLEN);
  5289. }
  5290. }
  5291. }
  5292. }
  5293. }
  5294. }
  5295. return addr_candidate;
  5296. }
  5297. #endif
  5298. inline socket_t create_client_socket(
  5299. const std::string &host, const std::string &ip, int port,
  5300. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5301. SocketOptions socket_options, time_t connection_timeout_sec,
  5302. time_t connection_timeout_usec, time_t read_timeout_sec,
  5303. time_t read_timeout_usec, time_t write_timeout_sec,
  5304. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5305. auto sock = create_socket(
  5306. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5307. std::move(socket_options),
  5308. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5309. if (!intf.empty()) {
  5310. #ifdef USE_IF2IP
  5311. auto ip_from_if = if2ip(address_family, intf);
  5312. if (ip_from_if.empty()) { ip_from_if = intf; }
  5313. if (!bind_ip_address(sock2, ip_from_if)) {
  5314. error = Error::BindIPAddress;
  5315. return false;
  5316. }
  5317. #endif
  5318. }
  5319. set_nonblocking(sock2, true);
  5320. auto ret =
  5321. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5322. if (ret < 0) {
  5323. if (is_connection_error()) {
  5324. error = Error::Connection;
  5325. return false;
  5326. }
  5327. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5328. connection_timeout_usec);
  5329. if (error != Error::Success) {
  5330. if (error == Error::ConnectionTimeout) { quit = true; }
  5331. return false;
  5332. }
  5333. }
  5334. set_nonblocking(sock2, false);
  5335. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5336. read_timeout_usec);
  5337. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5338. write_timeout_usec);
  5339. error = Error::Success;
  5340. return true;
  5341. },
  5342. connection_timeout_sec); // Pass DNS timeout
  5343. if (sock != INVALID_SOCKET) {
  5344. error = Error::Success;
  5345. } else {
  5346. if (error == Error::Success) { error = Error::Connection; }
  5347. }
  5348. return sock;
  5349. }
  5350. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5351. socklen_t addr_len, std::string &ip, int &port) {
  5352. if (addr.ss_family == AF_INET) {
  5353. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5354. } else if (addr.ss_family == AF_INET6) {
  5355. port =
  5356. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5357. } else {
  5358. return false;
  5359. }
  5360. std::array<char, NI_MAXHOST> ipstr{};
  5361. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5362. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5363. 0, NI_NUMERICHOST)) {
  5364. return false;
  5365. }
  5366. ip = ipstr.data();
  5367. return true;
  5368. }
  5369. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5370. struct sockaddr_storage addr;
  5371. socklen_t addr_len = sizeof(addr);
  5372. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5373. &addr_len)) {
  5374. get_ip_and_port(addr, addr_len, ip, port);
  5375. }
  5376. }
  5377. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5378. struct sockaddr_storage addr;
  5379. socklen_t addr_len = sizeof(addr);
  5380. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5381. &addr_len)) {
  5382. #ifndef _WIN32
  5383. if (addr.ss_family == AF_UNIX) {
  5384. #if defined(__linux__)
  5385. struct ucred ucred;
  5386. socklen_t len = sizeof(ucred);
  5387. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5388. port = ucred.pid;
  5389. }
  5390. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5391. pid_t pid;
  5392. socklen_t len = sizeof(pid);
  5393. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5394. port = pid;
  5395. }
  5396. #endif
  5397. return;
  5398. }
  5399. #endif
  5400. get_ip_and_port(addr, addr_len, ip, port);
  5401. }
  5402. }
  5403. // Recursive form retained so operator""_t below can compute hashes for
  5404. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5405. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5406. // instead, which is iterative and stack-safe.
  5407. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5408. unsigned int h) {
  5409. return (l == 0)
  5410. ? h
  5411. : str2tag_core(
  5412. s + 1, l - 1,
  5413. // Unsets the 6 high bits of h, therefore no overflow happens
  5414. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5415. h * 33) ^
  5416. static_cast<unsigned char>(*s));
  5417. }
  5418. inline unsigned int str2tag(const std::string &s) {
  5419. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5420. // for compile-time UDL evaluation of short string literals, but at runtime
  5421. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5422. // would blow the stack with one frame per character.
  5423. unsigned int h = 0;
  5424. for (auto c : s) {
  5425. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5426. static_cast<unsigned char>(c);
  5427. }
  5428. return h;
  5429. }
  5430. namespace udl {
  5431. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5432. return str2tag_core(s, l, 0);
  5433. }
  5434. } // namespace udl
  5435. inline std::string
  5436. find_content_type(const std::string &path,
  5437. const std::map<std::string, std::string> &user_data,
  5438. const std::string &default_content_type) {
  5439. auto ext = file_extension(path);
  5440. auto it = user_data.find(ext);
  5441. if (it != user_data.end()) { return it->second; }
  5442. using udl::operator""_t;
  5443. switch (str2tag(ext)) {
  5444. default: return default_content_type;
  5445. case "css"_t: return "text/css";
  5446. case "csv"_t: return "text/csv";
  5447. case "htm"_t:
  5448. case "html"_t: return "text/html";
  5449. case "js"_t:
  5450. case "mjs"_t: return "text/javascript";
  5451. case "txt"_t: return "text/plain";
  5452. case "vtt"_t: return "text/vtt";
  5453. case "apng"_t: return "image/apng";
  5454. case "avif"_t: return "image/avif";
  5455. case "bmp"_t: return "image/bmp";
  5456. case "gif"_t: return "image/gif";
  5457. case "png"_t: return "image/png";
  5458. case "svg"_t: return "image/svg+xml";
  5459. case "webp"_t: return "image/webp";
  5460. case "ico"_t: return "image/x-icon";
  5461. case "tif"_t: return "image/tiff";
  5462. case "tiff"_t: return "image/tiff";
  5463. case "jpg"_t:
  5464. case "jpeg"_t: return "image/jpeg";
  5465. case "mp4"_t: return "video/mp4";
  5466. case "mpeg"_t: return "video/mpeg";
  5467. case "webm"_t: return "video/webm";
  5468. case "mp3"_t: return "audio/mp3";
  5469. case "mpga"_t: return "audio/mpeg";
  5470. case "weba"_t: return "audio/webm";
  5471. case "wav"_t: return "audio/wave";
  5472. case "otf"_t: return "font/otf";
  5473. case "ttf"_t: return "font/ttf";
  5474. case "woff"_t: return "font/woff";
  5475. case "woff2"_t: return "font/woff2";
  5476. case "7z"_t: return "application/x-7z-compressed";
  5477. case "atom"_t: return "application/atom+xml";
  5478. case "pdf"_t: return "application/pdf";
  5479. case "json"_t: return "application/json";
  5480. case "rss"_t: return "application/rss+xml";
  5481. case "tar"_t: return "application/x-tar";
  5482. case "xht"_t:
  5483. case "xhtml"_t: return "application/xhtml+xml";
  5484. case "xslt"_t: return "application/xslt+xml";
  5485. case "xml"_t: return "application/xml";
  5486. case "gz"_t: return "application/gzip";
  5487. case "zip"_t: return "application/zip";
  5488. case "wasm"_t: return "application/wasm";
  5489. }
  5490. }
  5491. inline std::string
  5492. extract_media_type(const std::string &content_type,
  5493. std::map<std::string, std::string> *params = nullptr) {
  5494. // Extract type/subtype from Content-Type value (RFC 2045)
  5495. // e.g. "application/json; charset=utf-8" -> "application/json"
  5496. auto media_type = content_type;
  5497. auto semicolon_pos = media_type.find(';');
  5498. if (semicolon_pos != std::string::npos) {
  5499. auto param_str = media_type.substr(semicolon_pos + 1);
  5500. media_type = media_type.substr(0, semicolon_pos);
  5501. if (params) {
  5502. // Parse parameters: key=value pairs separated by ';'
  5503. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5504. [&](const char *b, const char *e) {
  5505. std::string key;
  5506. std::string val;
  5507. split(b, e, '=', [&](const char *b2, const char *e2) {
  5508. if (key.empty()) {
  5509. key.assign(b2, e2);
  5510. } else {
  5511. val.assign(b2, e2);
  5512. }
  5513. });
  5514. if (!key.empty()) {
  5515. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5516. }
  5517. });
  5518. }
  5519. }
  5520. // Trim whitespace from media type
  5521. return trim_copy(media_type);
  5522. }
  5523. inline bool can_compress_content_type(const std::string &content_type) {
  5524. using udl::operator""_t;
  5525. auto mime_type = extract_media_type(content_type);
  5526. auto tag = str2tag(mime_type);
  5527. switch (tag) {
  5528. case "image/svg+xml"_t:
  5529. case "application/javascript"_t:
  5530. case "application/x-javascript"_t:
  5531. case "application/json"_t:
  5532. case "application/ld+json"_t:
  5533. case "application/xml"_t:
  5534. case "application/xhtml+xml"_t:
  5535. case "application/rss+xml"_t:
  5536. case "application/atom+xml"_t:
  5537. case "application/xslt+xml"_t:
  5538. case "application/protobuf"_t: return true;
  5539. case "text/event-stream"_t: return false;
  5540. default: return !mime_type.rfind("text/", 0);
  5541. }
  5542. }
  5543. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5544. double &quality) {
  5545. quality = 1.0;
  5546. token.clear();
  5547. // Split on first ';': left = token name, right = parameters
  5548. const char *params_b = nullptr;
  5549. std::size_t params_len = 0;
  5550. divide(
  5551. b, static_cast<std::size_t>(e - b), ';',
  5552. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5553. auto r = trim(lb, lb + llen, 0, llen);
  5554. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5555. params_b = rb;
  5556. params_len = rlen;
  5557. });
  5558. if (token.empty()) { return false; }
  5559. if (params_len == 0) { return true; }
  5560. // Scan parameters for q= (stops on first match)
  5561. bool invalid = false;
  5562. split_find(params_b, params_b + params_len, ';',
  5563. (std::numeric_limits<size_t>::max)(),
  5564. [&](const char *pb, const char *pe) -> bool {
  5565. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5566. auto len = static_cast<size_t>(pe - pb);
  5567. if (len < 2) { return false; }
  5568. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5569. return false;
  5570. }
  5571. // Trim the value portion
  5572. auto r = trim(pb, pe, 2, len);
  5573. if (r.first >= r.second) {
  5574. invalid = true;
  5575. return true;
  5576. }
  5577. double v = 0.0;
  5578. auto res = from_chars(pb + r.first, pb + r.second, v);
  5579. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5580. invalid = true;
  5581. return true;
  5582. }
  5583. quality = v;
  5584. return true;
  5585. });
  5586. return !invalid;
  5587. }
  5588. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5589. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5590. return EncodingType::None;
  5591. }
  5592. const auto &s = req.get_header_value("Accept-Encoding");
  5593. if (s.empty()) { return EncodingType::None; }
  5594. // Single-pass: iterate tokens and track the best supported encoding.
  5595. // Server preference breaks ties (br > gzip > zstd).
  5596. EncodingType best = EncodingType::None;
  5597. double best_q = 0.0; // q=0 means "not acceptable"
  5598. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5599. auto priority = [](EncodingType t) -> int {
  5600. switch (t) {
  5601. case EncodingType::Brotli: return 0;
  5602. case EncodingType::Gzip: return 1;
  5603. case EncodingType::Zstd: return 2;
  5604. default: return 3;
  5605. }
  5606. };
  5607. std::string name;
  5608. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5609. double quality = 1.0;
  5610. if (!parse_quality(b, e, name, quality)) { return; }
  5611. if (quality <= 0.0) { return; }
  5612. EncodingType type = EncodingType::None;
  5613. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5614. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5615. #endif
  5616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5617. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5618. type = EncodingType::Gzip;
  5619. }
  5620. #endif
  5621. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5622. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5623. type = EncodingType::Zstd;
  5624. }
  5625. #endif
  5626. if (type == EncodingType::None) { return; }
  5627. // Higher q-value wins; for equal q, server preference breaks ties
  5628. if (quality > best_q ||
  5629. (quality == best_q && priority(type) < priority(best))) {
  5630. best_q = quality;
  5631. best = type;
  5632. }
  5633. });
  5634. return best;
  5635. }
  5636. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5637. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5638. if (type == EncodingType::Gzip) {
  5639. return detail::make_unique<gzip_compressor>();
  5640. }
  5641. #endif
  5642. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5643. if (type == EncodingType::Brotli) {
  5644. return detail::make_unique<brotli_compressor>();
  5645. }
  5646. #endif
  5647. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5648. if (type == EncodingType::Zstd) {
  5649. return detail::make_unique<zstd_compressor>();
  5650. }
  5651. #endif
  5652. (void)type;
  5653. return nullptr;
  5654. }
  5655. inline const char *encoding_name(EncodingType type) {
  5656. switch (type) {
  5657. case EncodingType::Gzip: return "gzip";
  5658. case EncodingType::Brotli: return "br";
  5659. case EncodingType::Zstd: return "zstd";
  5660. default: return "";
  5661. }
  5662. }
  5663. inline bool nocompressor::compress(const char *data, size_t data_length,
  5664. bool /*last*/, Callback callback) {
  5665. if (!data_length) { return true; }
  5666. return callback(data, data_length);
  5667. }
  5668. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5669. inline gzip_compressor::gzip_compressor() {
  5670. std::memset(&strm_, 0, sizeof(strm_));
  5671. strm_.zalloc = Z_NULL;
  5672. strm_.zfree = Z_NULL;
  5673. strm_.opaque = Z_NULL;
  5674. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5675. Z_DEFAULT_STRATEGY) == Z_OK;
  5676. }
  5677. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5678. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5679. bool last, Callback callback) {
  5680. assert(is_valid_);
  5681. do {
  5682. constexpr size_t max_avail_in =
  5683. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5684. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5685. (std::min)(data_length, max_avail_in));
  5686. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5687. data_length -= strm_.avail_in;
  5688. data += strm_.avail_in;
  5689. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5690. auto ret = Z_OK;
  5691. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5692. do {
  5693. strm_.avail_out = static_cast<uInt>(buff.size());
  5694. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5695. ret = deflate(&strm_, flush);
  5696. if (ret == Z_STREAM_ERROR) { return false; }
  5697. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5698. return false;
  5699. }
  5700. } while (strm_.avail_out == 0);
  5701. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5702. (flush == Z_NO_FLUSH && ret == Z_OK));
  5703. assert(strm_.avail_in == 0);
  5704. } while (data_length > 0);
  5705. return true;
  5706. }
  5707. inline gzip_decompressor::gzip_decompressor() {
  5708. std::memset(&strm_, 0, sizeof(strm_));
  5709. strm_.zalloc = Z_NULL;
  5710. strm_.zfree = Z_NULL;
  5711. strm_.opaque = Z_NULL;
  5712. // 15 is the value of wbits, which should be at the maximum possible value
  5713. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5714. // that the stream type should be automatically detected either gzip or
  5715. // deflate.
  5716. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5717. }
  5718. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5719. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5720. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5721. Callback callback) {
  5722. assert(is_valid_);
  5723. auto ret = Z_OK;
  5724. do {
  5725. constexpr size_t max_avail_in =
  5726. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5727. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5728. (std::min)(data_length, max_avail_in));
  5729. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5730. data_length -= strm_.avail_in;
  5731. data += strm_.avail_in;
  5732. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5733. while (strm_.avail_in > 0 && ret == Z_OK) {
  5734. strm_.avail_out = static_cast<uInt>(buff.size());
  5735. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5736. ret = inflate(&strm_, Z_NO_FLUSH);
  5737. assert(ret != Z_STREAM_ERROR);
  5738. switch (ret) {
  5739. case Z_NEED_DICT:
  5740. case Z_DATA_ERROR:
  5741. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5742. }
  5743. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5744. return false;
  5745. }
  5746. }
  5747. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5748. } while (data_length > 0);
  5749. return true;
  5750. }
  5751. #endif
  5752. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5753. inline brotli_compressor::brotli_compressor() {
  5754. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5755. }
  5756. inline brotli_compressor::~brotli_compressor() {
  5757. BrotliEncoderDestroyInstance(state_);
  5758. }
  5759. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5760. bool last, Callback callback) {
  5761. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5762. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5763. auto available_in = data_length;
  5764. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5765. for (;;) {
  5766. if (last) {
  5767. if (BrotliEncoderIsFinished(state_)) { break; }
  5768. } else {
  5769. if (!available_in) { break; }
  5770. }
  5771. auto available_out = buff.size();
  5772. auto next_out = buff.data();
  5773. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5774. &available_out, &next_out, nullptr)) {
  5775. return false;
  5776. }
  5777. auto output_bytes = buff.size() - available_out;
  5778. if (output_bytes) {
  5779. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5780. }
  5781. }
  5782. return true;
  5783. }
  5784. inline brotli_decompressor::brotli_decompressor() {
  5785. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5786. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5787. : BROTLI_DECODER_RESULT_ERROR;
  5788. }
  5789. inline brotli_decompressor::~brotli_decompressor() {
  5790. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5791. }
  5792. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5793. inline bool brotli_decompressor::decompress(const char *data,
  5794. size_t data_length,
  5795. Callback callback) {
  5796. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5797. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5798. return 0;
  5799. }
  5800. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5801. size_t avail_in = data_length;
  5802. size_t total_out;
  5803. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5804. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5805. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5806. char *next_out = buff.data();
  5807. size_t avail_out = buff.size();
  5808. decoder_r = BrotliDecoderDecompressStream(
  5809. decoder_s, &avail_in, &next_in, &avail_out,
  5810. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5811. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5812. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5813. }
  5814. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5815. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5816. }
  5817. #endif
  5818. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5819. inline zstd_compressor::zstd_compressor() {
  5820. ctx_ = ZSTD_createCCtx();
  5821. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5822. }
  5823. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5824. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5825. bool last, Callback callback) {
  5826. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5827. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5828. ZSTD_inBuffer input = {data, data_length, 0};
  5829. bool finished;
  5830. do {
  5831. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5832. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5833. if (ZSTD_isError(remaining)) { return false; }
  5834. if (!callback(buff.data(), output.pos)) { return false; }
  5835. finished = last ? (remaining == 0) : (input.pos == input.size);
  5836. } while (!finished);
  5837. return true;
  5838. }
  5839. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5840. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5841. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5842. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5843. Callback callback) {
  5844. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5845. ZSTD_inBuffer input = {data, data_length, 0};
  5846. while (input.pos < input.size) {
  5847. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5848. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5849. if (ZSTD_isError(remaining)) { return false; }
  5850. if (!callback(buff.data(), output.pos)) { return false; }
  5851. }
  5852. return true;
  5853. }
  5854. #endif
  5855. inline std::unique_ptr<decompressor>
  5856. create_decompressor(const std::string &encoding) {
  5857. std::unique_ptr<decompressor> decompressor;
  5858. if (encoding == "gzip" || encoding == "deflate") {
  5859. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5860. decompressor = detail::make_unique<gzip_decompressor>();
  5861. #endif
  5862. } else if (encoding.find("br") != std::string::npos) {
  5863. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5864. decompressor = detail::make_unique<brotli_decompressor>();
  5865. #endif
  5866. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5867. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5868. decompressor = detail::make_unique<zstd_decompressor>();
  5869. #endif
  5870. }
  5871. return decompressor;
  5872. }
  5873. // Returns the best available compressor and its Content-Encoding name.
  5874. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5875. inline std::pair<std::unique_ptr<compressor>, const char *>
  5876. create_compressor() {
  5877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5878. return {detail::make_unique<brotli_compressor>(), "br"};
  5879. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5880. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5881. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5882. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5883. #else
  5884. return {nullptr, nullptr};
  5885. #endif
  5886. }
  5887. inline bool is_prohibited_header_name(const std::string &name) {
  5888. using udl::operator""_t;
  5889. switch (str2tag(name)) {
  5890. case "REMOTE_ADDR"_t:
  5891. case "REMOTE_PORT"_t:
  5892. case "LOCAL_ADDR"_t:
  5893. case "LOCAL_PORT"_t: return true;
  5894. default: return false;
  5895. }
  5896. }
  5897. inline bool has_header(const Headers &headers, const std::string &key) {
  5898. if (is_prohibited_header_name(key)) { return false; }
  5899. return headers.find(key) != headers.end();
  5900. }
  5901. inline const char *get_header_value(const Headers &headers,
  5902. const std::string &key, const char *def,
  5903. size_t id) {
  5904. if (is_prohibited_header_name(key)) {
  5905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5906. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5907. throw std::invalid_argument(msg);
  5908. #else
  5909. return "";
  5910. #endif
  5911. }
  5912. auto rng = headers.equal_range(key);
  5913. auto it = rng.first;
  5914. std::advance(it, static_cast<ssize_t>(id));
  5915. if (it != rng.second) { return it->second.c_str(); }
  5916. return def;
  5917. }
  5918. inline size_t get_header_value_count(const Headers &headers,
  5919. const std::string &key) {
  5920. auto r = headers.equal_range(key);
  5921. return static_cast<size_t>(std::distance(r.first, r.second));
  5922. }
  5923. template <typename Map>
  5924. inline typename Map::mapped_type
  5925. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5926. auto rng = m.equal_range(key);
  5927. auto it = rng.first;
  5928. std::advance(it, static_cast<ssize_t>(id));
  5929. if (it != rng.second) { return it->second; }
  5930. return typename Map::mapped_type();
  5931. }
  5932. inline void set_header(Headers &headers, const std::string &key,
  5933. const std::string &val) {
  5934. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5935. headers.emplace(key, val);
  5936. }
  5937. }
  5938. inline bool read_headers(Stream &strm, Headers &headers) {
  5939. const auto bufsiz = 2048;
  5940. char buf[bufsiz];
  5941. stream_line_reader line_reader(strm, buf, bufsiz);
  5942. size_t header_count = 0;
  5943. for (;;) {
  5944. if (!line_reader.getline()) { return false; }
  5945. // Check if the line ends with CRLF.
  5946. auto line_terminator_len = 2;
  5947. if (line_reader.end_with_crlf()) {
  5948. // Blank line indicates end of headers.
  5949. if (line_reader.size() == 2) { break; }
  5950. } else {
  5951. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5952. // Blank line indicates end of headers.
  5953. if (line_reader.size() == 1) { break; }
  5954. line_terminator_len = 1;
  5955. #else
  5956. continue; // Skip invalid line.
  5957. #endif
  5958. }
  5959. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5960. // Check header count limit
  5961. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5962. // Exclude line terminator
  5963. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5964. if (!parse_header(line_reader.ptr(), end,
  5965. [&](const std::string &key, const std::string &val) {
  5966. headers.emplace(key, val);
  5967. })) {
  5968. return false;
  5969. }
  5970. header_count++;
  5971. }
  5972. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5973. // headers that have different values to prevent request smuggling.
  5974. auto cl_range = headers.equal_range("Content-Length");
  5975. if (cl_range.first != cl_range.second) {
  5976. const auto &first_val = cl_range.first->second;
  5977. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5978. if (it->second != first_val) { return false; }
  5979. }
  5980. }
  5981. return true;
  5982. }
  5983. inline bool read_websocket_upgrade_response(Stream &strm,
  5984. const std::string &expected_accept,
  5985. std::string &selected_subprotocol) {
  5986. // Read status line
  5987. const auto bufsiz = 2048;
  5988. char buf[bufsiz];
  5989. stream_line_reader line_reader(strm, buf, bufsiz);
  5990. if (!line_reader.getline()) { return false; }
  5991. // Check for "HTTP/1.1 101"
  5992. auto line = std::string(line_reader.ptr(), line_reader.size());
  5993. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5994. // Parse headers using existing read_headers
  5995. Headers headers;
  5996. if (!read_headers(strm, headers)) { return false; }
  5997. // Verify Upgrade: websocket (case-insensitive)
  5998. auto upgrade_it = headers.find("Upgrade");
  5999. if (upgrade_it == headers.end()) { return false; }
  6000. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6001. if (upgrade_val != "websocket") { return false; }
  6002. // Verify Connection header contains "Upgrade" (case-insensitive)
  6003. auto connection_it = headers.find("Connection");
  6004. if (connection_it == headers.end()) { return false; }
  6005. auto connection_val = case_ignore::to_lower(connection_it->second);
  6006. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6007. // Verify Sec-WebSocket-Accept header value
  6008. auto it = headers.find("Sec-WebSocket-Accept");
  6009. if (it == headers.end() || it->second != expected_accept) { return false; }
  6010. // Extract negotiated subprotocol
  6011. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6012. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6013. return true;
  6014. }
  6015. enum class ReadContentResult {
  6016. Success, // Successfully read the content
  6017. PayloadTooLarge, // The content exceeds the specified payload limit
  6018. Error // An error occurred while reading the content
  6019. };
  6020. inline ReadContentResult read_content_with_length(
  6021. Stream &strm, size_t len, DownloadProgress progress,
  6022. ContentReceiverWithProgress out,
  6023. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6024. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6025. detail::BodyReader br;
  6026. br.stream = &strm;
  6027. br.has_content_length = true;
  6028. br.content_length = len;
  6029. br.payload_max_length = payload_max_length;
  6030. br.chunked = false;
  6031. br.bytes_read = 0;
  6032. br.last_error = Error::Success;
  6033. size_t r = 0;
  6034. while (r < len) {
  6035. auto read_len = static_cast<size_t>(len - r);
  6036. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6037. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6038. if (n <= 0) {
  6039. // Check if it was a payload size error
  6040. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6041. return ReadContentResult::PayloadTooLarge;
  6042. }
  6043. return ReadContentResult::Error;
  6044. }
  6045. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6046. return ReadContentResult::Error;
  6047. }
  6048. r += static_cast<size_t>(n);
  6049. if (progress) {
  6050. if (!progress(r, len)) { return ReadContentResult::Error; }
  6051. }
  6052. }
  6053. return ReadContentResult::Success;
  6054. }
  6055. inline ReadContentResult
  6056. read_content_without_length(Stream &strm, size_t payload_max_length,
  6057. ContentReceiverWithProgress out) {
  6058. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6059. size_t r = 0;
  6060. for (;;) {
  6061. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6062. if (n == 0) { return ReadContentResult::Success; }
  6063. if (n < 0) { return ReadContentResult::Error; }
  6064. // Check if adding this data would exceed the payload limit
  6065. if (r > payload_max_length ||
  6066. payload_max_length - r < static_cast<size_t>(n)) {
  6067. return ReadContentResult::PayloadTooLarge;
  6068. }
  6069. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6070. return ReadContentResult::Error;
  6071. }
  6072. r += static_cast<size_t>(n);
  6073. }
  6074. return ReadContentResult::Success;
  6075. }
  6076. template <typename T>
  6077. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6078. size_t payload_max_length,
  6079. ContentReceiverWithProgress out) {
  6080. detail::ChunkedDecoder dec(strm);
  6081. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6082. size_t total_len = 0;
  6083. for (;;) {
  6084. size_t chunk_offset = 0;
  6085. size_t chunk_total = 0;
  6086. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6087. if (n < 0) { return ReadContentResult::Error; }
  6088. if (n == 0) {
  6089. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6090. return ReadContentResult::Error;
  6091. }
  6092. return ReadContentResult::Success;
  6093. }
  6094. if (total_len > payload_max_length ||
  6095. payload_max_length - total_len < static_cast<size_t>(n)) {
  6096. return ReadContentResult::PayloadTooLarge;
  6097. }
  6098. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6099. return ReadContentResult::Error;
  6100. }
  6101. total_len += static_cast<size_t>(n);
  6102. }
  6103. }
  6104. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6105. return case_ignore::equal(
  6106. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  6107. }
  6108. template <typename T, typename U>
  6109. bool prepare_content_receiver(T &x, int &status,
  6110. ContentReceiverWithProgress receiver,
  6111. bool decompress, size_t payload_max_length,
  6112. bool &exceed_payload_max_length, U callback) {
  6113. if (decompress) {
  6114. std::string encoding = x.get_header_value("Content-Encoding");
  6115. std::unique_ptr<decompressor> decompressor;
  6116. if (!encoding.empty()) {
  6117. decompressor = detail::create_decompressor(encoding);
  6118. if (!decompressor) {
  6119. // Unsupported encoding or no support compiled in
  6120. status = StatusCode::UnsupportedMediaType_415;
  6121. return false;
  6122. }
  6123. }
  6124. if (decompressor) {
  6125. if (decompressor->is_valid()) {
  6126. size_t decompressed_size = 0;
  6127. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6128. size_t off, size_t len) {
  6129. return decompressor->decompress(
  6130. buf, n, [&](const char *buf2, size_t n2) {
  6131. // Guard against zip-bomb: check
  6132. // decompressed size against limit.
  6133. if (payload_max_length > 0 &&
  6134. (decompressed_size >= payload_max_length ||
  6135. n2 > payload_max_length - decompressed_size)) {
  6136. exceed_payload_max_length = true;
  6137. return false;
  6138. }
  6139. decompressed_size += n2;
  6140. return receiver(buf2, n2, off, len);
  6141. });
  6142. };
  6143. return callback(std::move(out));
  6144. } else {
  6145. status = StatusCode::InternalServerError_500;
  6146. return false;
  6147. }
  6148. }
  6149. }
  6150. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6151. size_t len) {
  6152. return receiver(buf, n, off, len);
  6153. };
  6154. return callback(std::move(out));
  6155. }
  6156. template <typename T>
  6157. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6158. DownloadProgress progress,
  6159. ContentReceiverWithProgress receiver, bool decompress) {
  6160. bool exceed_payload_max_length = false;
  6161. return prepare_content_receiver(
  6162. x, status, std::move(receiver), decompress, payload_max_length,
  6163. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6164. auto ret = true;
  6165. // Note: exceed_payload_max_length may also be set by the decompressor
  6166. // wrapper in prepare_content_receiver when the decompressed payload
  6167. // size exceeds the limit.
  6168. if (is_chunked_transfer_encoding(x.headers)) {
  6169. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6170. if (result == ReadContentResult::Success) {
  6171. ret = true;
  6172. } else if (result == ReadContentResult::PayloadTooLarge) {
  6173. exceed_payload_max_length = true;
  6174. ret = false;
  6175. } else {
  6176. ret = false;
  6177. }
  6178. } else if (!has_header(x.headers, "Content-Length")) {
  6179. auto result =
  6180. read_content_without_length(strm, payload_max_length, out);
  6181. if (result == ReadContentResult::Success) {
  6182. ret = true;
  6183. } else if (result == ReadContentResult::PayloadTooLarge) {
  6184. exceed_payload_max_length = true;
  6185. ret = false;
  6186. } else {
  6187. ret = false;
  6188. }
  6189. } else {
  6190. auto is_invalid_value = false;
  6191. auto len = get_header_value_u64(x.headers, "Content-Length",
  6192. (std::numeric_limits<size_t>::max)(),
  6193. 0, is_invalid_value);
  6194. if (is_invalid_value) {
  6195. ret = false;
  6196. } else if (len > 0) {
  6197. auto result = read_content_with_length(
  6198. strm, len, std::move(progress), out, payload_max_length);
  6199. ret = (result == ReadContentResult::Success);
  6200. if (result == ReadContentResult::PayloadTooLarge) {
  6201. exceed_payload_max_length = true;
  6202. }
  6203. }
  6204. }
  6205. if (!ret) {
  6206. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6207. : StatusCode::BadRequest_400;
  6208. }
  6209. return ret;
  6210. });
  6211. }
  6212. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6213. const std::string &path) {
  6214. std::string s = method;
  6215. s += ' ';
  6216. s += path;
  6217. s += " HTTP/1.1\r\n";
  6218. return strm.write(s.data(), s.size());
  6219. }
  6220. inline ssize_t write_response_line(Stream &strm, int status) {
  6221. std::string s = "HTTP/1.1 ";
  6222. s += std::to_string(status);
  6223. s += ' ';
  6224. s += httplib::status_message(status);
  6225. s += "\r\n";
  6226. return strm.write(s.data(), s.size());
  6227. }
  6228. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6229. ssize_t write_len = 0;
  6230. for (const auto &x : headers) {
  6231. std::string s;
  6232. s = x.first;
  6233. s += ": ";
  6234. s += x.second;
  6235. s += "\r\n";
  6236. auto len = strm.write(s.data(), s.size());
  6237. if (len < 0) { return len; }
  6238. write_len += len;
  6239. }
  6240. auto len = strm.write("\r\n");
  6241. if (len < 0) { return len; }
  6242. write_len += len;
  6243. return write_len;
  6244. }
  6245. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6246. size_t offset = 0;
  6247. while (offset < l) {
  6248. auto length = strm.write(d + offset, l - offset);
  6249. if (length < 0) { return false; }
  6250. offset += static_cast<size_t>(length);
  6251. }
  6252. return true;
  6253. }
  6254. template <typename T>
  6255. inline bool write_content_with_progress(Stream &strm,
  6256. const ContentProvider &content_provider,
  6257. size_t offset, size_t length,
  6258. T is_shutting_down,
  6259. const UploadProgress &upload_progress,
  6260. Error &error) {
  6261. size_t end_offset = offset + length;
  6262. size_t start_offset = offset;
  6263. auto ok = true;
  6264. DataSink data_sink;
  6265. data_sink.write = [&](const char *d, size_t l) -> bool {
  6266. if (ok) {
  6267. if (write_data(strm, d, l)) {
  6268. offset += l;
  6269. if (upload_progress && length > 0) {
  6270. size_t current_written = offset - start_offset;
  6271. if (!upload_progress(current_written, length)) {
  6272. ok = false;
  6273. return false;
  6274. }
  6275. }
  6276. } else {
  6277. ok = false;
  6278. }
  6279. }
  6280. return ok;
  6281. };
  6282. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6283. while (offset < end_offset && !is_shutting_down()) {
  6284. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6285. error = Error::Write;
  6286. return false;
  6287. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6288. error = Error::Canceled;
  6289. return false;
  6290. } else if (!ok) {
  6291. error = Error::Write;
  6292. return false;
  6293. }
  6294. }
  6295. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6296. error = Error::Write;
  6297. return false;
  6298. }
  6299. error = Error::Success;
  6300. return true;
  6301. }
  6302. template <typename T>
  6303. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6304. size_t offset, size_t length, T is_shutting_down,
  6305. Error &error) {
  6306. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6307. is_shutting_down, nullptr, error);
  6308. }
  6309. template <typename T>
  6310. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6311. size_t offset, size_t length,
  6312. const T &is_shutting_down) {
  6313. auto error = Error::Success;
  6314. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6315. error);
  6316. }
  6317. template <typename T>
  6318. inline bool
  6319. write_content_without_length(Stream &strm,
  6320. const ContentProvider &content_provider,
  6321. const T &is_shutting_down) {
  6322. size_t offset = 0;
  6323. auto data_available = true;
  6324. auto ok = true;
  6325. DataSink data_sink;
  6326. data_sink.write = [&](const char *d, size_t l) -> bool {
  6327. if (ok) {
  6328. offset += l;
  6329. if (!write_data(strm, d, l)) { ok = false; }
  6330. }
  6331. return ok;
  6332. };
  6333. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6334. data_sink.done = [&](void) { data_available = false; };
  6335. while (data_available && !is_shutting_down()) {
  6336. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6337. return false;
  6338. } else if (!content_provider(offset, 0, data_sink)) {
  6339. return false;
  6340. } else if (!ok) {
  6341. return false;
  6342. }
  6343. }
  6344. return !data_available; // true only if done() was called, false if shutting
  6345. // down
  6346. }
  6347. template <typename T, typename U>
  6348. inline bool
  6349. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6350. const T &is_shutting_down, U &compressor, Error &error) {
  6351. size_t offset = 0;
  6352. auto data_available = true;
  6353. auto ok = true;
  6354. DataSink data_sink;
  6355. data_sink.write = [&](const char *d, size_t l) -> bool {
  6356. if (ok) {
  6357. data_available = l > 0;
  6358. offset += l;
  6359. std::string payload;
  6360. if (compressor.compress(d, l, false,
  6361. [&](const char *data, size_t data_len) {
  6362. payload.append(data, data_len);
  6363. return true;
  6364. })) {
  6365. if (!payload.empty()) {
  6366. // Emit chunked response header and footer for each chunk
  6367. auto chunk =
  6368. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6369. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6370. }
  6371. } else {
  6372. ok = false;
  6373. }
  6374. }
  6375. return ok;
  6376. };
  6377. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6378. auto done_with_trailer = [&](const Headers *trailer) {
  6379. if (!ok) { return; }
  6380. data_available = false;
  6381. std::string payload;
  6382. if (!compressor.compress(nullptr, 0, true,
  6383. [&](const char *data, size_t data_len) {
  6384. payload.append(data, data_len);
  6385. return true;
  6386. })) {
  6387. ok = false;
  6388. return;
  6389. }
  6390. if (!payload.empty()) {
  6391. // Emit chunked response header and footer for each chunk
  6392. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6393. if (!write_data(strm, chunk.data(), chunk.size())) {
  6394. ok = false;
  6395. return;
  6396. }
  6397. }
  6398. constexpr const char done_marker[] = "0\r\n";
  6399. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6400. // Trailer
  6401. if (trailer) {
  6402. for (const auto &kv : *trailer) {
  6403. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6404. if (!write_data(strm, field_line.data(), field_line.size())) {
  6405. ok = false;
  6406. }
  6407. }
  6408. }
  6409. constexpr const char crlf[] = "\r\n";
  6410. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6411. };
  6412. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6413. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6414. done_with_trailer(&trailer);
  6415. };
  6416. while (data_available && !is_shutting_down()) {
  6417. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6418. error = Error::Write;
  6419. return false;
  6420. } else if (!content_provider(offset, 0, data_sink)) {
  6421. error = Error::Canceled;
  6422. return false;
  6423. } else if (!ok) {
  6424. error = Error::Write;
  6425. return false;
  6426. }
  6427. }
  6428. if (data_available) { // exited due to is_shutting_down(), not done()
  6429. error = Error::Write;
  6430. return false;
  6431. }
  6432. error = Error::Success;
  6433. return true;
  6434. }
  6435. template <typename T, typename U>
  6436. inline bool write_content_chunked(Stream &strm,
  6437. const ContentProvider &content_provider,
  6438. const T &is_shutting_down, U &compressor) {
  6439. auto error = Error::Success;
  6440. return write_content_chunked(strm, content_provider, is_shutting_down,
  6441. compressor, error);
  6442. }
  6443. template <typename T>
  6444. inline bool redirect(T &cli, Request &req, Response &res,
  6445. const std::string &path, const std::string &location,
  6446. Error &error) {
  6447. Request new_req = req;
  6448. new_req.path = path;
  6449. new_req.redirect_count_ -= 1;
  6450. if (res.status == StatusCode::SeeOther_303 &&
  6451. (req.method != "GET" && req.method != "HEAD")) {
  6452. new_req.method = "GET";
  6453. new_req.body.clear();
  6454. new_req.headers.clear();
  6455. }
  6456. Response new_res;
  6457. auto ret = cli.send(new_req, new_res, error);
  6458. if (ret) {
  6459. req = std::move(new_req);
  6460. res = std::move(new_res);
  6461. if (res.location.empty()) { res.location = location; }
  6462. }
  6463. return ret;
  6464. }
  6465. inline std::string params_to_query_str(const Params &params) {
  6466. std::string query;
  6467. for (auto it = params.begin(); it != params.end(); ++it) {
  6468. if (it != params.begin()) { query += '&'; }
  6469. query += encode_query_component(it->first);
  6470. query += '=';
  6471. query += encode_query_component(it->second);
  6472. }
  6473. return query;
  6474. }
  6475. inline void parse_query_text(const char *data, std::size_t size,
  6476. Params &params) {
  6477. std::set<std::string> cache;
  6478. split(data, data + size, '&', [&](const char *b, const char *e) {
  6479. std::string kv(b, e);
  6480. if (cache.find(kv) != cache.end()) { return; }
  6481. cache.insert(std::move(kv));
  6482. std::string key;
  6483. std::string val;
  6484. divide(b, static_cast<std::size_t>(e - b), '=',
  6485. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6486. std::size_t rhs_size) {
  6487. key.assign(lhs_data, lhs_size);
  6488. val.assign(rhs_data, rhs_size);
  6489. });
  6490. if (!key.empty()) {
  6491. params.emplace(decode_query_component(key), decode_query_component(val));
  6492. }
  6493. });
  6494. }
  6495. inline void parse_query_text(const std::string &s, Params &params) {
  6496. parse_query_text(s.data(), s.size(), params);
  6497. }
  6498. // Normalize a query string by decoding and re-encoding each key/value pair
  6499. // while preserving the original parameter order. This avoids double-encoding
  6500. // and ensures consistent encoding without reordering (unlike Params which
  6501. // uses std::multimap and sorts keys).
  6502. inline std::string normalize_query_string(const std::string &query) {
  6503. std::string result;
  6504. split(query.data(), query.data() + query.size(), '&',
  6505. [&](const char *b, const char *e) {
  6506. std::string key;
  6507. std::string val;
  6508. divide(b, static_cast<std::size_t>(e - b), '=',
  6509. [&](const char *lhs_data, std::size_t lhs_size,
  6510. const char *rhs_data, std::size_t rhs_size) {
  6511. key.assign(lhs_data, lhs_size);
  6512. val.assign(rhs_data, rhs_size);
  6513. });
  6514. if (!key.empty()) {
  6515. auto dec_key = decode_query_component(key);
  6516. auto dec_val = decode_query_component(val);
  6517. if (!result.empty()) { result += '&'; }
  6518. result += encode_query_component(dec_key);
  6519. if (!val.empty() || std::find(b, e, '=') != e) {
  6520. result += '=';
  6521. result += encode_query_component(dec_val);
  6522. }
  6523. }
  6524. });
  6525. return result;
  6526. }
  6527. inline bool parse_multipart_boundary(const std::string &content_type,
  6528. std::string &boundary) {
  6529. std::map<std::string, std::string> params;
  6530. extract_media_type(content_type, &params);
  6531. auto it = params.find("boundary");
  6532. if (it == params.end()) { return false; }
  6533. boundary = it->second;
  6534. return !boundary.empty();
  6535. }
  6536. inline void parse_disposition_params(const std::string &s, Params &params) {
  6537. std::set<std::string> cache;
  6538. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6539. std::string kv(b, e);
  6540. if (cache.find(kv) != cache.end()) { return; }
  6541. cache.insert(kv);
  6542. std::string key;
  6543. std::string val;
  6544. split(b, e, '=', [&](const char *b2, const char *e2) {
  6545. if (key.empty()) {
  6546. key.assign(b2, e2);
  6547. } else {
  6548. val.assign(b2, e2);
  6549. }
  6550. });
  6551. if (!key.empty()) {
  6552. params.emplace(trim_double_quotes_copy((key)),
  6553. trim_double_quotes_copy((val)));
  6554. }
  6555. });
  6556. }
  6557. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6558. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6559. #else
  6560. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6561. #endif
  6562. auto is_valid = [](const std::string &str) {
  6563. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6564. };
  6565. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6566. const auto pos = static_cast<size_t>(6);
  6567. const auto len = static_cast<size_t>(s.size() - 6);
  6568. auto all_valid_ranges = true;
  6569. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6570. if (!all_valid_ranges) { return; }
  6571. const auto it = std::find(b, e, '-');
  6572. if (it == e) {
  6573. all_valid_ranges = false;
  6574. return;
  6575. }
  6576. const auto lhs = std::string(b, it);
  6577. const auto rhs = std::string(it + 1, e);
  6578. if (!is_valid(lhs) || !is_valid(rhs)) {
  6579. all_valid_ranges = false;
  6580. return;
  6581. }
  6582. ssize_t first = -1;
  6583. if (!lhs.empty()) {
  6584. ssize_t v;
  6585. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6586. if (res.ec == std::errc{}) { first = v; }
  6587. }
  6588. ssize_t last = -1;
  6589. if (!rhs.empty()) {
  6590. ssize_t v;
  6591. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6592. if (res.ec == std::errc{}) { last = v; }
  6593. }
  6594. if ((first == -1 && last == -1) ||
  6595. (first != -1 && last != -1 && first > last)) {
  6596. all_valid_ranges = false;
  6597. return;
  6598. }
  6599. ranges.emplace_back(first, last);
  6600. });
  6601. return all_valid_ranges && !ranges.empty();
  6602. }
  6603. return false;
  6604. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6605. }
  6606. #else
  6607. } catch (...) { return false; }
  6608. #endif
  6609. inline bool parse_accept_header(const std::string &s,
  6610. std::vector<std::string> &content_types) {
  6611. content_types.clear();
  6612. // Empty string is considered valid (no preference)
  6613. if (s.empty()) { return true; }
  6614. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6615. if (s.front() == ',' || s.back() == ',' ||
  6616. s.find(",,") != std::string::npos) {
  6617. return false;
  6618. }
  6619. struct AcceptEntry {
  6620. std::string media_type;
  6621. double quality;
  6622. int order;
  6623. };
  6624. std::vector<AcceptEntry> entries;
  6625. int order = 0;
  6626. bool has_invalid_entry = false;
  6627. // Split by comma and parse each entry
  6628. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6629. std::string entry(b, e);
  6630. entry = trim_copy(entry);
  6631. if (entry.empty()) {
  6632. has_invalid_entry = true;
  6633. return;
  6634. }
  6635. AcceptEntry accept_entry;
  6636. accept_entry.order = order++;
  6637. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6638. accept_entry.media_type, accept_entry.quality)) {
  6639. has_invalid_entry = true;
  6640. return;
  6641. }
  6642. // Remove additional parameters from media type
  6643. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6644. // Basic validation of media type format
  6645. if (accept_entry.media_type.empty()) {
  6646. has_invalid_entry = true;
  6647. return;
  6648. }
  6649. // Check for basic media type format (should contain '/' or be '*')
  6650. if (accept_entry.media_type != "*" &&
  6651. accept_entry.media_type.find('/') == std::string::npos) {
  6652. has_invalid_entry = true;
  6653. return;
  6654. }
  6655. entries.push_back(std::move(accept_entry));
  6656. });
  6657. // Return false if any invalid entry was found
  6658. if (has_invalid_entry) { return false; }
  6659. // Sort by quality (descending), then by original order (ascending)
  6660. std::sort(entries.begin(), entries.end(),
  6661. [](const AcceptEntry &a, const AcceptEntry &b) {
  6662. if (a.quality != b.quality) {
  6663. return a.quality > b.quality; // Higher quality first
  6664. }
  6665. return a.order < b.order; // Earlier order first for same quality
  6666. });
  6667. // Extract sorted media types
  6668. content_types.reserve(entries.size());
  6669. for (auto &entry : entries) {
  6670. content_types.push_back(std::move(entry.media_type));
  6671. }
  6672. return true;
  6673. }
  6674. class FormDataParser {
  6675. public:
  6676. FormDataParser() = default;
  6677. void set_boundary(std::string &&boundary) {
  6678. boundary_ = std::move(boundary);
  6679. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6680. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6681. }
  6682. bool is_valid() const { return is_valid_; }
  6683. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6684. const ContentReceiver &content_callback) {
  6685. buf_append(buf, n);
  6686. while (buf_size() > 0) {
  6687. switch (state_) {
  6688. case 0: { // Initial boundary
  6689. auto pos = buf_find(dash_boundary_crlf_);
  6690. if (pos == buf_size()) { return true; }
  6691. buf_erase(pos + dash_boundary_crlf_.size());
  6692. state_ = 1;
  6693. break;
  6694. }
  6695. case 1: { // New entry
  6696. clear_file_info();
  6697. state_ = 2;
  6698. break;
  6699. }
  6700. case 2: { // Headers
  6701. auto pos = buf_find(crlf_);
  6702. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6703. while (pos < buf_size()) {
  6704. // Empty line
  6705. if (pos == 0) {
  6706. if (!header_callback(file_)) {
  6707. is_valid_ = false;
  6708. return false;
  6709. }
  6710. buf_erase(crlf_.size());
  6711. state_ = 3;
  6712. break;
  6713. }
  6714. const auto header = buf_head(pos);
  6715. if (!parse_header(header.data(), header.data() + header.size(),
  6716. [&](const std::string &, const std::string &) {})) {
  6717. is_valid_ = false;
  6718. return false;
  6719. }
  6720. // Parse and emplace space trimmed headers into a map
  6721. if (!parse_header(
  6722. header.data(), header.data() + header.size(),
  6723. [&](const std::string &key, const std::string &val) {
  6724. file_.headers.emplace(key, val);
  6725. })) {
  6726. is_valid_ = false;
  6727. return false;
  6728. }
  6729. constexpr const char header_content_type[] = "Content-Type:";
  6730. if (start_with_case_ignore(header, header_content_type)) {
  6731. file_.content_type =
  6732. trim_copy(header.substr(str_len(header_content_type)));
  6733. } else {
  6734. std::string disposition_params;
  6735. if (parse_content_disposition(header, disposition_params)) {
  6736. Params params;
  6737. parse_disposition_params(disposition_params, params);
  6738. auto it = params.find("name");
  6739. if (it != params.end()) {
  6740. file_.name = it->second;
  6741. } else {
  6742. is_valid_ = false;
  6743. return false;
  6744. }
  6745. it = params.find("filename");
  6746. if (it != params.end()) { file_.filename = it->second; }
  6747. it = params.find("filename*");
  6748. if (it != params.end()) {
  6749. // RFC 5987: only UTF-8 encoding is allowed
  6750. const auto &val = it->second;
  6751. constexpr const char utf8_prefix[] = "UTF-8''";
  6752. constexpr size_t prefix_len = str_len(utf8_prefix);
  6753. if (val.size() > prefix_len &&
  6754. start_with_case_ignore(val, utf8_prefix)) {
  6755. file_.filename = decode_path_component(
  6756. val.substr(prefix_len)); // override...
  6757. } else {
  6758. is_valid_ = false;
  6759. return false;
  6760. }
  6761. }
  6762. }
  6763. }
  6764. buf_erase(pos + crlf_.size());
  6765. pos = buf_find(crlf_);
  6766. }
  6767. if (state_ != 3) { return true; }
  6768. break;
  6769. }
  6770. case 3: { // Body
  6771. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6772. auto pos = buf_find(crlf_dash_boundary_);
  6773. if (pos < buf_size()) {
  6774. if (!content_callback(buf_data(), pos)) {
  6775. is_valid_ = false;
  6776. return false;
  6777. }
  6778. buf_erase(pos + crlf_dash_boundary_.size());
  6779. state_ = 4;
  6780. } else {
  6781. auto len = buf_size() - crlf_dash_boundary_.size();
  6782. if (len > 0) {
  6783. if (!content_callback(buf_data(), len)) {
  6784. is_valid_ = false;
  6785. return false;
  6786. }
  6787. buf_erase(len);
  6788. }
  6789. return true;
  6790. }
  6791. break;
  6792. }
  6793. case 4: { // Boundary
  6794. if (crlf_.size() > buf_size()) { return true; }
  6795. if (buf_start_with(crlf_)) {
  6796. buf_erase(crlf_.size());
  6797. state_ = 1;
  6798. } else {
  6799. if (dash_.size() > buf_size()) { return true; }
  6800. if (buf_start_with(dash_)) {
  6801. buf_erase(dash_.size());
  6802. is_valid_ = true;
  6803. buf_erase(buf_size()); // Remove epilogue
  6804. } else {
  6805. return true;
  6806. }
  6807. }
  6808. break;
  6809. }
  6810. }
  6811. }
  6812. return true;
  6813. }
  6814. private:
  6815. void clear_file_info() {
  6816. file_.name.clear();
  6817. file_.filename.clear();
  6818. file_.content_type.clear();
  6819. file_.headers.clear();
  6820. }
  6821. bool start_with_case_ignore(const std::string &a, const char *b,
  6822. size_t offset = 0) const {
  6823. const auto b_len = strlen(b);
  6824. if (a.size() < offset + b_len) { return false; }
  6825. for (size_t i = 0; i < b_len; i++) {
  6826. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6827. return false;
  6828. }
  6829. }
  6830. return true;
  6831. }
  6832. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6833. // Returns true if header matches, with the params portion in `params_out`.
  6834. bool parse_content_disposition(const std::string &header,
  6835. std::string &params_out) const {
  6836. constexpr const char prefix[] = "Content-Disposition:";
  6837. constexpr size_t prefix_len = str_len(prefix);
  6838. if (!start_with_case_ignore(header, prefix)) { return false; }
  6839. // Skip whitespace after "Content-Disposition:"
  6840. auto pos = prefix_len;
  6841. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6842. pos++;
  6843. }
  6844. // Match "form-data;" (case-insensitive)
  6845. constexpr const char form_data[] = "form-data;";
  6846. constexpr size_t form_data_len = str_len(form_data);
  6847. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6848. pos += form_data_len;
  6849. // Skip whitespace after "form-data;"
  6850. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6851. pos++;
  6852. }
  6853. params_out = header.substr(pos);
  6854. return true;
  6855. }
  6856. const std::string dash_ = "--";
  6857. const std::string crlf_ = "\r\n";
  6858. std::string boundary_;
  6859. std::string dash_boundary_crlf_;
  6860. std::string crlf_dash_boundary_;
  6861. size_t state_ = 0;
  6862. bool is_valid_ = false;
  6863. FormData file_;
  6864. // Buffer
  6865. bool start_with(const std::string &a, size_t spos, size_t epos,
  6866. const std::string &b) const {
  6867. if (epos - spos < b.size()) { return false; }
  6868. for (size_t i = 0; i < b.size(); i++) {
  6869. if (a[i + spos] != b[i]) { return false; }
  6870. }
  6871. return true;
  6872. }
  6873. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6874. const char *buf_data() const { return &buf_[buf_spos_]; }
  6875. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6876. bool buf_start_with(const std::string &s) const {
  6877. return start_with(buf_, buf_spos_, buf_epos_, s);
  6878. }
  6879. size_t buf_find(const std::string &s) const {
  6880. auto c = s.front();
  6881. size_t off = buf_spos_;
  6882. while (off < buf_epos_) {
  6883. auto pos = off;
  6884. while (true) {
  6885. if (pos == buf_epos_) { return buf_size(); }
  6886. if (buf_[pos] == c) { break; }
  6887. pos++;
  6888. }
  6889. auto remaining_size = buf_epos_ - pos;
  6890. if (s.size() > remaining_size) { return buf_size(); }
  6891. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6892. off = pos + 1;
  6893. }
  6894. return buf_size();
  6895. }
  6896. void buf_append(const char *data, size_t n) {
  6897. auto remaining_size = buf_size();
  6898. if (remaining_size > 0 && buf_spos_ > 0) {
  6899. for (size_t i = 0; i < remaining_size; i++) {
  6900. buf_[i] = buf_[buf_spos_ + i];
  6901. }
  6902. }
  6903. buf_spos_ = 0;
  6904. buf_epos_ = remaining_size;
  6905. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6906. for (size_t i = 0; i < n; i++) {
  6907. buf_[buf_epos_ + i] = data[i];
  6908. }
  6909. buf_epos_ += n;
  6910. }
  6911. void buf_erase(size_t size) { buf_spos_ += size; }
  6912. std::string buf_;
  6913. size_t buf_spos_ = 0;
  6914. size_t buf_epos_ = 0;
  6915. };
  6916. inline std::string random_string(size_t length) {
  6917. constexpr const char data[] =
  6918. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6919. thread_local auto engine([]() {
  6920. // std::random_device might actually be deterministic on some
  6921. // platforms, but due to lack of support in the c++ standard library,
  6922. // doing better requires either some ugly hacks or breaking portability.
  6923. std::random_device seed_gen;
  6924. // Request 128 bits of entropy for initialization
  6925. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6926. return std::mt19937(seed_sequence);
  6927. }());
  6928. std::string result;
  6929. for (size_t i = 0; i < length; i++) {
  6930. result += data[engine() % (sizeof(data) - 1)];
  6931. }
  6932. return result;
  6933. }
  6934. inline std::string make_multipart_data_boundary() {
  6935. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6936. }
  6937. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6938. auto valid = true;
  6939. for (size_t i = 0; i < boundary.size(); i++) {
  6940. auto c = boundary[i];
  6941. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  6942. valid = false;
  6943. break;
  6944. }
  6945. }
  6946. return valid;
  6947. }
  6948. // Escape a multipart field name/filename following the WHATWG HTML standard
  6949. // ("escape a multipart form-data name"), which is what browsers send:
  6950. // '"' -> %22, CR -> %0D, LF -> %0A
  6951. // With escape_quote = false, only CR and LF are escaped; this is for header
  6952. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  6953. inline std::string escape_multipart_field(const std::string &s,
  6954. bool escape_quote = true) {
  6955. std::string result;
  6956. result.reserve(s.size());
  6957. for (auto c : s) {
  6958. switch (c) {
  6959. case '"':
  6960. if (escape_quote) {
  6961. result += "%22";
  6962. } else {
  6963. result += c;
  6964. }
  6965. break;
  6966. case '\r': result += "%0D"; break;
  6967. case '\n': result += "%0A"; break;
  6968. default: result += c; break;
  6969. }
  6970. }
  6971. return result;
  6972. }
  6973. template <typename T>
  6974. inline std::string
  6975. serialize_multipart_formdata_item_begin(const T &item,
  6976. const std::string &boundary) {
  6977. std::string body = "--" + boundary + "\r\n";
  6978. body += "Content-Disposition: form-data; name=\"" +
  6979. escape_multipart_field(item.name) + "\"";
  6980. if (!item.filename.empty()) {
  6981. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  6982. }
  6983. body += "\r\n";
  6984. if (!item.content_type.empty()) {
  6985. body +=
  6986. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  6987. "\r\n";
  6988. }
  6989. body += "\r\n";
  6990. return body;
  6991. }
  6992. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6993. inline std::string
  6994. serialize_multipart_formdata_finish(const std::string &boundary) {
  6995. return "--" + boundary + "--\r\n";
  6996. }
  6997. inline std::string
  6998. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6999. return "multipart/form-data; boundary=" + boundary;
  7000. }
  7001. inline std::string
  7002. serialize_multipart_formdata(const UploadFormDataItems &items,
  7003. const std::string &boundary, bool finish = true) {
  7004. std::string body;
  7005. for (const auto &item : items) {
  7006. body += serialize_multipart_formdata_item_begin(item, boundary);
  7007. body += item.content + serialize_multipart_formdata_item_end();
  7008. }
  7009. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7010. return body;
  7011. }
  7012. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7013. const std::string &boundary) {
  7014. size_t total = 0;
  7015. for (const auto &item : items) {
  7016. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7017. total += item.content.size();
  7018. total += serialize_multipart_formdata_item_end().size();
  7019. }
  7020. total += serialize_multipart_formdata_finish(boundary).size();
  7021. return total;
  7022. }
  7023. struct MultipartSegment {
  7024. const char *data;
  7025. size_t size;
  7026. };
  7027. // NOTE: items must outlive the returned ContentProvider
  7028. // (safe for synchronous use inside Post/Put/Patch)
  7029. inline ContentProvider
  7030. make_multipart_content_provider(const UploadFormDataItems &items,
  7031. const std::string &boundary) {
  7032. // Own the per-item header strings and the finish string
  7033. std::vector<std::string> owned;
  7034. owned.reserve(items.size() + 1);
  7035. for (const auto &item : items)
  7036. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7037. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7038. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7039. std::vector<MultipartSegment> segs;
  7040. segs.reserve(items.size() * 3 + 1);
  7041. static const char crlf[] = "\r\n";
  7042. for (size_t i = 0; i < items.size(); i++) {
  7043. segs.push_back({owned[i].data(), owned[i].size()});
  7044. segs.push_back({items[i].content.data(), items[i].content.size()});
  7045. segs.push_back({crlf, 2});
  7046. }
  7047. segs.push_back({owned.back().data(), owned.back().size()});
  7048. struct MultipartState {
  7049. std::vector<std::string> owned;
  7050. std::vector<MultipartSegment> segs;
  7051. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7052. };
  7053. auto state = std::make_shared<MultipartState>();
  7054. state->owned = std::move(owned);
  7055. // `segs` holds raw pointers into owned strings; std::string move preserves
  7056. // the data pointer, so these pointers remain valid after the move above.
  7057. state->segs = std::move(segs);
  7058. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7059. // Buffer multiple small segments into fewer, larger writes to avoid
  7060. // excessive TCP packets when there are many form data items (#2410)
  7061. auto &buf = state->buf;
  7062. auto buf_size = buf.size();
  7063. size_t buf_len = 0;
  7064. size_t remaining = length;
  7065. // Find the first segment containing 'offset'
  7066. size_t pos = 0;
  7067. size_t seg_idx = 0;
  7068. for (; seg_idx < state->segs.size(); seg_idx++) {
  7069. const auto &seg = state->segs[seg_idx];
  7070. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7071. pos += seg.size;
  7072. }
  7073. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7074. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7075. const auto &seg = state->segs[seg_idx];
  7076. size_t available = seg.size - seg_offset;
  7077. size_t to_copy = (std::min)(available, remaining);
  7078. const char *src = seg.data + seg_offset;
  7079. seg_offset = 0; // only the first segment has a non-zero offset
  7080. while (to_copy > 0) {
  7081. size_t space = buf_size - buf_len;
  7082. size_t chunk = (std::min)(to_copy, space);
  7083. std::memcpy(buf.data() + buf_len, src, chunk);
  7084. buf_len += chunk;
  7085. src += chunk;
  7086. to_copy -= chunk;
  7087. remaining -= chunk;
  7088. if (buf_len == buf_size) {
  7089. if (!sink.write(buf.data(), buf_len)) { return false; }
  7090. buf_len = 0;
  7091. }
  7092. }
  7093. }
  7094. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7095. return true;
  7096. };
  7097. }
  7098. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7099. if (ranges.size() <= 1) return;
  7100. // Sort ranges by start position
  7101. std::sort(ranges.begin(), ranges.end(),
  7102. [](const Range &a, const Range &b) { return a.first < b.first; });
  7103. Ranges coalesced;
  7104. coalesced.reserve(ranges.size());
  7105. for (auto &r : ranges) {
  7106. auto first_pos = r.first;
  7107. auto last_pos = r.second;
  7108. // Handle special cases like in range_error
  7109. if (first_pos == -1 && last_pos == -1) {
  7110. first_pos = 0;
  7111. last_pos = static_cast<ssize_t>(content_length);
  7112. }
  7113. if (first_pos == -1) {
  7114. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7115. last_pos = static_cast<ssize_t>(content_length) - 1;
  7116. }
  7117. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7118. last_pos = static_cast<ssize_t>(content_length) - 1;
  7119. }
  7120. // Skip invalid ranges
  7121. if (!(0 <= first_pos && first_pos <= last_pos &&
  7122. last_pos < static_cast<ssize_t>(content_length))) {
  7123. continue;
  7124. }
  7125. // Coalesce with previous range if overlapping or adjacent (but not
  7126. // identical)
  7127. if (!coalesced.empty()) {
  7128. auto &prev = coalesced.back();
  7129. // Check if current range overlaps or is adjacent to previous range
  7130. // but don't coalesce identical ranges (allow duplicates)
  7131. if (first_pos <= prev.second + 1 &&
  7132. !(first_pos == prev.first && last_pos == prev.second)) {
  7133. // Extend the previous range
  7134. prev.second = (std::max)(prev.second, last_pos);
  7135. continue;
  7136. }
  7137. }
  7138. // Add new range
  7139. coalesced.emplace_back(first_pos, last_pos);
  7140. }
  7141. ranges = std::move(coalesced);
  7142. }
  7143. inline bool range_error(Request &req, Response &res) {
  7144. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7145. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7146. req.ranges.clear();
  7147. if (res.status == StatusCode::PartialContent_206) {
  7148. res.status = StatusCode::OK_200;
  7149. }
  7150. return false;
  7151. }
  7152. ssize_t content_len = static_cast<ssize_t>(
  7153. res.content_length_ ? res.content_length_ : res.body.size());
  7154. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7155. size_t overwrapping_count = 0;
  7156. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7157. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7158. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7159. // Too many ranges
  7160. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7161. for (auto &r : req.ranges) {
  7162. auto &first_pos = r.first;
  7163. auto &last_pos = r.second;
  7164. if (first_pos == -1 && last_pos == -1) {
  7165. first_pos = 0;
  7166. last_pos = content_len;
  7167. }
  7168. if (first_pos == -1) {
  7169. first_pos = content_len - last_pos;
  7170. last_pos = content_len - 1;
  7171. }
  7172. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7173. // A client can limit the number of bytes requested without knowing the
  7174. // size of the selected representation. If the last-pos value is absent,
  7175. // or if the value is greater than or equal to the current length of the
  7176. // representation data, the byte range is interpreted as the remainder of
  7177. // the representation (i.e., the server replaces the value of last-pos
  7178. // with a value that is one less than the current length of the selected
  7179. // representation).
  7180. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7181. if (last_pos == -1 || last_pos >= content_len) {
  7182. last_pos = content_len - 1;
  7183. }
  7184. // Range must be within content length
  7185. if (!(0 <= first_pos && first_pos <= last_pos &&
  7186. last_pos <= content_len - 1)) {
  7187. return true;
  7188. }
  7189. // Request must not have more than two overlapping ranges
  7190. for (const auto &processed_range : processed_ranges) {
  7191. if (!(last_pos < processed_range.first ||
  7192. first_pos > processed_range.second)) {
  7193. overwrapping_count++;
  7194. if (overwrapping_count > 2) { return true; }
  7195. break; // Only count once per range
  7196. }
  7197. }
  7198. processed_ranges.emplace_back(first_pos, last_pos);
  7199. }
  7200. // After validation, coalesce overlapping ranges as per RFC 9110
  7201. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7202. }
  7203. return false;
  7204. }
  7205. inline std::pair<size_t, size_t>
  7206. get_range_offset_and_length(Range r, size_t content_length) {
  7207. assert(r.first != -1 && r.second != -1);
  7208. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7209. assert(r.first <= r.second &&
  7210. r.second < static_cast<ssize_t>(content_length));
  7211. (void)(content_length);
  7212. return std::make_pair(static_cast<size_t>(r.first),
  7213. static_cast<size_t>(r.second - r.first) + 1);
  7214. }
  7215. inline std::string make_content_range_header_field(
  7216. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7217. auto st = offset_and_length.first;
  7218. auto ed = st + offset_and_length.second - 1;
  7219. std::string field = "bytes ";
  7220. field += std::to_string(st);
  7221. field += '-';
  7222. field += std::to_string(ed);
  7223. field += '/';
  7224. field += std::to_string(content_length);
  7225. return field;
  7226. }
  7227. template <typename SToken, typename CToken, typename Content>
  7228. bool process_multipart_ranges_data(const Request &req,
  7229. const std::string &boundary,
  7230. const std::string &content_type,
  7231. size_t content_length, SToken stoken,
  7232. CToken ctoken, Content content) {
  7233. for (size_t i = 0; i < req.ranges.size(); i++) {
  7234. ctoken("--");
  7235. stoken(boundary);
  7236. ctoken("\r\n");
  7237. if (!content_type.empty()) {
  7238. ctoken("Content-Type: ");
  7239. stoken(content_type);
  7240. ctoken("\r\n");
  7241. }
  7242. auto offset_and_length =
  7243. get_range_offset_and_length(req.ranges[i], content_length);
  7244. ctoken("Content-Range: ");
  7245. stoken(make_content_range_header_field(offset_and_length, content_length));
  7246. ctoken("\r\n");
  7247. ctoken("\r\n");
  7248. if (!content(offset_and_length.first, offset_and_length.second)) {
  7249. return false;
  7250. }
  7251. ctoken("\r\n");
  7252. }
  7253. ctoken("--");
  7254. stoken(boundary);
  7255. ctoken("--");
  7256. return true;
  7257. }
  7258. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7259. const std::string &boundary,
  7260. const std::string &content_type,
  7261. size_t content_length,
  7262. std::string &data) {
  7263. process_multipart_ranges_data(
  7264. req, boundary, content_type, content_length,
  7265. [&](const std::string &token) { data += token; },
  7266. [&](const std::string &token) { data += token; },
  7267. [&](size_t offset, size_t length) {
  7268. assert(offset + length <= content_length);
  7269. data += res.body.substr(offset, length);
  7270. return true;
  7271. });
  7272. }
  7273. inline size_t get_multipart_ranges_data_length(const Request &req,
  7274. const std::string &boundary,
  7275. const std::string &content_type,
  7276. size_t content_length) {
  7277. size_t data_length = 0;
  7278. process_multipart_ranges_data(
  7279. req, boundary, content_type, content_length,
  7280. [&](const std::string &token) { data_length += token.size(); },
  7281. [&](const std::string &token) { data_length += token.size(); },
  7282. [&](size_t /*offset*/, size_t length) {
  7283. data_length += length;
  7284. return true;
  7285. });
  7286. return data_length;
  7287. }
  7288. template <typename T>
  7289. inline bool
  7290. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7291. const std::string &boundary,
  7292. const std::string &content_type,
  7293. size_t content_length, const T &is_shutting_down) {
  7294. return process_multipart_ranges_data(
  7295. req, boundary, content_type, content_length,
  7296. [&](const std::string &token) { strm.write(token); },
  7297. [&](const std::string &token) { strm.write(token); },
  7298. [&](size_t offset, size_t length) {
  7299. return write_content(strm, res.content_provider_, offset, length,
  7300. is_shutting_down);
  7301. });
  7302. }
  7303. inline bool has_framed_body(const Request &req) {
  7304. return is_chunked_transfer_encoding(req.headers) ||
  7305. req.get_header_value_u64("Content-Length") > 0;
  7306. }
  7307. inline bool is_connection_persistent(const Request &req) {
  7308. auto conn = req.get_header_value("Connection");
  7309. if (conn == "close") { return false; }
  7310. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7311. return true;
  7312. }
  7313. inline bool expect_content(const Request &req) {
  7314. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7315. req.method == "DELETE") {
  7316. return true;
  7317. }
  7318. return has_framed_body(req);
  7319. }
  7320. #ifdef _WIN32
  7321. class WSInit {
  7322. public:
  7323. WSInit() {
  7324. WSADATA wsaData;
  7325. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7326. }
  7327. ~WSInit() {
  7328. if (is_valid_) WSACleanup();
  7329. }
  7330. bool is_valid_ = false;
  7331. };
  7332. static WSInit wsinit_;
  7333. #endif
  7334. inline bool parse_www_authenticate(const Response &res,
  7335. std::map<std::string, std::string> &auth,
  7336. bool is_proxy) {
  7337. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7338. if (res.has_header(auth_key)) {
  7339. thread_local auto re =
  7340. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7341. auto s = res.get_header_value(auth_key);
  7342. auto pos = s.find(' ');
  7343. if (pos != std::string::npos) {
  7344. auto type = s.substr(0, pos);
  7345. if (type == "Basic") {
  7346. return false;
  7347. } else if (type == "Digest") {
  7348. s = s.substr(pos + 1);
  7349. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7350. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7351. const auto &m = *i;
  7352. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7353. static_cast<size_t>(m.length(1)));
  7354. auto val = m.length(2) > 0
  7355. ? s.substr(static_cast<size_t>(m.position(2)),
  7356. static_cast<size_t>(m.length(2)))
  7357. : s.substr(static_cast<size_t>(m.position(3)),
  7358. static_cast<size_t>(m.length(3)));
  7359. auth[std::move(key)] = std::move(val);
  7360. }
  7361. return true;
  7362. }
  7363. }
  7364. }
  7365. return false;
  7366. }
  7367. class ContentProviderAdapter {
  7368. public:
  7369. explicit ContentProviderAdapter(
  7370. ContentProviderWithoutLength &&content_provider)
  7371. : content_provider_(std::move(content_provider)) {}
  7372. bool operator()(size_t offset, size_t, DataSink &sink) {
  7373. return content_provider_(offset, sink);
  7374. }
  7375. private:
  7376. ContentProviderWithoutLength content_provider_;
  7377. };
  7378. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7379. namespace fields {
  7380. inline bool is_token_char(char c) {
  7381. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7382. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7383. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7384. }
  7385. inline bool is_token(const std::string &s) {
  7386. if (s.empty()) { return false; }
  7387. for (auto c : s) {
  7388. if (!is_token_char(c)) { return false; }
  7389. }
  7390. return true;
  7391. }
  7392. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7393. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7394. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7395. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7396. inline bool is_field_content(const std::string &s) {
  7397. if (s.empty()) { return true; }
  7398. if (s.size() == 1) {
  7399. return is_field_vchar(s[0]);
  7400. } else if (s.size() == 2) {
  7401. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7402. } else {
  7403. size_t i = 0;
  7404. if (!is_field_vchar(s[i])) { return false; }
  7405. i++;
  7406. while (i < s.size() - 1) {
  7407. auto c = s[i++];
  7408. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7409. } else {
  7410. return false;
  7411. }
  7412. }
  7413. return is_field_vchar(s[i]);
  7414. }
  7415. }
  7416. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7417. } // namespace fields
  7418. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7419. int port, bool is_ssl,
  7420. const std::string &path,
  7421. const Headers &headers,
  7422. std::string &selected_subprotocol) {
  7423. // Validate path and host
  7424. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7425. return false;
  7426. }
  7427. // Validate user-provided headers
  7428. for (const auto &h : headers) {
  7429. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7430. return false;
  7431. }
  7432. }
  7433. // Generate random Sec-WebSocket-Key
  7434. thread_local std::mt19937 rng(std::random_device{}());
  7435. std::string key_bytes(16, '\0');
  7436. for (size_t i = 0; i < 16; i += 4) {
  7437. auto r = rng();
  7438. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7439. }
  7440. auto client_key = base64_encode(key_bytes);
  7441. // Build upgrade request
  7442. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7443. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7444. req_str += "Upgrade: websocket\r\n";
  7445. req_str += "Connection: Upgrade\r\n";
  7446. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7447. req_str += "Sec-WebSocket-Version: 13\r\n";
  7448. for (const auto &h : headers) {
  7449. req_str += h.first + ": " + h.second + "\r\n";
  7450. }
  7451. req_str += "\r\n";
  7452. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7453. // Verify 101 response and Sec-WebSocket-Accept header
  7454. auto expected_accept = websocket_accept_key(client_key);
  7455. return read_websocket_upgrade_response(strm, expected_accept,
  7456. selected_subprotocol);
  7457. }
  7458. } // namespace detail
  7459. /*
  7460. * Group 2: detail namespace - SSL common utilities
  7461. */
  7462. #ifdef CPPHTTPLIB_SSL_ENABLED
  7463. namespace detail {
  7464. class SSLSocketStream final : public Stream {
  7465. public:
  7466. SSLSocketStream(
  7467. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7468. time_t read_timeout_usec, time_t write_timeout_sec,
  7469. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7470. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7471. (std::chrono::steady_clock::time_point::min)());
  7472. ~SSLSocketStream() override;
  7473. bool is_readable() const override;
  7474. bool wait_readable() const override;
  7475. bool wait_writable() const override;
  7476. bool is_peer_alive() const override;
  7477. ssize_t read(char *ptr, size_t size) override;
  7478. ssize_t write(const char *ptr, size_t size) override;
  7479. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7480. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7481. socket_t socket() const override;
  7482. time_t duration() const override;
  7483. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7484. private:
  7485. socket_t sock_;
  7486. tls::session_t session_;
  7487. time_t read_timeout_sec_;
  7488. time_t read_timeout_usec_;
  7489. time_t write_timeout_sec_;
  7490. time_t write_timeout_usec_;
  7491. time_t max_timeout_msec_;
  7492. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7493. };
  7494. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7495. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7496. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7497. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7498. unsigned int hash_length = 0;
  7499. unsigned char hash[EVP_MAX_MD_SIZE];
  7500. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7501. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7502. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7503. std::stringstream ss;
  7504. for (auto i = 0u; i < hash_length; ++i) {
  7505. ss << std::hex << std::setw(2) << std::setfill('0')
  7506. << static_cast<unsigned int>(hash[i]);
  7507. }
  7508. return ss.str();
  7509. }
  7510. inline std::string MD5(const std::string &s) {
  7511. return message_digest(s, EVP_md5());
  7512. }
  7513. inline std::string SHA_256(const std::string &s) {
  7514. return message_digest(s, EVP_sha256());
  7515. }
  7516. inline std::string SHA_512(const std::string &s) {
  7517. return message_digest(s, EVP_sha512());
  7518. }
  7519. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7520. namespace {
  7521. template <size_t N>
  7522. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7523. std::stringstream ss;
  7524. for (size_t i = 0; i < N; ++i) {
  7525. ss << std::hex << std::setw(2) << std::setfill('0')
  7526. << static_cast<unsigned int>(hash[i]);
  7527. }
  7528. return ss.str();
  7529. }
  7530. } // namespace
  7531. inline std::string MD5(const std::string &s) {
  7532. unsigned char hash[16];
  7533. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7534. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7535. hash);
  7536. #else
  7537. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7538. hash);
  7539. #endif
  7540. return hash_to_hex(hash);
  7541. }
  7542. inline std::string SHA_256(const std::string &s) {
  7543. unsigned char hash[32];
  7544. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7545. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7546. hash, 0);
  7547. #else
  7548. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7549. s.size(), hash, 0);
  7550. #endif
  7551. return hash_to_hex(hash);
  7552. }
  7553. inline std::string SHA_512(const std::string &s) {
  7554. unsigned char hash[64];
  7555. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7556. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7557. hash, 0);
  7558. #else
  7559. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7560. s.size(), hash, 0);
  7561. #endif
  7562. return hash_to_hex(hash);
  7563. }
  7564. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7565. namespace {
  7566. template <size_t N>
  7567. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7568. std::stringstream ss;
  7569. for (size_t i = 0; i < N; ++i) {
  7570. ss << std::hex << std::setw(2) << std::setfill('0')
  7571. << static_cast<unsigned int>(hash[i]);
  7572. }
  7573. return ss.str();
  7574. }
  7575. } // namespace
  7576. inline std::string MD5(const std::string &s) {
  7577. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7578. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7579. static_cast<word32>(s.size()), hash);
  7580. return hash_to_hex(hash);
  7581. }
  7582. inline std::string SHA_256(const std::string &s) {
  7583. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7584. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7585. static_cast<word32>(s.size()), hash);
  7586. return hash_to_hex(hash);
  7587. }
  7588. inline std::string SHA_512(const std::string &s) {
  7589. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7590. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7591. static_cast<word32>(s.size()), hash);
  7592. return hash_to_hex(hash);
  7593. }
  7594. #endif
  7595. inline bool is_ip_address(const std::string &host) {
  7596. struct in_addr addr4;
  7597. struct in6_addr addr6;
  7598. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7599. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7600. }
  7601. template <typename T>
  7602. inline bool process_server_socket_ssl(
  7603. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7604. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7605. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7606. time_t write_timeout_usec, T callback) {
  7607. return process_server_socket_core(
  7608. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7609. [&](bool close_connection, bool &connection_closed) {
  7610. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7611. write_timeout_sec, write_timeout_usec);
  7612. return callback(strm, close_connection, connection_closed);
  7613. });
  7614. }
  7615. template <typename T>
  7616. inline bool process_client_socket_ssl(
  7617. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7618. time_t read_timeout_usec, time_t write_timeout_sec,
  7619. time_t write_timeout_usec, time_t max_timeout_msec,
  7620. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7621. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7622. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7623. start_time);
  7624. return callback(strm);
  7625. }
  7626. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7627. const Request &req, const std::map<std::string, std::string> &auth,
  7628. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7629. const std::string &password, bool is_proxy = false) {
  7630. std::string nc;
  7631. {
  7632. std::stringstream ss;
  7633. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7634. nc = ss.str();
  7635. }
  7636. std::string qop;
  7637. if (auth.find("qop") != auth.end()) {
  7638. qop = auth.at("qop");
  7639. if (qop.find("auth-int") != std::string::npos) {
  7640. qop = "auth-int";
  7641. } else if (qop.find("auth") != std::string::npos) {
  7642. qop = "auth";
  7643. } else {
  7644. qop.clear();
  7645. }
  7646. }
  7647. std::string algo = "MD5";
  7648. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7649. std::string response;
  7650. {
  7651. auto H = algo == "SHA-256" ? detail::SHA_256
  7652. : algo == "SHA-512" ? detail::SHA_512
  7653. : detail::MD5;
  7654. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7655. auto A2 = req.method + ":" + req.path;
  7656. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7657. if (qop.empty()) {
  7658. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7659. } else {
  7660. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7661. ":" + qop + ":" + H(A2));
  7662. }
  7663. }
  7664. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7665. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7666. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7667. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7668. (qop.empty() ? ", response=\""
  7669. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7670. cnonce + "\", response=\"") +
  7671. response + "\"" +
  7672. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7673. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7674. return std::make_pair(key, field);
  7675. }
  7676. inline bool match_hostname(const std::string &pattern,
  7677. const std::string &hostname) {
  7678. // Exact match (case-insensitive)
  7679. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7680. // Split both pattern and hostname into components by '.'
  7681. std::vector<std::string> pattern_components;
  7682. if (!pattern.empty()) {
  7683. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7684. [&](const char *b, const char *e) {
  7685. pattern_components.emplace_back(b, e);
  7686. });
  7687. }
  7688. std::vector<std::string> host_components;
  7689. if (!hostname.empty()) {
  7690. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7691. [&](const char *b, const char *e) {
  7692. host_components.emplace_back(b, e);
  7693. });
  7694. }
  7695. // Component count must match
  7696. if (host_components.size() != pattern_components.size()) { return false; }
  7697. // Compare each component with wildcard support
  7698. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7699. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7700. auto itr = pattern_components.begin();
  7701. for (const auto &h : host_components) {
  7702. auto &p = *itr;
  7703. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7704. bool partial_match = false;
  7705. if (!p.empty() && p[p.size() - 1] == '*') {
  7706. const auto prefix_length = p.size() - 1;
  7707. if (prefix_length == 0) {
  7708. partial_match = true;
  7709. } else if (h.size() >= prefix_length) {
  7710. partial_match =
  7711. std::equal(p.begin(),
  7712. p.begin() + static_cast<std::string::difference_type>(
  7713. prefix_length),
  7714. h.begin(), [](const char ca, const char cb) {
  7715. return detail::case_ignore::to_lower(ca) ==
  7716. detail::case_ignore::to_lower(cb);
  7717. });
  7718. }
  7719. }
  7720. if (!partial_match) { return false; }
  7721. }
  7722. ++itr;
  7723. }
  7724. return true;
  7725. }
  7726. #ifdef _WIN32
  7727. // Verify certificate using Windows CertGetCertificateChain API.
  7728. // This provides real-time certificate validation with Windows Update
  7729. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7730. inline bool
  7731. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7732. const std::string &hostname,
  7733. bool verify_hostname, uint64_t &out_error) {
  7734. if (der_cert.empty()) { return false; }
  7735. out_error = 0;
  7736. // Create Windows certificate context from DER data
  7737. auto cert_context = CertCreateCertificateContext(
  7738. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7739. static_cast<DWORD>(der_cert.size()));
  7740. if (!cert_context) {
  7741. out_error = GetLastError();
  7742. return false;
  7743. }
  7744. auto cert_guard =
  7745. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7746. // Setup chain parameters
  7747. CERT_CHAIN_PARA chain_para = {};
  7748. chain_para.cbSize = sizeof(chain_para);
  7749. // Build certificate chain with revocation checking
  7750. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7751. auto chain_result = CertGetCertificateChain(
  7752. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7753. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7754. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7755. nullptr, &chain_context);
  7756. if (!chain_result || !chain_context) {
  7757. out_error = GetLastError();
  7758. return false;
  7759. }
  7760. auto chain_guard =
  7761. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7762. // Check if chain has errors
  7763. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7764. out_error = chain_context->TrustStatus.dwErrorStatus;
  7765. return false;
  7766. }
  7767. // Verify SSL policy
  7768. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7769. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7770. #ifdef AUTHTYPE_SERVER
  7771. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7772. #endif
  7773. std::wstring whost;
  7774. if (verify_hostname) {
  7775. whost = u8string_to_wstring(hostname.c_str());
  7776. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7777. }
  7778. CERT_CHAIN_POLICY_PARA policy_para = {};
  7779. policy_para.cbSize = sizeof(policy_para);
  7780. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7781. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7782. #else
  7783. policy_para.dwFlags = 0;
  7784. #endif
  7785. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7786. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7787. policy_status.cbSize = sizeof(policy_status);
  7788. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7789. &policy_para, &policy_status)) {
  7790. out_error = GetLastError();
  7791. return false;
  7792. }
  7793. if (policy_status.dwError != 0) {
  7794. out_error = policy_status.dwError;
  7795. return false;
  7796. }
  7797. return true;
  7798. }
  7799. #endif // _WIN32
  7800. // Loads CA file/dir configuration and applies the system CA policy to a
  7801. // client TLS context. PEM data and native stores are applied to the context
  7802. // directly at set time; has_custom_store reflects them for the Auto policy
  7803. // decision.
  7804. inline bool load_client_ca_config(tls::ctx_t ctx,
  7805. const std::string &ca_cert_file_path,
  7806. const std::string &ca_cert_dir_path,
  7807. bool has_custom_store, SystemCAMode mode,
  7808. uint64_t &backend_error) {
  7809. auto ret = true;
  7810. if (!ca_cert_file_path.empty()) {
  7811. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7812. backend_error = tls::get_error();
  7813. ret = false;
  7814. }
  7815. } else if (!ca_cert_dir_path.empty()) {
  7816. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7817. backend_error = tls::get_error();
  7818. ret = false;
  7819. }
  7820. }
  7821. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7822. !ca_cert_dir_path.empty() || has_custom_store;
  7823. if (mode == SystemCAMode::Enabled ||
  7824. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7825. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7826. }
  7827. return ret;
  7828. }
  7829. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7830. tls::session_t &session, socket_t sock,
  7831. bool server_certificate_verification,
  7832. time_t timeout_sec, time_t timeout_usec) {
  7833. using namespace tls;
  7834. if (!ctx) { return false; }
  7835. bool is_ip = is_ip_address(host);
  7836. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7837. // Chain verification happens during the handshake even for IP hosts; the
  7838. // certificate identity is verified post-handshake via verify_hostname()
  7839. set_verify_client(ctx, server_certificate_verification);
  7840. #endif
  7841. session = create_session(ctx, sock);
  7842. if (!session) { return false; }
  7843. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7844. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7845. // their identity is checked post-handshake below instead.
  7846. if (!is_ip) {
  7847. if (server_certificate_verification) {
  7848. set_hostname(session, host.c_str());
  7849. } else {
  7850. set_sni(session, host.c_str());
  7851. }
  7852. }
  7853. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7854. return false;
  7855. }
  7856. if (server_certificate_verification) {
  7857. if (get_verify_result(session) != 0) { return false; }
  7858. // Identity check against the peer certificate, post-handshake for all
  7859. // backends (same as SSLClient). For IP hosts this is the only identity
  7860. // verification since no hostname is bound during the handshake.
  7861. auto server_cert = get_peer_cert(session);
  7862. if (!server_cert) { return false; }
  7863. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7864. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7865. }
  7866. return true;
  7867. }
  7868. } // namespace detail
  7869. #endif // CPPHTTPLIB_SSL_ENABLED
  7870. /*
  7871. * Group 3: httplib namespace - Non-SSL public API implementations
  7872. */
  7873. inline void default_socket_options(socket_t sock) {
  7874. set_socket_opt(sock, SOL_SOCKET,
  7875. #ifdef SO_REUSEPORT
  7876. SO_REUSEPORT,
  7877. #else
  7878. SO_REUSEADDR,
  7879. #endif
  7880. 1);
  7881. }
  7882. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7883. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7884. sizeof(optval));
  7885. }
  7886. inline std::string get_bearer_token_auth(const Request &req) {
  7887. if (req.has_header("Authorization")) {
  7888. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7889. return req.get_header_value("Authorization")
  7890. .substr(bearer_header_prefix_len);
  7891. }
  7892. return "";
  7893. }
  7894. inline const char *status_message(int status) {
  7895. switch (status) {
  7896. case StatusCode::Continue_100: return "Continue";
  7897. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7898. case StatusCode::Processing_102: return "Processing";
  7899. case StatusCode::EarlyHints_103: return "Early Hints";
  7900. case StatusCode::OK_200: return "OK";
  7901. case StatusCode::Created_201: return "Created";
  7902. case StatusCode::Accepted_202: return "Accepted";
  7903. case StatusCode::NonAuthoritativeInformation_203:
  7904. return "Non-Authoritative Information";
  7905. case StatusCode::NoContent_204: return "No Content";
  7906. case StatusCode::ResetContent_205: return "Reset Content";
  7907. case StatusCode::PartialContent_206: return "Partial Content";
  7908. case StatusCode::MultiStatus_207: return "Multi-Status";
  7909. case StatusCode::AlreadyReported_208: return "Already Reported";
  7910. case StatusCode::IMUsed_226: return "IM Used";
  7911. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7912. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7913. case StatusCode::Found_302: return "Found";
  7914. case StatusCode::SeeOther_303: return "See Other";
  7915. case StatusCode::NotModified_304: return "Not Modified";
  7916. case StatusCode::UseProxy_305: return "Use Proxy";
  7917. case StatusCode::unused_306: return "unused";
  7918. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7919. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7920. case StatusCode::BadRequest_400: return "Bad Request";
  7921. case StatusCode::Unauthorized_401: return "Unauthorized";
  7922. case StatusCode::PaymentRequired_402: return "Payment Required";
  7923. case StatusCode::Forbidden_403: return "Forbidden";
  7924. case StatusCode::NotFound_404: return "Not Found";
  7925. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7926. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7927. case StatusCode::ProxyAuthenticationRequired_407:
  7928. return "Proxy Authentication Required";
  7929. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7930. case StatusCode::Conflict_409: return "Conflict";
  7931. case StatusCode::Gone_410: return "Gone";
  7932. case StatusCode::LengthRequired_411: return "Length Required";
  7933. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7934. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7935. case StatusCode::UriTooLong_414: return "URI Too Long";
  7936. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7937. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7938. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7939. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7940. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7941. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7942. case StatusCode::Locked_423: return "Locked";
  7943. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7944. case StatusCode::TooEarly_425: return "Too Early";
  7945. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7946. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7947. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7948. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7949. return "Request Header Fields Too Large";
  7950. case StatusCode::UnavailableForLegalReasons_451:
  7951. return "Unavailable For Legal Reasons";
  7952. case StatusCode::NotImplemented_501: return "Not Implemented";
  7953. case StatusCode::BadGateway_502: return "Bad Gateway";
  7954. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7955. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7956. case StatusCode::HttpVersionNotSupported_505:
  7957. return "HTTP Version Not Supported";
  7958. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7959. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7960. case StatusCode::LoopDetected_508: return "Loop Detected";
  7961. case StatusCode::NotExtended_510: return "Not Extended";
  7962. case StatusCode::NetworkAuthenticationRequired_511:
  7963. return "Network Authentication Required";
  7964. default:
  7965. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7966. }
  7967. }
  7968. inline std::string to_string(const Error error) {
  7969. switch (error) {
  7970. case Error::Success: return "Success (no error)";
  7971. case Error::Unknown: return "Unknown";
  7972. case Error::Connection: return "Could not establish connection";
  7973. case Error::BindIPAddress: return "Failed to bind IP address";
  7974. case Error::Read: return "Failed to read connection";
  7975. case Error::Write: return "Failed to write connection";
  7976. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7977. case Error::Canceled: return "Connection handling canceled";
  7978. case Error::SSLConnection: return "SSL connection failed";
  7979. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7980. case Error::SSLServerVerification: return "SSL server verification failed";
  7981. case Error::SSLServerHostnameVerification:
  7982. return "SSL server hostname verification failed";
  7983. case Error::UnsupportedMultipartBoundaryChars:
  7984. return "Unsupported HTTP multipart boundary characters";
  7985. case Error::Compression: return "Compression failed";
  7986. case Error::ConnectionTimeout: return "Connection timed out";
  7987. case Error::ProxyConnection: return "Proxy connection failed";
  7988. case Error::ConnectionClosed: return "Connection closed by server";
  7989. case Error::Timeout: return "Read timeout";
  7990. case Error::ResourceExhaustion: return "Resource exhaustion";
  7991. case Error::TooManyFormDataFiles: return "Too many form data files";
  7992. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7993. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7994. case Error::ExceedMaxSocketDescriptorCount:
  7995. return "Exceeded maximum socket descriptor count";
  7996. case Error::InvalidRequestLine: return "Invalid request line";
  7997. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7998. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7999. case Error::InvalidHeaders: return "Invalid headers";
  8000. case Error::MultipartParsing: return "Multipart parsing failed";
  8001. case Error::OpenFile: return "Failed to open file";
  8002. case Error::Listen: return "Failed to listen on socket";
  8003. case Error::GetSockName: return "Failed to get socket name";
  8004. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8005. case Error::HTTPParsing: return "HTTP parsing failed";
  8006. case Error::InvalidRangeHeader: return "Invalid Range header";
  8007. default: break;
  8008. }
  8009. return "Invalid";
  8010. }
  8011. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8012. os << to_string(obj);
  8013. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8014. return os;
  8015. }
  8016. inline std::string hosted_at(const std::string &hostname) {
  8017. std::vector<std::string> addrs;
  8018. hosted_at(hostname, addrs);
  8019. if (addrs.empty()) { return std::string(); }
  8020. return addrs[0];
  8021. }
  8022. inline void hosted_at(const std::string &hostname,
  8023. std::vector<std::string> &addrs) {
  8024. struct addrinfo hints;
  8025. struct addrinfo *result;
  8026. memset(&hints, 0, sizeof(struct addrinfo));
  8027. hints.ai_family = AF_UNSPEC;
  8028. hints.ai_socktype = SOCK_STREAM;
  8029. hints.ai_protocol = 0;
  8030. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8031. &result, 0)) {
  8032. #if defined __linux__ && !defined __ANDROID__
  8033. res_init();
  8034. #endif
  8035. return;
  8036. }
  8037. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8038. for (auto rp = result; rp; rp = rp->ai_next) {
  8039. const auto &addr =
  8040. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8041. std::string ip;
  8042. auto dummy = -1;
  8043. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8044. dummy)) {
  8045. addrs.emplace_back(std::move(ip));
  8046. }
  8047. }
  8048. }
  8049. inline std::string encode_uri_component(const std::string &value) {
  8050. std::ostringstream escaped;
  8051. escaped.fill('0');
  8052. escaped << std::hex;
  8053. for (auto c : value) {
  8054. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8055. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8056. escaped << c;
  8057. } else {
  8058. escaped << std::uppercase;
  8059. escaped << '%' << std::setw(2)
  8060. << static_cast<int>(static_cast<unsigned char>(c));
  8061. escaped << std::nouppercase;
  8062. }
  8063. }
  8064. return escaped.str();
  8065. }
  8066. inline std::string encode_uri(const std::string &value) {
  8067. std::ostringstream escaped;
  8068. escaped.fill('0');
  8069. escaped << std::hex;
  8070. for (auto c : value) {
  8071. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8072. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8073. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8074. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8075. escaped << c;
  8076. } else {
  8077. escaped << std::uppercase;
  8078. escaped << '%' << std::setw(2)
  8079. << static_cast<int>(static_cast<unsigned char>(c));
  8080. escaped << std::nouppercase;
  8081. }
  8082. }
  8083. return escaped.str();
  8084. }
  8085. inline std::string decode_uri_component(const std::string &value) {
  8086. std::string result;
  8087. for (size_t i = 0; i < value.size(); i++) {
  8088. if (value[i] == '%' && i + 2 < value.size()) {
  8089. auto val = 0;
  8090. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8091. result += static_cast<char>(val);
  8092. i += 2;
  8093. } else {
  8094. result += value[i];
  8095. }
  8096. } else {
  8097. result += value[i];
  8098. }
  8099. }
  8100. return result;
  8101. }
  8102. inline std::string decode_uri(const std::string &value) {
  8103. std::string result;
  8104. for (size_t i = 0; i < value.size(); i++) {
  8105. if (value[i] == '%' && i + 2 < value.size()) {
  8106. auto val = 0;
  8107. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8108. result += static_cast<char>(val);
  8109. i += 2;
  8110. } else {
  8111. result += value[i];
  8112. }
  8113. } else {
  8114. result += value[i];
  8115. }
  8116. }
  8117. return result;
  8118. }
  8119. inline std::string encode_path_component(const std::string &component) {
  8120. std::string result;
  8121. result.reserve(component.size() * 3);
  8122. for (size_t i = 0; i < component.size(); i++) {
  8123. auto c = static_cast<unsigned char>(component[i]);
  8124. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8125. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8126. c == '_' || c == '~') {
  8127. result += static_cast<char>(c);
  8128. }
  8129. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8130. // "," / ";" / "="
  8131. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8132. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8133. c == '=') {
  8134. result += static_cast<char>(c);
  8135. }
  8136. // Colon is allowed in path segments except first segment
  8137. else if (c == ':') {
  8138. result += static_cast<char>(c);
  8139. }
  8140. // @ is allowed in path
  8141. else if (c == '@') {
  8142. result += static_cast<char>(c);
  8143. } else {
  8144. result += '%';
  8145. char hex[3];
  8146. snprintf(hex, sizeof(hex), "%02X", c);
  8147. result.append(hex, 2);
  8148. }
  8149. }
  8150. return result;
  8151. }
  8152. inline std::string decode_path_component(const std::string &component) {
  8153. std::string result;
  8154. result.reserve(component.size());
  8155. for (size_t i = 0; i < component.size(); i++) {
  8156. if (component[i] == '%' && i + 1 < component.size()) {
  8157. if (component[i + 1] == 'u') {
  8158. // Unicode %uXXXX encoding
  8159. auto val = 0;
  8160. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8161. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8162. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8163. char buff[4];
  8164. size_t len = detail::to_utf8(val, buff);
  8165. if (len > 0) { result.append(buff, len); }
  8166. i += 5; // 'u0000'
  8167. } else {
  8168. result += component[i];
  8169. }
  8170. } else {
  8171. // Standard %XX encoding
  8172. auto val = 0;
  8173. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8174. // 2 digits hex codes
  8175. result += static_cast<char>(val);
  8176. i += 2; // 'XX'
  8177. } else {
  8178. result += component[i];
  8179. }
  8180. }
  8181. } else {
  8182. result += component[i];
  8183. }
  8184. }
  8185. return result;
  8186. }
  8187. inline std::string encode_query_component(const std::string &component,
  8188. bool space_as_plus) {
  8189. std::string result;
  8190. result.reserve(component.size() * 3);
  8191. for (size_t i = 0; i < component.size(); i++) {
  8192. auto c = static_cast<unsigned char>(component[i]);
  8193. // Unreserved characters per RFC 3986
  8194. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8195. c == '_' || c == '~') {
  8196. result += static_cast<char>(c);
  8197. }
  8198. // Space handling
  8199. else if (c == ' ') {
  8200. if (space_as_plus) {
  8201. result += '+';
  8202. } else {
  8203. result += "%20";
  8204. }
  8205. }
  8206. // Plus sign handling
  8207. else if (c == '+') {
  8208. if (space_as_plus) {
  8209. result += "%2B";
  8210. } else {
  8211. result += static_cast<char>(c);
  8212. }
  8213. }
  8214. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8215. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8216. c == '*' || c == ',' || c == ';') {
  8217. result += static_cast<char>(c);
  8218. }
  8219. // Colon and @ are allowed in query
  8220. else if (c == ':' || c == '@') {
  8221. result += static_cast<char>(c);
  8222. }
  8223. // Forward slash is allowed in query values
  8224. else if (c == '/') {
  8225. result += static_cast<char>(c);
  8226. }
  8227. // Question mark is allowed in query values (after first ?)
  8228. else if (c == '?') {
  8229. result += static_cast<char>(c);
  8230. } else {
  8231. result += '%';
  8232. char hex[3];
  8233. snprintf(hex, sizeof(hex), "%02X", c);
  8234. result.append(hex, 2);
  8235. }
  8236. }
  8237. return result;
  8238. }
  8239. inline std::string decode_query_component(const std::string &component,
  8240. bool plus_as_space) {
  8241. std::string result;
  8242. result.reserve(component.size());
  8243. for (size_t i = 0; i < component.size(); i++) {
  8244. if (component[i] == '%' && i + 2 < component.size()) {
  8245. auto val = 0;
  8246. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8247. result += static_cast<char>(val);
  8248. i += 2;
  8249. } else {
  8250. result += component[i];
  8251. }
  8252. } else if (component[i] == '+' && plus_as_space) {
  8253. result += ' '; // + becomes space in form-urlencoded
  8254. } else {
  8255. result += component[i];
  8256. }
  8257. }
  8258. return result;
  8259. }
  8260. inline std::string sanitize_filename(const std::string &filename) {
  8261. // Extract basename: find the last path separator (/ or \)
  8262. auto pos = filename.find_last_of("/\\");
  8263. auto result =
  8264. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8265. // Strip null bytes
  8266. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8267. // Trim whitespace
  8268. {
  8269. auto start = result.find_first_not_of(" \t");
  8270. auto end = result.find_last_not_of(" \t");
  8271. result = (start == std::string::npos)
  8272. ? ""
  8273. : result.substr(start, end - start + 1);
  8274. }
  8275. // Reject . and ..
  8276. if (result == "." || result == "..") { return ""; }
  8277. return result;
  8278. }
  8279. inline std::string append_query_params(const std::string &path,
  8280. const Params &params) {
  8281. std::string path_with_query = path;
  8282. thread_local const std::regex re("[^?]+\\?.*");
  8283. auto delm = std::regex_match(path, re) ? '&' : '?';
  8284. path_with_query += delm + detail::params_to_query_str(params);
  8285. return path_with_query;
  8286. }
  8287. // Header utilities
  8288. inline std::pair<std::string, std::string>
  8289. make_range_header(const Ranges &ranges) {
  8290. std::string field = "bytes=";
  8291. auto i = 0;
  8292. for (const auto &r : ranges) {
  8293. if (i != 0) { field += ", "; }
  8294. if (r.first != -1) { field += std::to_string(r.first); }
  8295. field += '-';
  8296. if (r.second != -1) { field += std::to_string(r.second); }
  8297. i++;
  8298. }
  8299. return std::make_pair("Range", std::move(field));
  8300. }
  8301. inline std::pair<std::string, std::string>
  8302. make_basic_authentication_header(const std::string &username,
  8303. const std::string &password, bool is_proxy) {
  8304. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8305. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8306. return std::make_pair(key, std::move(field));
  8307. }
  8308. inline std::pair<std::string, std::string>
  8309. make_bearer_token_authentication_header(const std::string &token,
  8310. bool is_proxy = false) {
  8311. auto field = "Bearer " + token;
  8312. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8313. return std::make_pair(key, std::move(field));
  8314. }
  8315. // Request implementation
  8316. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8317. size_t id) const {
  8318. return detail::get_header_value_u64(headers, key, def, id);
  8319. }
  8320. inline bool Request::has_header(const std::string &key) const {
  8321. return detail::has_header(headers, key);
  8322. }
  8323. inline std::string Request::get_header_value(const std::string &key,
  8324. const char *def, size_t id) const {
  8325. return detail::get_header_value(headers, key, def, id);
  8326. }
  8327. inline size_t Request::get_header_value_count(const std::string &key) const {
  8328. return detail::get_header_value_count(headers, key);
  8329. }
  8330. inline void Request::set_header(const std::string &key,
  8331. const std::string &val) {
  8332. detail::set_header(headers, key, val);
  8333. }
  8334. inline bool Request::has_trailer(const std::string &key) const {
  8335. return trailers.find(key) != trailers.end();
  8336. }
  8337. inline std::string Request::get_trailer_value(const std::string &key,
  8338. size_t id) const {
  8339. return detail::get_multimap_value(trailers, key, id);
  8340. }
  8341. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8342. auto r = trailers.equal_range(key);
  8343. return static_cast<size_t>(std::distance(r.first, r.second));
  8344. }
  8345. inline bool Request::has_param(const std::string &key) const {
  8346. return params.find(key) != params.end();
  8347. }
  8348. inline std::string Request::get_param_value(const std::string &key,
  8349. size_t id) const {
  8350. return detail::get_multimap_value(params, key, id);
  8351. }
  8352. inline std::vector<std::string>
  8353. Request::get_param_values(const std::string &key) const {
  8354. auto rng = params.equal_range(key);
  8355. std::vector<std::string> values;
  8356. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8357. for (auto it = rng.first; it != rng.second; ++it) {
  8358. values.push_back(it->second);
  8359. }
  8360. return values;
  8361. }
  8362. inline size_t Request::get_param_value_count(const std::string &key) const {
  8363. auto r = params.equal_range(key);
  8364. return static_cast<size_t>(std::distance(r.first, r.second));
  8365. }
  8366. inline bool Request::is_multipart_form_data() const {
  8367. const auto &content_type = get_header_value("Content-Type");
  8368. return detail::extract_media_type(content_type) == "multipart/form-data";
  8369. }
  8370. // Multipart FormData implementation
  8371. inline std::string MultipartFormData::get_field(const std::string &key,
  8372. size_t id) const {
  8373. auto rng = fields.equal_range(key);
  8374. auto it = rng.first;
  8375. std::advance(it, static_cast<ssize_t>(id));
  8376. if (it != rng.second) { return it->second.content; }
  8377. return std::string();
  8378. }
  8379. inline std::vector<std::string>
  8380. MultipartFormData::get_fields(const std::string &key) const {
  8381. std::vector<std::string> values;
  8382. auto rng = fields.equal_range(key);
  8383. for (auto it = rng.first; it != rng.second; it++) {
  8384. values.push_back(it->second.content);
  8385. }
  8386. return values;
  8387. }
  8388. inline bool MultipartFormData::has_field(const std::string &key) const {
  8389. return fields.find(key) != fields.end();
  8390. }
  8391. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8392. auto r = fields.equal_range(key);
  8393. return static_cast<size_t>(std::distance(r.first, r.second));
  8394. }
  8395. inline FormData MultipartFormData::get_file(const std::string &key,
  8396. size_t id) const {
  8397. return detail::get_multimap_value(files, key, id);
  8398. }
  8399. inline std::vector<FormData>
  8400. MultipartFormData::get_files(const std::string &key) const {
  8401. std::vector<FormData> values;
  8402. auto rng = files.equal_range(key);
  8403. for (auto it = rng.first; it != rng.second; it++) {
  8404. values.push_back(it->second);
  8405. }
  8406. return values;
  8407. }
  8408. inline bool MultipartFormData::has_file(const std::string &key) const {
  8409. return files.find(key) != files.end();
  8410. }
  8411. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8412. auto r = files.equal_range(key);
  8413. return static_cast<size_t>(std::distance(r.first, r.second));
  8414. }
  8415. // Multipart FormData writer implementation
  8416. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8417. return detail::is_multipart_boundary_chars_valid(boundary);
  8418. }
  8419. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8420. : boundary_(detail::make_multipart_data_boundary()) {}
  8421. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8422. : boundary_(std::move(boundary)) {}
  8423. inline const std::string &MultipartFormDataWriter::boundary() const {
  8424. return boundary_;
  8425. }
  8426. inline std::string MultipartFormDataWriter::content_type() const {
  8427. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8428. }
  8429. inline std::string
  8430. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8431. return detail::serialize_multipart_formdata(items, boundary_);
  8432. }
  8433. inline size_t MultipartFormDataWriter::content_length(
  8434. const UploadFormDataItems &items) const {
  8435. return detail::get_multipart_content_length(items, boundary_);
  8436. }
  8437. inline std::string
  8438. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8439. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8440. }
  8441. inline std::string MultipartFormDataWriter::item_end() {
  8442. return detail::serialize_multipart_formdata_item_end();
  8443. }
  8444. inline std::string MultipartFormDataWriter::finish() const {
  8445. return detail::serialize_multipart_formdata_finish(boundary_);
  8446. }
  8447. // Response implementation
  8448. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8449. size_t id) const {
  8450. return detail::get_header_value_u64(headers, key, def, id);
  8451. }
  8452. inline bool Response::has_header(const std::string &key) const {
  8453. return headers.find(key) != headers.end();
  8454. }
  8455. inline std::string Response::get_header_value(const std::string &key,
  8456. const char *def,
  8457. size_t id) const {
  8458. return detail::get_header_value(headers, key, def, id);
  8459. }
  8460. inline size_t Response::get_header_value_count(const std::string &key) const {
  8461. return detail::get_header_value_count(headers, key);
  8462. }
  8463. inline void Response::set_header(const std::string &key,
  8464. const std::string &val) {
  8465. detail::set_header(headers, key, val);
  8466. }
  8467. inline bool Response::has_trailer(const std::string &key) const {
  8468. return trailers.find(key) != trailers.end();
  8469. }
  8470. inline std::string Response::get_trailer_value(const std::string &key,
  8471. size_t id) const {
  8472. return detail::get_multimap_value(trailers, key, id);
  8473. }
  8474. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8475. auto r = trailers.equal_range(key);
  8476. return static_cast<size_t>(std::distance(r.first, r.second));
  8477. }
  8478. inline void Response::set_redirect(const std::string &url, int stat) {
  8479. if (detail::fields::is_field_value(url)) {
  8480. set_header("Location", url);
  8481. if (300 <= stat && stat < 400) {
  8482. this->status = stat;
  8483. } else {
  8484. this->status = StatusCode::Found_302;
  8485. }
  8486. }
  8487. }
  8488. inline void Response::set_content(const char *s, size_t n,
  8489. const std::string &content_type) {
  8490. body.assign(s, n);
  8491. auto rng = headers.equal_range("Content-Type");
  8492. headers.erase(rng.first, rng.second);
  8493. set_header("Content-Type", content_type);
  8494. }
  8495. inline void Response::set_content(const std::string &s,
  8496. const std::string &content_type) {
  8497. set_content(s.data(), s.size(), content_type);
  8498. }
  8499. inline void Response::set_content(std::string &&s,
  8500. const std::string &content_type) {
  8501. body = std::move(s);
  8502. auto rng = headers.equal_range("Content-Type");
  8503. headers.erase(rng.first, rng.second);
  8504. set_header("Content-Type", content_type);
  8505. }
  8506. inline void Response::set_content_provider(
  8507. size_t in_length, const std::string &content_type, ContentProvider provider,
  8508. ContentProviderResourceReleaser resource_releaser) {
  8509. set_header("Content-Type", content_type);
  8510. content_length_ = in_length;
  8511. if (in_length > 0) { content_provider_ = std::move(provider); }
  8512. content_provider_resource_releaser_ = std::move(resource_releaser);
  8513. is_chunked_content_provider_ = false;
  8514. }
  8515. inline void Response::set_content_provider(
  8516. const std::string &content_type, ContentProviderWithoutLength provider,
  8517. ContentProviderResourceReleaser resource_releaser) {
  8518. set_header("Content-Type", content_type);
  8519. content_length_ = 0;
  8520. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8521. content_provider_resource_releaser_ = std::move(resource_releaser);
  8522. is_chunked_content_provider_ = false;
  8523. }
  8524. inline void Response::set_chunked_content_provider(
  8525. const std::string &content_type, ContentProviderWithoutLength provider,
  8526. ContentProviderResourceReleaser resource_releaser) {
  8527. set_header("Content-Type", content_type);
  8528. content_length_ = 0;
  8529. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8530. content_provider_resource_releaser_ = std::move(resource_releaser);
  8531. is_chunked_content_provider_ = true;
  8532. }
  8533. inline void Response::set_file_content(const std::string &path,
  8534. const std::string &content_type) {
  8535. file_content_path_ = path;
  8536. file_content_content_type_ = content_type;
  8537. }
  8538. inline void Response::set_file_content(const std::string &path) {
  8539. file_content_path_ = path;
  8540. }
  8541. // Result implementation
  8542. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8543. size_t def,
  8544. size_t id) const {
  8545. return detail::get_header_value_u64(request_headers_, key, def, id);
  8546. }
  8547. inline bool Result::has_request_header(const std::string &key) const {
  8548. return request_headers_.find(key) != request_headers_.end();
  8549. }
  8550. inline std::string Result::get_request_header_value(const std::string &key,
  8551. const char *def,
  8552. size_t id) const {
  8553. return detail::get_header_value(request_headers_, key, def, id);
  8554. }
  8555. inline size_t
  8556. Result::get_request_header_value_count(const std::string &key) const {
  8557. auto r = request_headers_.equal_range(key);
  8558. return static_cast<size_t>(std::distance(r.first, r.second));
  8559. }
  8560. // Stream implementation
  8561. inline ssize_t Stream::write(const char *ptr) {
  8562. return write(ptr, strlen(ptr));
  8563. }
  8564. inline ssize_t Stream::write(const std::string &s) {
  8565. return write(s.data(), s.size());
  8566. }
  8567. // BodyReader implementation
  8568. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8569. if (!stream) {
  8570. last_error = Error::Connection;
  8571. return -1;
  8572. }
  8573. if (eof) { return 0; }
  8574. if (!chunked) {
  8575. // Content-Length based reading
  8576. if (has_content_length && bytes_read >= content_length) {
  8577. eof = true;
  8578. return 0;
  8579. }
  8580. auto to_read = len;
  8581. if (has_content_length) {
  8582. auto remaining = content_length - bytes_read;
  8583. to_read = (std::min)(len, remaining);
  8584. }
  8585. auto n = stream->read(buf, to_read);
  8586. if (n < 0) {
  8587. last_error = stream->get_error();
  8588. if (last_error == Error::Success) { last_error = Error::Read; }
  8589. eof = true;
  8590. return n;
  8591. }
  8592. if (n == 0) {
  8593. // Unexpected EOF before content_length
  8594. last_error = stream->get_error();
  8595. if (last_error == Error::Success) { last_error = Error::Read; }
  8596. eof = true;
  8597. return 0;
  8598. }
  8599. bytes_read += static_cast<size_t>(n);
  8600. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8601. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8602. last_error = Error::ExceedMaxPayloadSize;
  8603. eof = true;
  8604. return -1;
  8605. }
  8606. return n;
  8607. }
  8608. // Chunked transfer encoding: delegate to shared decoder instance.
  8609. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8610. size_t chunk_offset = 0;
  8611. size_t chunk_total = 0;
  8612. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8613. if (n < 0) {
  8614. last_error = stream->get_error();
  8615. if (last_error == Error::Success) { last_error = Error::Read; }
  8616. eof = true;
  8617. return n;
  8618. }
  8619. if (n == 0) {
  8620. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8621. eof = true;
  8622. return 0;
  8623. }
  8624. bytes_read += static_cast<size_t>(n);
  8625. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8626. last_error = Error::ExceedMaxPayloadSize;
  8627. eof = true;
  8628. return -1;
  8629. }
  8630. return n;
  8631. }
  8632. // ThreadPool implementation
  8633. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8634. time_t idle_timeout_sec)
  8635. : base_thread_count_(n), max_queued_requests_(mqr),
  8636. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8637. shutdown_(false) {
  8638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8639. if (max_n != 0 && max_n < n) {
  8640. std::string msg = "max_threads must be >= base_threads";
  8641. throw std::invalid_argument(msg);
  8642. }
  8643. #endif
  8644. max_thread_count_ = max_n == 0 ? n : max_n;
  8645. threads_.reserve(base_thread_count_);
  8646. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8647. try {
  8648. #endif
  8649. for (size_t i = 0; i < base_thread_count_; i++) {
  8650. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8651. }
  8652. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8653. } catch (...) {
  8654. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8655. // signal the workers we already spawned to exit and join them so the
  8656. // vector destructor does not see joinable threads (which would call
  8657. // std::terminate). Then rethrow so the caller learns of the failure.
  8658. {
  8659. std::unique_lock<std::mutex> lock(mutex_);
  8660. shutdown_ = true;
  8661. }
  8662. cond_.notify_all();
  8663. for (auto &t : threads_) {
  8664. if (t.joinable()) { t.join(); }
  8665. }
  8666. throw;
  8667. }
  8668. #endif
  8669. }
  8670. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8671. {
  8672. std::unique_lock<std::mutex> lock(mutex_);
  8673. if (shutdown_) { return false; }
  8674. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8675. return false;
  8676. }
  8677. jobs_.push_back(std::move(fn));
  8678. // Spawn a dynamic thread if no idle threads and under max
  8679. if (idle_thread_count_ == 0 &&
  8680. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8681. cleanup_finished_threads();
  8682. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8683. }
  8684. }
  8685. cond_.notify_one();
  8686. return true;
  8687. }
  8688. inline void ThreadPool::shutdown() {
  8689. {
  8690. std::unique_lock<std::mutex> lock(mutex_);
  8691. shutdown_ = true;
  8692. }
  8693. cond_.notify_all();
  8694. for (auto &t : threads_) {
  8695. if (t.joinable()) { t.join(); }
  8696. }
  8697. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8698. // with worker threads that call move_to_finished() concurrently.
  8699. std::list<std::thread> remaining_dynamic;
  8700. {
  8701. std::unique_lock<std::mutex> lock(mutex_);
  8702. remaining_dynamic = std::move(dynamic_threads_);
  8703. }
  8704. for (auto &t : remaining_dynamic) {
  8705. if (t.joinable()) { t.join(); }
  8706. }
  8707. std::unique_lock<std::mutex> lock(mutex_);
  8708. cleanup_finished_threads();
  8709. }
  8710. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8711. // Must be called with mutex_ held
  8712. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8713. if (it->get_id() == id) {
  8714. finished_threads_.push_back(std::move(*it));
  8715. dynamic_threads_.erase(it);
  8716. return;
  8717. }
  8718. }
  8719. }
  8720. inline void ThreadPool::cleanup_finished_threads() {
  8721. // Must be called with mutex_ held
  8722. for (auto &t : finished_threads_) {
  8723. if (t.joinable()) { t.join(); }
  8724. }
  8725. finished_threads_.clear();
  8726. }
  8727. inline void ThreadPool::worker(bool is_dynamic) {
  8728. for (;;) {
  8729. std::function<void()> fn;
  8730. {
  8731. std::unique_lock<std::mutex> lock(mutex_);
  8732. idle_thread_count_++;
  8733. if (is_dynamic) {
  8734. auto has_work =
  8735. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8736. [&] { return !jobs_.empty() || shutdown_; });
  8737. if (!has_work) {
  8738. // Timed out with no work - exit this dynamic thread
  8739. idle_thread_count_--;
  8740. move_to_finished(std::this_thread::get_id());
  8741. break;
  8742. }
  8743. } else {
  8744. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8745. }
  8746. idle_thread_count_--;
  8747. if (shutdown_ && jobs_.empty()) { break; }
  8748. fn = std::move(jobs_.front());
  8749. jobs_.pop_front();
  8750. }
  8751. assert(true == static_cast<bool>(fn));
  8752. fn();
  8753. }
  8754. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8755. !defined(LIBRESSL_VERSION_NUMBER)
  8756. OPENSSL_thread_stop();
  8757. #endif
  8758. }
  8759. /*
  8760. * Group 1 (continued): detail namespace - Stream implementations
  8761. */
  8762. namespace detail {
  8763. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8764. time_t timeout_sec, time_t timeout_usec,
  8765. time_t &actual_timeout_sec,
  8766. time_t &actual_timeout_usec) {
  8767. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8768. auto actual_timeout_msec =
  8769. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8770. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8771. actual_timeout_sec = actual_timeout_msec / 1000;
  8772. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8773. }
  8774. // Socket stream implementation
  8775. inline SocketStream::SocketStream(
  8776. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8777. time_t write_timeout_sec, time_t write_timeout_usec,
  8778. time_t max_timeout_msec,
  8779. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8780. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8781. read_timeout_usec_(read_timeout_usec),
  8782. write_timeout_sec_(write_timeout_sec),
  8783. write_timeout_usec_(write_timeout_usec),
  8784. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8785. read_buff_(read_buff_size_, 0) {}
  8786. inline SocketStream::~SocketStream() = default;
  8787. inline bool SocketStream::is_readable() const {
  8788. return read_buff_off_ < read_buff_content_size_;
  8789. }
  8790. inline bool SocketStream::wait_readable() const {
  8791. if (max_timeout_msec_ <= 0) {
  8792. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8793. }
  8794. time_t read_timeout_sec;
  8795. time_t read_timeout_usec;
  8796. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8797. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8798. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8799. }
  8800. inline bool SocketStream::wait_writable() const {
  8801. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8802. }
  8803. inline bool SocketStream::is_peer_alive() const {
  8804. return detail::is_socket_alive(sock_);
  8805. }
  8806. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8807. #ifdef _WIN32
  8808. size =
  8809. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8810. #else
  8811. size = (std::min)(size,
  8812. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8813. #endif
  8814. if (read_buff_off_ < read_buff_content_size_) {
  8815. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8816. if (size <= remaining_size) {
  8817. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8818. read_buff_off_ += size;
  8819. return static_cast<ssize_t>(size);
  8820. } else {
  8821. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8822. read_buff_off_ += remaining_size;
  8823. return static_cast<ssize_t>(remaining_size);
  8824. }
  8825. }
  8826. if (!wait_readable()) {
  8827. error_ = Error::Timeout;
  8828. return -1;
  8829. }
  8830. read_buff_off_ = 0;
  8831. read_buff_content_size_ = 0;
  8832. if (size < read_buff_size_) {
  8833. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8834. CPPHTTPLIB_RECV_FLAGS);
  8835. if (n <= 0) {
  8836. if (n == 0) {
  8837. error_ = Error::ConnectionClosed;
  8838. } else {
  8839. error_ = Error::Read;
  8840. }
  8841. return n;
  8842. } else if (n <= static_cast<ssize_t>(size)) {
  8843. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8844. return n;
  8845. } else {
  8846. memcpy(ptr, read_buff_.data(), size);
  8847. read_buff_off_ = size;
  8848. read_buff_content_size_ = static_cast<size_t>(n);
  8849. return static_cast<ssize_t>(size);
  8850. }
  8851. } else {
  8852. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8853. if (n <= 0) {
  8854. if (n == 0) {
  8855. error_ = Error::ConnectionClosed;
  8856. } else {
  8857. error_ = Error::Read;
  8858. }
  8859. }
  8860. return n;
  8861. }
  8862. }
  8863. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8864. if (!wait_writable()) { return -1; }
  8865. #if defined(_WIN32) && !defined(_WIN64)
  8866. size =
  8867. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8868. #endif
  8869. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8870. }
  8871. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8872. int &port) const {
  8873. return detail::get_remote_ip_and_port(sock_, ip, port);
  8874. }
  8875. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8876. int &port) const {
  8877. return detail::get_local_ip_and_port(sock_, ip, port);
  8878. }
  8879. inline socket_t SocketStream::socket() const { return sock_; }
  8880. inline time_t SocketStream::duration() const {
  8881. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8882. std::chrono::steady_clock::now() - start_time_)
  8883. .count();
  8884. }
  8885. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8886. read_timeout_sec_ = sec;
  8887. read_timeout_usec_ = usec;
  8888. }
  8889. // Buffer stream implementation
  8890. inline bool BufferStream::is_readable() const { return true; }
  8891. inline bool BufferStream::wait_readable() const { return true; }
  8892. inline bool BufferStream::wait_writable() const { return true; }
  8893. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8894. #if defined(_MSC_VER) && _MSC_VER < 1910
  8895. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8896. #else
  8897. auto len_read = buffer.copy(ptr, size, position);
  8898. #endif
  8899. position += static_cast<size_t>(len_read);
  8900. return static_cast<ssize_t>(len_read);
  8901. }
  8902. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8903. buffer.append(ptr, size);
  8904. return static_cast<ssize_t>(size);
  8905. }
  8906. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8907. int & /*port*/) const {}
  8908. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8909. int & /*port*/) const {}
  8910. inline socket_t BufferStream::socket() const { return 0; }
  8911. inline time_t BufferStream::duration() const { return 0; }
  8912. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8913. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8914. : MatcherBase(pattern) {
  8915. constexpr const char marker[] = "/:";
  8916. // One past the last ending position of a path param substring
  8917. std::size_t last_param_end = 0;
  8918. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8919. // Needed to ensure that parameter names are unique during matcher
  8920. // construction
  8921. // If exceptions are disabled, only last duplicate path
  8922. // parameter will be set
  8923. std::unordered_set<std::string> param_name_set;
  8924. #endif
  8925. while (true) {
  8926. const auto marker_pos = pattern.find(
  8927. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8928. if (marker_pos == std::string::npos) { break; }
  8929. static_fragments_.push_back(
  8930. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8931. const auto param_name_start = marker_pos + str_len(marker);
  8932. auto sep_pos = pattern.find(separator, param_name_start);
  8933. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8934. auto param_name =
  8935. pattern.substr(param_name_start, sep_pos - param_name_start);
  8936. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8937. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8938. std::string msg = "Encountered path parameter '" + param_name +
  8939. "' multiple times in route pattern '" + pattern + "'.";
  8940. throw std::invalid_argument(msg);
  8941. }
  8942. #endif
  8943. param_names_.push_back(std::move(param_name));
  8944. last_param_end = sep_pos + 1;
  8945. }
  8946. if (last_param_end < pattern.length()) {
  8947. static_fragments_.push_back(pattern.substr(last_param_end));
  8948. }
  8949. }
  8950. inline bool PathParamsMatcher::match(Request &request) const {
  8951. request.matches = std::smatch();
  8952. request.path_params.clear();
  8953. request.path_params.reserve(param_names_.size());
  8954. // One past the position at which the path matched the pattern last time
  8955. std::size_t starting_pos = 0;
  8956. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8957. const auto &fragment = static_fragments_[i];
  8958. if (starting_pos + fragment.length() > request.path.length()) {
  8959. return false;
  8960. }
  8961. // Avoid unnecessary allocation by using strncmp instead of substr +
  8962. // comparison
  8963. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8964. fragment.length()) != 0) {
  8965. return false;
  8966. }
  8967. starting_pos += fragment.length();
  8968. // Should only happen when we have a static fragment after a param
  8969. // Example: '/users/:id/subscriptions'
  8970. // The 'subscriptions' fragment here does not have a corresponding param
  8971. if (i >= param_names_.size()) { continue; }
  8972. auto sep_pos = request.path.find(separator, starting_pos);
  8973. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8974. const auto &param_name = param_names_[i];
  8975. request.path_params.emplace(
  8976. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8977. // Mark everything up to '/' as matched
  8978. starting_pos = sep_pos + 1;
  8979. }
  8980. // Returns false if the path is longer than the pattern
  8981. return starting_pos >= request.path.length();
  8982. }
  8983. inline bool RegexMatcher::match(Request &request) const {
  8984. request.path_params.clear();
  8985. return std::regex_match(request.path, request.matches, regex_);
  8986. }
  8987. // Enclose IPv6 address in brackets if needed
  8988. inline std::string prepare_host_string(const std::string &host) {
  8989. // Enclose IPv6 address in brackets (but not if already enclosed)
  8990. if (host.find(':') == std::string::npos ||
  8991. (!host.empty() && host[0] == '[')) {
  8992. // IPv4, hostname, or already bracketed IPv6
  8993. return host;
  8994. } else {
  8995. // IPv6 address without brackets
  8996. return "[" + host + "]";
  8997. }
  8998. }
  8999. inline std::string make_host_and_port_string(const std::string &host, int port,
  9000. bool is_ssl) {
  9001. auto result = prepare_host_string(host);
  9002. // Append port if not default
  9003. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9004. ; // do nothing
  9005. } else {
  9006. result += ":" + std::to_string(port);
  9007. }
  9008. return result;
  9009. }
  9010. // Create "host:port" string always including port number (for CONNECT method)
  9011. inline std::string
  9012. make_host_and_port_string_always_port(const std::string &host, int port) {
  9013. return prepare_host_string(host) + ":" + std::to_string(port);
  9014. }
  9015. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9016. NormalizedTarget normalize_target(const std::string &host);
  9017. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9018. bool host_matches_no_proxy(const NormalizedTarget &target,
  9019. const std::vector<NoProxyEntry> &entries);
  9020. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9021. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9022. if (prefix_bits == 0) { return true; }
  9023. int full_bytes = prefix_bits / 8;
  9024. int rem_bits = prefix_bits % 8;
  9025. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9026. static_cast<size_t>(full_bytes)) != 0) {
  9027. return false;
  9028. }
  9029. if (rem_bits == 0) { return true; }
  9030. auto i = static_cast<size_t>(full_bytes);
  9031. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9032. return (ip[i] & mask) == (net[i] & mask);
  9033. }
  9034. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9035. if (token.empty()) { return false; }
  9036. if (token == "*") {
  9037. out.kind = NoProxyKind::Wildcard;
  9038. return true;
  9039. }
  9040. auto slash = token.find('/');
  9041. std::string addr_part =
  9042. (slash == std::string::npos) ? token : token.substr(0, slash);
  9043. std::string prefix_part =
  9044. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9045. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9046. // don't silently treat it as a /32 (or /128).
  9047. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9048. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9049. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9050. // when brackets are present.
  9051. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9052. addr_part.back() == ']';
  9053. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9054. if (!bracketed) {
  9055. struct in_addr v4;
  9056. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9057. int prefix = 32;
  9058. if (!prefix_part.empty()) {
  9059. auto r = from_chars(prefix_part.data(),
  9060. prefix_part.data() + prefix_part.size(), prefix);
  9061. if (r.ec != std::errc{} ||
  9062. r.ptr != prefix_part.data() + prefix_part.size()) {
  9063. return false;
  9064. }
  9065. if (prefix < 0 || prefix > 32) { return false; }
  9066. }
  9067. out.kind = NoProxyKind::IPv4Cidr;
  9068. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9069. out.prefix_bits = prefix;
  9070. return true;
  9071. }
  9072. }
  9073. struct in6_addr v6;
  9074. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9075. int prefix = 128;
  9076. if (!prefix_part.empty()) {
  9077. auto r = from_chars(prefix_part.data(),
  9078. prefix_part.data() + prefix_part.size(), prefix);
  9079. if (r.ec != std::errc{} ||
  9080. r.ptr != prefix_part.data() + prefix_part.size()) {
  9081. return false;
  9082. }
  9083. if (prefix < 0 || prefix > 128) { return false; }
  9084. }
  9085. out.kind = NoProxyKind::IPv6Cidr;
  9086. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9087. out.prefix_bits = prefix;
  9088. return true;
  9089. }
  9090. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9091. // the entry is malformed — don't fall through to the hostname branch.
  9092. if (bracketed) { return false; }
  9093. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9094. if (slash != std::string::npos) { return false; }
  9095. // Port-specific entries (host:port) are not supported.
  9096. if (token.find(':') != std::string::npos) { return false; }
  9097. std::string hostname = case_ignore::to_lower(token);
  9098. while (!hostname.empty() && hostname.front() == '.') {
  9099. hostname.erase(hostname.begin());
  9100. }
  9101. while (!hostname.empty() && hostname.back() == '.') {
  9102. hostname.pop_back();
  9103. }
  9104. if (hostname.empty()) { return false; }
  9105. out.kind = NoProxyKind::HostnameSuffix;
  9106. out.hostname_pattern = std::move(hostname);
  9107. return true;
  9108. }
  9109. inline NormalizedTarget normalize_target(const std::string &host) {
  9110. NormalizedTarget t;
  9111. std::string h = host;
  9112. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9113. h = h.substr(1, h.size() - 2);
  9114. }
  9115. // Strip a single trailing dot so "example.com." canonicalizes to
  9116. // "example.com".
  9117. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9118. t.hostname = case_ignore::to_lower(h);
  9119. if (!t.hostname.empty()) {
  9120. struct in_addr v4;
  9121. struct in6_addr v6;
  9122. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9123. t.is_ipv4 = true;
  9124. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9125. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9126. t.is_ipv6 = true;
  9127. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9128. }
  9129. }
  9130. return t;
  9131. }
  9132. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9133. const std::vector<NoProxyEntry> &entries) {
  9134. if (target.hostname.empty()) { return false; }
  9135. for (const auto &e : entries) {
  9136. switch (e.kind) {
  9137. case NoProxyKind::Wildcard: return true;
  9138. case NoProxyKind::IPv4Cidr:
  9139. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9140. return true;
  9141. }
  9142. break;
  9143. case NoProxyKind::IPv6Cidr:
  9144. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9145. return true;
  9146. }
  9147. break;
  9148. case NoProxyKind::HostnameSuffix:
  9149. if (target.is_ipv4 || target.is_ipv6) { break; }
  9150. if (target.hostname == e.hostname_pattern) { return true; }
  9151. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9152. // an entry of "example.com".
  9153. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9154. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9155. if (target.hostname[offset - 1] == '.' &&
  9156. target.hostname.compare(offset, e.hostname_pattern.size(),
  9157. e.hostname_pattern) == 0) {
  9158. return true;
  9159. }
  9160. }
  9161. break;
  9162. }
  9163. }
  9164. return false;
  9165. }
  9166. template <typename T>
  9167. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9168. T header_writer, Error &error) {
  9169. for (const auto &h : headers) {
  9170. if (!detail::fields::is_field_name(h.first) ||
  9171. !detail::fields::is_field_value(h.second)) {
  9172. error = Error::InvalidHeaders;
  9173. return false;
  9174. }
  9175. }
  9176. if (header_writer(strm, headers) <= 0) {
  9177. error = Error::Write;
  9178. return false;
  9179. }
  9180. return true;
  9181. }
  9182. } // namespace detail
  9183. /*
  9184. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9185. */
  9186. #ifdef CPPHTTPLIB_SSL_ENABLED
  9187. namespace detail {
  9188. // SSL socket stream implementation
  9189. inline SSLSocketStream::SSLSocketStream(
  9190. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9191. time_t read_timeout_usec, time_t write_timeout_sec,
  9192. time_t write_timeout_usec, time_t max_timeout_msec,
  9193. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9194. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9195. read_timeout_usec_(read_timeout_usec),
  9196. write_timeout_sec_(write_timeout_sec),
  9197. write_timeout_usec_(write_timeout_usec),
  9198. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9200. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9201. // Note: create_session() also clears this, but SSLClient currently
  9202. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9203. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9204. // SSL session was created.
  9205. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9206. #endif
  9207. }
  9208. inline SSLSocketStream::~SSLSocketStream() = default;
  9209. inline bool SSLSocketStream::is_readable() const {
  9210. return tls::pending(session_) > 0;
  9211. }
  9212. inline bool SSLSocketStream::wait_readable() const {
  9213. if (max_timeout_msec_ <= 0) {
  9214. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9215. }
  9216. time_t read_timeout_sec;
  9217. time_t read_timeout_usec;
  9218. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9219. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9220. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9221. }
  9222. inline bool SSLSocketStream::wait_writable() const {
  9223. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9224. !tls::is_peer_closed(session_, sock_);
  9225. }
  9226. inline bool SSLSocketStream::is_peer_alive() const {
  9227. return !tls::is_peer_closed(session_, sock_);
  9228. }
  9229. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9230. if (tls::pending(session_) > 0) {
  9231. tls::TlsError err;
  9232. auto ret = tls::read(session_, ptr, size, err);
  9233. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9234. error_ = Error::ConnectionClosed;
  9235. }
  9236. return ret;
  9237. } else if (wait_readable()) {
  9238. tls::TlsError err;
  9239. auto ret = tls::read(session_, ptr, size, err);
  9240. if (ret < 0) {
  9241. auto n = 1000;
  9242. #ifdef _WIN32
  9243. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9244. (err.code == tls::ErrorCode::SyscallError &&
  9245. WSAGetLastError() == WSAETIMEDOUT))) {
  9246. #else
  9247. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9248. #endif
  9249. if (tls::pending(session_) > 0) {
  9250. return tls::read(session_, ptr, size, err);
  9251. } else if (wait_readable()) {
  9252. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9253. ret = tls::read(session_, ptr, size, err);
  9254. if (ret >= 0) { return ret; }
  9255. } else {
  9256. break;
  9257. }
  9258. }
  9259. assert(ret < 0);
  9260. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9261. error_ = Error::ConnectionClosed;
  9262. }
  9263. return ret;
  9264. } else {
  9265. error_ = Error::Timeout;
  9266. return -1;
  9267. }
  9268. }
  9269. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9270. if (wait_writable()) {
  9271. auto handle_size =
  9272. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9273. tls::TlsError err;
  9274. auto ret = tls::write(session_, ptr, handle_size, err);
  9275. if (ret < 0) {
  9276. auto n = 1000;
  9277. #ifdef _WIN32
  9278. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9279. (err.code == tls::ErrorCode::SyscallError &&
  9280. WSAGetLastError() == WSAETIMEDOUT))) {
  9281. #else
  9282. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9283. #endif
  9284. if (wait_writable()) {
  9285. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9286. ret = tls::write(session_, ptr, handle_size, err);
  9287. if (ret >= 0) { return ret; }
  9288. } else {
  9289. break;
  9290. }
  9291. }
  9292. assert(ret < 0);
  9293. }
  9294. return ret;
  9295. }
  9296. return -1;
  9297. }
  9298. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9299. int &port) const {
  9300. detail::get_remote_ip_and_port(sock_, ip, port);
  9301. }
  9302. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9303. int &port) const {
  9304. detail::get_local_ip_and_port(sock_, ip, port);
  9305. }
  9306. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9307. inline time_t SSLSocketStream::duration() const {
  9308. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9309. std::chrono::steady_clock::now() - start_time_)
  9310. .count();
  9311. }
  9312. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9313. read_timeout_sec_ = sec;
  9314. read_timeout_usec_ = usec;
  9315. }
  9316. } // namespace detail
  9317. #endif // CPPHTTPLIB_SSL_ENABLED
  9318. /*
  9319. * Group 4: Server implementation
  9320. */
  9321. // HTTP server implementation
  9322. inline Server::Server()
  9323. : new_task_queue([] {
  9324. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9325. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9326. }) {
  9327. #ifndef _WIN32
  9328. signal(SIGPIPE, SIG_IGN);
  9329. #endif
  9330. }
  9331. inline Server::~Server() = default;
  9332. inline std::unique_ptr<detail::MatcherBase>
  9333. Server::make_matcher(const std::string &pattern) {
  9334. if (pattern.find("/:") != std::string::npos) {
  9335. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9336. } else {
  9337. return detail::make_unique<detail::RegexMatcher>(pattern);
  9338. }
  9339. }
  9340. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9341. return add_handler(get_handlers_, pattern, std::move(handler));
  9342. }
  9343. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9344. return add_handler(post_handlers_, pattern, std::move(handler));
  9345. }
  9346. inline Server &Server::Post(const std::string &pattern,
  9347. HandlerWithContentReader handler) {
  9348. return add_handler(post_handlers_for_content_reader_, pattern,
  9349. std::move(handler));
  9350. }
  9351. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9352. return add_handler(put_handlers_, pattern, std::move(handler));
  9353. }
  9354. inline Server &Server::Put(const std::string &pattern,
  9355. HandlerWithContentReader handler) {
  9356. return add_handler(put_handlers_for_content_reader_, pattern,
  9357. std::move(handler));
  9358. }
  9359. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9360. return add_handler(patch_handlers_, pattern, std::move(handler));
  9361. }
  9362. inline Server &Server::Patch(const std::string &pattern,
  9363. HandlerWithContentReader handler) {
  9364. return add_handler(patch_handlers_for_content_reader_, pattern,
  9365. std::move(handler));
  9366. }
  9367. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9368. return add_handler(delete_handlers_, pattern, std::move(handler));
  9369. }
  9370. inline Server &Server::Delete(const std::string &pattern,
  9371. HandlerWithContentReader handler) {
  9372. return add_handler(delete_handlers_for_content_reader_, pattern,
  9373. std::move(handler));
  9374. }
  9375. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9376. return add_handler(options_handlers_, pattern, std::move(handler));
  9377. }
  9378. inline Server &Server::WebSocket(const std::string &pattern,
  9379. WebSocketHandler handler) {
  9380. websocket_handlers_.push_back(
  9381. {make_matcher(pattern), std::move(handler), nullptr});
  9382. return *this;
  9383. }
  9384. inline Server &Server::WebSocket(const std::string &pattern,
  9385. WebSocketHandler handler,
  9386. SubProtocolSelector sub_protocol_selector) {
  9387. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9388. std::move(sub_protocol_selector)});
  9389. return *this;
  9390. }
  9391. inline bool Server::set_base_dir(const std::string &dir,
  9392. const std::string &mount_point) {
  9393. return set_mount_point(mount_point, dir);
  9394. }
  9395. inline bool Server::set_mount_point(const std::string &mount_point,
  9396. const std::string &dir, Headers headers) {
  9397. detail::FileStat stat(dir);
  9398. if (stat.is_dir()) {
  9399. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9400. if (!mnt.empty() && mnt[0] == '/') {
  9401. std::string resolved_base;
  9402. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9403. #if defined(_WIN32)
  9404. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9405. resolved_base += '\\';
  9406. }
  9407. #else
  9408. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9409. #endif
  9410. }
  9411. base_dirs_.push_back(
  9412. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9413. return true;
  9414. }
  9415. }
  9416. return false;
  9417. }
  9418. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9419. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9420. if (it->mount_point == mount_point) {
  9421. base_dirs_.erase(it);
  9422. return true;
  9423. }
  9424. }
  9425. return false;
  9426. }
  9427. inline Server &
  9428. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9429. const std::string &mime) {
  9430. file_extension_and_mimetype_map_[ext] = mime;
  9431. return *this;
  9432. }
  9433. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9434. default_file_mimetype_ = mime;
  9435. return *this;
  9436. }
  9437. inline Server &Server::set_file_request_handler(Handler handler) {
  9438. file_request_handler_ = std::move(handler);
  9439. return *this;
  9440. }
  9441. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9442. std::true_type) {
  9443. error_handler_ = std::move(handler);
  9444. return *this;
  9445. }
  9446. inline Server &Server::set_error_handler_core(Handler handler,
  9447. std::false_type) {
  9448. error_handler_ = [handler](const Request &req, Response &res) {
  9449. handler(req, res);
  9450. return HandlerResponse::Handled;
  9451. };
  9452. return *this;
  9453. }
  9454. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9455. exception_handler_ = std::move(handler);
  9456. return *this;
  9457. }
  9458. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9459. pre_routing_handler_ = std::move(handler);
  9460. return *this;
  9461. }
  9462. inline Server &Server::set_post_routing_handler(Handler handler) {
  9463. post_routing_handler_ = std::move(handler);
  9464. return *this;
  9465. }
  9466. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9467. pre_request_handler_ = std::move(handler);
  9468. return *this;
  9469. }
  9470. inline Server &Server::set_logger(Logger logger) {
  9471. logger_ = std::move(logger);
  9472. return *this;
  9473. }
  9474. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9475. error_logger_ = std::move(error_logger);
  9476. return *this;
  9477. }
  9478. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9479. pre_compression_logger_ = std::move(logger);
  9480. return *this;
  9481. }
  9482. inline Server &
  9483. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9484. expect_100_continue_handler_ = std::move(handler);
  9485. return *this;
  9486. }
  9487. inline Server &Server::set_start_handler(StartHandler handler) {
  9488. start_handler_ = std::move(handler);
  9489. return *this;
  9490. }
  9491. inline Server &Server::set_address_family(int family) {
  9492. address_family_ = family;
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_tcp_nodelay(bool on) {
  9496. tcp_nodelay_ = on;
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_ipv6_v6only(bool on) {
  9500. ipv6_v6only_ = on;
  9501. return *this;
  9502. }
  9503. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9504. socket_options_ = std::move(socket_options);
  9505. return *this;
  9506. }
  9507. inline Server &Server::set_default_headers(Headers headers) {
  9508. default_headers_ = std::move(headers);
  9509. return *this;
  9510. }
  9511. inline Server &Server::set_header_writer(
  9512. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9513. header_writer_ = writer;
  9514. return *this;
  9515. }
  9516. inline Server &
  9517. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9518. trusted_proxies_ = proxies;
  9519. return *this;
  9520. }
  9521. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9522. keep_alive_max_count_ = count;
  9523. return *this;
  9524. }
  9525. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9526. keep_alive_timeout_sec_ = sec;
  9527. return *this;
  9528. }
  9529. template <class Rep, class Period>
  9530. inline Server &Server::set_keep_alive_timeout(
  9531. const std::chrono::duration<Rep, Period> &duration) {
  9532. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9533. set_keep_alive_timeout(sec);
  9534. });
  9535. return *this;
  9536. }
  9537. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9538. read_timeout_sec_ = sec;
  9539. read_timeout_usec_ = usec;
  9540. return *this;
  9541. }
  9542. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9543. write_timeout_sec_ = sec;
  9544. write_timeout_usec_ = usec;
  9545. return *this;
  9546. }
  9547. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9548. idle_interval_sec_ = sec;
  9549. idle_interval_usec_ = usec;
  9550. return *this;
  9551. }
  9552. inline Server &Server::set_payload_max_length(size_t length) {
  9553. payload_max_length_ = length;
  9554. return *this;
  9555. }
  9556. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9557. websocket_max_missed_pongs_ = count;
  9558. return *this;
  9559. }
  9560. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9561. websocket_ping_interval_sec_ = sec;
  9562. return *this;
  9563. }
  9564. template <class Rep, class Period>
  9565. inline Server &Server::set_websocket_ping_interval(
  9566. const std::chrono::duration<Rep, Period> &duration) {
  9567. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9568. set_websocket_ping_interval(sec);
  9569. });
  9570. return *this;
  9571. }
  9572. inline bool Server::bind_to_port(const std::string &host, int port,
  9573. int socket_flags) {
  9574. auto ret = bind_internal(host, port, socket_flags);
  9575. if (ret == -1) { is_decommissioned = true; }
  9576. return ret >= 0;
  9577. }
  9578. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9579. auto ret = bind_internal(host, 0, socket_flags);
  9580. if (ret == -1) { is_decommissioned = true; }
  9581. return ret;
  9582. }
  9583. inline bool Server::listen_after_bind() { return listen_internal(); }
  9584. inline bool Server::listen(const std::string &host, int port,
  9585. int socket_flags) {
  9586. return bind_to_port(host, port, socket_flags) && listen_internal();
  9587. }
  9588. inline bool Server::is_running() const { return is_running_; }
  9589. inline void Server::wait_until_ready() const {
  9590. while (!is_running_ && !is_decommissioned) {
  9591. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9592. }
  9593. }
  9594. inline void Server::stop() noexcept {
  9595. if (is_running_) {
  9596. assert(svr_sock_ != INVALID_SOCKET);
  9597. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9598. detail::shutdown_socket(sock);
  9599. detail::close_socket(sock);
  9600. }
  9601. is_decommissioned = false;
  9602. }
  9603. inline void Server::decommission() { is_decommissioned = true; }
  9604. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9605. auto len = strlen(s);
  9606. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9607. len -= 2;
  9608. {
  9609. size_t count = 0;
  9610. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9611. switch (count) {
  9612. case 0: req.method = std::string(b, e); break;
  9613. case 1: req.target = std::string(b, e); break;
  9614. case 2: req.version = std::string(b, e); break;
  9615. default: break;
  9616. }
  9617. count++;
  9618. });
  9619. if (count != 3) { return false; }
  9620. }
  9621. thread_local const std::set<std::string> methods{
  9622. "GET", "HEAD", "POST", "PUT", "DELETE",
  9623. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9624. if (methods.find(req.method) == methods.end()) {
  9625. output_error_log(Error::InvalidHTTPMethod, &req);
  9626. return false;
  9627. }
  9628. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9629. output_error_log(Error::InvalidHTTPVersion, &req);
  9630. return false;
  9631. }
  9632. {
  9633. // Skip URL fragment
  9634. for (size_t i = 0; i < req.target.size(); i++) {
  9635. if (req.target[i] == '#') {
  9636. req.target.erase(i);
  9637. break;
  9638. }
  9639. }
  9640. detail::divide(req.target, '?',
  9641. [&](const char *lhs_data, std::size_t lhs_size,
  9642. const char *rhs_data, std::size_t rhs_size) {
  9643. req.path =
  9644. decode_path_component(std::string(lhs_data, lhs_size));
  9645. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9646. });
  9647. }
  9648. return true;
  9649. }
  9650. inline bool Server::write_response(Stream &strm, bool close_connection,
  9651. Request &req, Response &res) {
  9652. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9653. // incorrectly to the error content.
  9654. req.ranges.clear();
  9655. return write_response_core(strm, close_connection, req, res, false);
  9656. }
  9657. inline bool Server::write_response_with_content(Stream &strm,
  9658. bool close_connection,
  9659. const Request &req,
  9660. Response &res) {
  9661. return write_response_core(strm, close_connection, req, res, true);
  9662. }
  9663. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9664. const Request &req, Response &res,
  9665. bool need_apply_ranges) {
  9666. assert(res.status != -1);
  9667. if (400 <= res.status && error_handler_ &&
  9668. error_handler_(req, res) == HandlerResponse::Handled) {
  9669. need_apply_ranges = true;
  9670. }
  9671. std::string content_type;
  9672. std::string boundary;
  9673. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9674. // Prepare additional headers
  9675. if (close_connection || req.get_header_value("Connection") == "close" ||
  9676. 400 <= res.status) { // Don't leave connections open after errors
  9677. res.set_header("Connection", "close");
  9678. } else {
  9679. std::string s = "timeout=";
  9680. s += std::to_string(keep_alive_timeout_sec_);
  9681. s += ", max=";
  9682. s += std::to_string(keep_alive_max_count_);
  9683. res.set_header("Keep-Alive", s);
  9684. }
  9685. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9686. !res.has_header("Content-Type")) {
  9687. res.set_header("Content-Type", "text/plain");
  9688. }
  9689. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9690. !res.has_header("Content-Length")) {
  9691. res.set_header("Content-Length", "0");
  9692. }
  9693. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9694. res.set_header("Accept-Ranges", "bytes");
  9695. }
  9696. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9697. // Response line and headers
  9698. detail::BufferStream bstrm;
  9699. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9700. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9701. // Combine small body with headers to reduce write syscalls
  9702. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9703. bstrm.write(res.body.data(), res.body.size());
  9704. }
  9705. // Log before writing to avoid race condition with client-side code that
  9706. // accesses logger-captured data immediately after receiving the response.
  9707. output_log(req, res);
  9708. // Flush buffer
  9709. auto &data = bstrm.get_buffer();
  9710. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9711. // Streaming body
  9712. auto ret = true;
  9713. if (req.method != "HEAD" && res.content_provider_) {
  9714. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9715. res.content_provider_success_ = true;
  9716. } else {
  9717. ret = false;
  9718. }
  9719. }
  9720. return ret;
  9721. }
  9722. inline bool
  9723. Server::write_content_with_provider(Stream &strm, const Request &req,
  9724. Response &res, const std::string &boundary,
  9725. const std::string &content_type) {
  9726. auto is_shutting_down = [this]() {
  9727. return this->svr_sock_ == INVALID_SOCKET;
  9728. };
  9729. if (res.content_length_ > 0) {
  9730. if (req.ranges.empty()) {
  9731. return detail::write_content(strm, res.content_provider_, 0,
  9732. res.content_length_, is_shutting_down);
  9733. } else if (req.ranges.size() == 1) {
  9734. auto offset_and_length = detail::get_range_offset_and_length(
  9735. req.ranges[0], res.content_length_);
  9736. return detail::write_content(strm, res.content_provider_,
  9737. offset_and_length.first,
  9738. offset_and_length.second, is_shutting_down);
  9739. } else {
  9740. return detail::write_multipart_ranges_data(
  9741. strm, req, res, boundary, content_type, res.content_length_,
  9742. is_shutting_down);
  9743. }
  9744. } else {
  9745. if (res.is_chunked_content_provider_) {
  9746. auto type = detail::encoding_type(req, res);
  9747. auto compressor = detail::make_compressor(type);
  9748. if (!compressor) {
  9749. compressor = detail::make_unique<detail::nocompressor>();
  9750. }
  9751. return detail::write_content_chunked(strm, res.content_provider_,
  9752. is_shutting_down, *compressor);
  9753. } else {
  9754. return detail::write_content_without_length(strm, res.content_provider_,
  9755. is_shutting_down);
  9756. }
  9757. }
  9758. }
  9759. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9760. FormFields::iterator cur_field;
  9761. FormFiles::iterator cur_file;
  9762. auto is_text_field = false;
  9763. size_t count = 0;
  9764. if (read_content_core(
  9765. strm, req, res,
  9766. // Regular
  9767. [&](const char *buf, size_t n) {
  9768. // Prevent arithmetic overflow when checking sizes.
  9769. // Avoid computing (req.body.size() + n) directly because
  9770. // adding two unsigned `size_t` values can wrap around and
  9771. // produce a small result instead of indicating overflow.
  9772. // Instead, check using subtraction: ensure `n` does not
  9773. // exceed the remaining capacity `max_size() - size()`.
  9774. if (req.body.size() >= req.body.max_size() ||
  9775. n > req.body.max_size() - req.body.size()) {
  9776. return false;
  9777. }
  9778. // Limit decompressed body size to payload_max_length_ to protect
  9779. // against "zip bomb" attacks where a small compressed payload
  9780. // decompresses to a massive size.
  9781. if (payload_max_length_ > 0 &&
  9782. (req.body.size() >= payload_max_length_ ||
  9783. n > payload_max_length_ - req.body.size())) {
  9784. return false;
  9785. }
  9786. req.body.append(buf, n);
  9787. return true;
  9788. },
  9789. // Multipart FormData
  9790. [&](const FormData &file) {
  9791. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9792. output_error_log(Error::TooManyFormDataFiles, &req);
  9793. return false;
  9794. }
  9795. if (file.filename.empty()) {
  9796. cur_field = req.form.fields.emplace(
  9797. file.name, FormField{file.name, file.content, file.headers});
  9798. is_text_field = true;
  9799. } else {
  9800. cur_file = req.form.files.emplace(file.name, file);
  9801. is_text_field = false;
  9802. }
  9803. return true;
  9804. },
  9805. [&](const char *buf, size_t n) {
  9806. if (is_text_field) {
  9807. auto &content = cur_field->second.content;
  9808. if (content.size() + n > content.max_size()) { return false; }
  9809. content.append(buf, n);
  9810. } else {
  9811. auto &content = cur_file->second.content;
  9812. if (content.size() + n > content.max_size()) { return false; }
  9813. content.append(buf, n);
  9814. }
  9815. return true;
  9816. })) {
  9817. const auto &content_type = req.get_header_value("Content-Type");
  9818. if (detail::extract_media_type(content_type) ==
  9819. "application/x-www-form-urlencoded") {
  9820. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9821. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9822. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9823. return false;
  9824. }
  9825. detail::parse_query_text(req.body, req.params);
  9826. }
  9827. return true;
  9828. }
  9829. return false;
  9830. }
  9831. inline bool Server::read_content_with_content_receiver(
  9832. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9833. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9834. return read_content_core(strm, req, res, std::move(receiver),
  9835. std::move(multipart_header),
  9836. std::move(multipart_receiver));
  9837. }
  9838. inline bool Server::read_content_core(
  9839. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9840. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9841. detail::FormDataParser multipart_form_data_parser;
  9842. ContentReceiverWithProgress out;
  9843. if (req.is_multipart_form_data()) {
  9844. const auto &content_type = req.get_header_value("Content-Type");
  9845. std::string boundary;
  9846. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9847. res.status = StatusCode::BadRequest_400;
  9848. output_error_log(Error::MultipartParsing, &req);
  9849. return false;
  9850. }
  9851. multipart_form_data_parser.set_boundary(std::move(boundary));
  9852. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9853. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9854. multipart_receiver);
  9855. };
  9856. } else {
  9857. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9858. size_t /*len*/) { return receiver(buf, n); };
  9859. }
  9860. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9861. // For non-SSL builds we still scan non-persistent connections for stray
  9862. // body bytes so the payload limit is enforced (413). On keep-alive,
  9863. // pending bytes may be the next request (issue #2450), so skip.
  9864. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9865. if (!req.has_header("Content-Length") &&
  9866. !detail::is_chunked_transfer_encoding(req.headers)) {
  9867. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9868. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9869. auto has_data = strm.is_readable();
  9870. if (!has_data) {
  9871. auto s = strm.socket();
  9872. if (s != INVALID_SOCKET) {
  9873. has_data = detail::select_read(s, 0, 0) > 0;
  9874. }
  9875. }
  9876. if (has_data) {
  9877. auto result =
  9878. detail::read_content_without_length(strm, payload_max_length_, out);
  9879. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9880. res.status = StatusCode::PayloadTooLarge_413;
  9881. return false;
  9882. } else if (result != detail::ReadContentResult::Success) {
  9883. return false;
  9884. }
  9885. return true;
  9886. }
  9887. }
  9888. return true;
  9889. }
  9890. #else
  9891. if (!req.has_header("Content-Length") &&
  9892. !detail::is_chunked_transfer_encoding(req.headers)) {
  9893. return true;
  9894. }
  9895. #endif
  9896. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9897. out, true)) {
  9898. return false;
  9899. }
  9900. req.body_consumed_ = true;
  9901. if (req.is_multipart_form_data()) {
  9902. if (!multipart_form_data_parser.is_valid()) {
  9903. res.status = StatusCode::BadRequest_400;
  9904. output_error_log(Error::MultipartParsing, &req);
  9905. return false;
  9906. }
  9907. }
  9908. return true;
  9909. }
  9910. inline bool Server::handle_file_request(Request &req, Response &res) {
  9911. for (const auto &entry : base_dirs_) {
  9912. // Prefix match
  9913. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9914. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9915. if (detail::is_valid_path(sub_path)) {
  9916. auto path = entry.base_dir + sub_path;
  9917. if (path.back() == '/') { path += "index.html"; }
  9918. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9919. // but symlinks/junctions can still escape the base directory.
  9920. if (!entry.resolved_base_dir.empty()) {
  9921. std::string resolved_path;
  9922. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9923. !detail::is_path_within_base(resolved_path,
  9924. entry.resolved_base_dir)) {
  9925. res.status = StatusCode::Forbidden_403;
  9926. return true;
  9927. }
  9928. }
  9929. detail::FileStat stat(path);
  9930. if (stat.is_dir()) {
  9931. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9932. return true;
  9933. }
  9934. if (stat.is_file()) {
  9935. for (const auto &kv : entry.headers) {
  9936. res.set_header(kv.first, kv.second);
  9937. }
  9938. auto etag = detail::compute_etag(stat);
  9939. if (!etag.empty()) { res.set_header("ETag", etag); }
  9940. auto mtime = stat.mtime();
  9941. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9942. if (!last_modified.empty()) {
  9943. res.set_header("Last-Modified", last_modified);
  9944. }
  9945. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9946. check_if_range(req, etag, mtime);
  9947. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9948. if (!mm->is_open()) {
  9949. output_error_log(Error::OpenFile, &req);
  9950. return false;
  9951. }
  9952. res.set_content_provider(
  9953. mm->size(),
  9954. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9955. default_file_mimetype_),
  9956. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9957. sink.write(mm->data() + offset, length);
  9958. return true;
  9959. });
  9960. if (req.method != "HEAD" && file_request_handler_) {
  9961. file_request_handler_(req, res);
  9962. }
  9963. return true;
  9964. } else {
  9965. output_error_log(Error::OpenFile, &req);
  9966. }
  9967. }
  9968. }
  9969. }
  9970. return false;
  9971. }
  9972. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9973. const std::string &etag,
  9974. time_t mtime) const {
  9975. // Handle conditional GET:
  9976. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9977. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9978. if (req.has_header("If-None-Match")) {
  9979. if (!etag.empty()) {
  9980. auto val = req.get_header_value("If-None-Match");
  9981. // NOTE: We use exact string matching here. This works correctly
  9982. // because our server always generates weak ETags (W/"..."), and
  9983. // clients typically send back the same ETag they received.
  9984. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9985. // If-None-Match, where W/"x" and "x" would match, but this
  9986. // simplified implementation requires exact matches.
  9987. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9988. [&](const char *b, const char *e) {
  9989. auto seg_len = static_cast<size_t>(e - b);
  9990. return (seg_len == 1 && *b == '*') ||
  9991. (seg_len == etag.size() &&
  9992. std::equal(b, e, etag.begin()));
  9993. });
  9994. if (ret) {
  9995. res.status = StatusCode::NotModified_304;
  9996. return true;
  9997. }
  9998. }
  9999. } else if (req.has_header("If-Modified-Since")) {
  10000. auto val = req.get_header_value("If-Modified-Since");
  10001. auto t = detail::parse_http_date(val);
  10002. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10003. res.status = StatusCode::NotModified_304;
  10004. return true;
  10005. }
  10006. }
  10007. return false;
  10008. }
  10009. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10010. time_t mtime) const {
  10011. // Handle If-Range for partial content requests (RFC 9110
  10012. // Section 13.1.5). If-Range is only evaluated when Range header is
  10013. // present. If the validator matches, serve partial content; otherwise
  10014. // serve full content.
  10015. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10016. auto val = req.get_header_value("If-Range");
  10017. auto is_valid_range = [&]() {
  10018. if (detail::is_strong_etag(val)) {
  10019. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10020. // comparison.
  10021. return (!etag.empty() && val == etag);
  10022. } else if (detail::is_weak_etag(val)) {
  10023. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10024. return false;
  10025. } else {
  10026. // HTTP-date comparison
  10027. auto t = detail::parse_http_date(val);
  10028. return (t != static_cast<time_t>(-1) && mtime <= t);
  10029. }
  10030. };
  10031. if (!is_valid_range()) {
  10032. // Validator doesn't match: ignore Range and serve full content
  10033. req.ranges.clear();
  10034. return false;
  10035. }
  10036. }
  10037. return true;
  10038. }
  10039. inline socket_t
  10040. Server::create_server_socket(const std::string &host, int port,
  10041. int socket_flags,
  10042. SocketOptions socket_options) const {
  10043. return detail::create_socket(
  10044. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10045. ipv6_v6only_, std::move(socket_options),
  10046. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10047. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10048. output_error_log(Error::BindIPAddress, nullptr);
  10049. return false;
  10050. }
  10051. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10052. output_error_log(Error::Listen, nullptr);
  10053. return false;
  10054. }
  10055. return true;
  10056. });
  10057. }
  10058. inline int Server::bind_internal(const std::string &host, int port,
  10059. int socket_flags) {
  10060. if (is_decommissioned) { return -1; }
  10061. if (!is_valid()) { return -1; }
  10062. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10063. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10064. if (port == 0) {
  10065. struct sockaddr_storage addr;
  10066. socklen_t addr_len = sizeof(addr);
  10067. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10068. &addr_len) == -1) {
  10069. output_error_log(Error::GetSockName, nullptr);
  10070. return -1;
  10071. }
  10072. if (addr.ss_family == AF_INET) {
  10073. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10074. } else if (addr.ss_family == AF_INET6) {
  10075. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10076. } else {
  10077. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10078. return -1;
  10079. }
  10080. } else {
  10081. return port;
  10082. }
  10083. }
  10084. inline bool Server::listen_internal() {
  10085. if (is_decommissioned) { return false; }
  10086. auto ret = true;
  10087. is_running_ = true;
  10088. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10089. if (start_handler_) { start_handler_(); }
  10090. {
  10091. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10092. while (svr_sock_ != INVALID_SOCKET) {
  10093. #ifndef _WIN32
  10094. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10095. #endif
  10096. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10097. idle_interval_usec_);
  10098. if (val == 0) { // Timeout
  10099. task_queue->on_idle();
  10100. continue;
  10101. }
  10102. #ifndef _WIN32
  10103. }
  10104. #endif
  10105. #if defined _WIN32
  10106. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10107. // OVERLAPPED
  10108. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10109. #elif defined SOCK_CLOEXEC
  10110. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10111. #else
  10112. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10113. #endif
  10114. if (sock == INVALID_SOCKET) {
  10115. if (errno == EMFILE) {
  10116. // The per-process limit of open file descriptors has been reached.
  10117. // Try to accept new connections after a short sleep.
  10118. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10119. continue;
  10120. } else if (errno == EINTR || errno == EAGAIN) {
  10121. continue;
  10122. }
  10123. if (svr_sock_ != INVALID_SOCKET) {
  10124. detail::close_socket(svr_sock_);
  10125. ret = false;
  10126. output_error_log(Error::Connection, nullptr);
  10127. } else {
  10128. ; // The server socket was closed by user.
  10129. }
  10130. break;
  10131. }
  10132. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10133. read_timeout_sec_, read_timeout_usec_);
  10134. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10135. write_timeout_sec_, write_timeout_usec_);
  10136. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10137. if (!task_queue->enqueue(
  10138. [this, sock]() { process_and_close_socket(sock); })) {
  10139. output_error_log(Error::ResourceExhaustion, nullptr);
  10140. detail::shutdown_socket(sock);
  10141. detail::close_socket(sock);
  10142. }
  10143. }
  10144. task_queue->shutdown();
  10145. }
  10146. is_decommissioned = !ret;
  10147. return ret;
  10148. }
  10149. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10150. if (pre_routing_handler_ &&
  10151. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10152. return true;
  10153. }
  10154. // File handler
  10155. if ((req.method == "GET" || req.method == "HEAD") &&
  10156. handle_file_request(req, res)) {
  10157. return true;
  10158. }
  10159. if (detail::expect_content(req)) {
  10160. // Content reader handler
  10161. {
  10162. // Track whether the ContentReader was aborted due to the decompressed
  10163. // payload exceeding `payload_max_length_`.
  10164. // The user handler runs after the lambda returns, so we must restore the
  10165. // 413 status if the handler overwrites it.
  10166. bool content_reader_payload_too_large = false;
  10167. ContentReader reader(
  10168. [&](ContentReceiver receiver) {
  10169. auto result = read_content_with_content_receiver(
  10170. strm, req, res, std::move(receiver), nullptr, nullptr);
  10171. if (!result) {
  10172. output_error_log(Error::Read, &req);
  10173. if (res.status == StatusCode::PayloadTooLarge_413) {
  10174. content_reader_payload_too_large = true;
  10175. }
  10176. }
  10177. return result;
  10178. },
  10179. [&](FormDataHeader header, ContentReceiver receiver) {
  10180. auto result = read_content_with_content_receiver(
  10181. strm, req, res, nullptr, std::move(header),
  10182. std::move(receiver));
  10183. if (!result) {
  10184. output_error_log(Error::Read, &req);
  10185. if (res.status == StatusCode::PayloadTooLarge_413) {
  10186. content_reader_payload_too_large = true;
  10187. }
  10188. }
  10189. return result;
  10190. });
  10191. bool dispatched = false;
  10192. if (req.method == "POST") {
  10193. dispatched = dispatch_request_for_content_reader(
  10194. req, res, std::move(reader), post_handlers_for_content_reader_);
  10195. } else if (req.method == "PUT") {
  10196. dispatched = dispatch_request_for_content_reader(
  10197. req, res, std::move(reader), put_handlers_for_content_reader_);
  10198. } else if (req.method == "PATCH") {
  10199. dispatched = dispatch_request_for_content_reader(
  10200. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10201. } else if (req.method == "DELETE") {
  10202. dispatched = dispatch_request_for_content_reader(
  10203. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10204. }
  10205. if (dispatched) {
  10206. if (content_reader_payload_too_large) {
  10207. // Enforce the limit: override any status the handler may have set
  10208. // and return false so the error path sends a plain 413 response.
  10209. res.status = StatusCode::PayloadTooLarge_413;
  10210. res.body.clear();
  10211. res.content_length_ = 0;
  10212. res.content_provider_ = nullptr;
  10213. return false;
  10214. }
  10215. return true;
  10216. }
  10217. }
  10218. // NOTE: `req.body` is not read here. For a regular handler the body is
  10219. // read inside dispatch_request(), after the route has matched and the
  10220. // pre-request handler has approved the request, so that a rejected
  10221. // request (e.g. failed authentication) never forces us to buffer a
  10222. // potentially large body.
  10223. }
  10224. // Regular handler
  10225. if (req.method == "GET" || req.method == "HEAD") {
  10226. return dispatch_request(req, res, get_handlers_, strm);
  10227. } else if (req.method == "POST") {
  10228. return dispatch_request(req, res, post_handlers_, strm);
  10229. } else if (req.method == "PUT") {
  10230. return dispatch_request(req, res, put_handlers_, strm);
  10231. } else if (req.method == "DELETE") {
  10232. return dispatch_request(req, res, delete_handlers_, strm);
  10233. } else if (req.method == "OPTIONS") {
  10234. return dispatch_request(req, res, options_handlers_, strm);
  10235. } else if (req.method == "PATCH") {
  10236. return dispatch_request(req, res, patch_handlers_, strm);
  10237. }
  10238. res.status = StatusCode::BadRequest_400;
  10239. return false;
  10240. }
  10241. inline bool Server::dispatch_request(Request &req, Response &res,
  10242. const Handlers &handlers, Stream &strm) {
  10243. for (const auto &x : handlers) {
  10244. const auto &matcher = x.first;
  10245. const auto &handler = x.second;
  10246. if (matcher->match(req)) {
  10247. req.matched_route = matcher->pattern();
  10248. // Run the pre-request handler before reading the body so a rejected
  10249. // request (e.g. failed authentication) never forces us to buffer a
  10250. // potentially large body. `req.matched_route` is available here.
  10251. if (pre_request_handler_ &&
  10252. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10253. return true;
  10254. }
  10255. // The route matched and the request was approved; read the body now.
  10256. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10257. output_error_log(Error::Read, &req);
  10258. return false;
  10259. }
  10260. handler(req, res);
  10261. return true;
  10262. }
  10263. }
  10264. return false;
  10265. }
  10266. inline void Server::apply_ranges(const Request &req, Response &res,
  10267. std::string &content_type,
  10268. std::string &boundary) const {
  10269. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10270. auto it = res.headers.find("Content-Type");
  10271. if (it != res.headers.end()) {
  10272. content_type = it->second;
  10273. res.headers.erase(it);
  10274. }
  10275. boundary = detail::make_multipart_data_boundary();
  10276. res.set_header("Content-Type",
  10277. "multipart/byteranges; boundary=" + boundary);
  10278. }
  10279. auto type = detail::encoding_type(req, res);
  10280. if (res.body.empty()) {
  10281. if (res.content_length_ > 0) {
  10282. size_t length = 0;
  10283. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10284. length = res.content_length_;
  10285. } else if (req.ranges.size() == 1) {
  10286. auto offset_and_length = detail::get_range_offset_and_length(
  10287. req.ranges[0], res.content_length_);
  10288. length = offset_and_length.second;
  10289. auto content_range = detail::make_content_range_header_field(
  10290. offset_and_length, res.content_length_);
  10291. res.set_header("Content-Range", content_range);
  10292. } else {
  10293. length = detail::get_multipart_ranges_data_length(
  10294. req, boundary, content_type, res.content_length_);
  10295. }
  10296. res.set_header("Content-Length", std::to_string(length));
  10297. } else {
  10298. if (res.content_provider_) {
  10299. if (res.is_chunked_content_provider_) {
  10300. res.set_header("Transfer-Encoding", "chunked");
  10301. if (type != detail::EncodingType::None) {
  10302. res.set_header("Content-Encoding", detail::encoding_name(type));
  10303. res.set_header("Vary", "Accept-Encoding");
  10304. }
  10305. }
  10306. }
  10307. }
  10308. } else {
  10309. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10310. ;
  10311. } else if (req.ranges.size() == 1) {
  10312. auto offset_and_length =
  10313. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10314. auto offset = offset_and_length.first;
  10315. auto length = offset_and_length.second;
  10316. auto content_range = detail::make_content_range_header_field(
  10317. offset_and_length, res.body.size());
  10318. res.set_header("Content-Range", content_range);
  10319. assert(offset + length <= res.body.size());
  10320. res.body = res.body.substr(offset, length);
  10321. } else {
  10322. std::string data;
  10323. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10324. res.body.size(), data);
  10325. res.body.swap(data);
  10326. }
  10327. if (type != detail::EncodingType::None) {
  10328. output_pre_compression_log(req, res);
  10329. if (auto compressor = detail::make_compressor(type)) {
  10330. std::string compressed;
  10331. if (compressor->compress(res.body.data(), res.body.size(), true,
  10332. [&](const char *data, size_t data_len) {
  10333. compressed.append(data, data_len);
  10334. return true;
  10335. })) {
  10336. res.body.swap(compressed);
  10337. res.set_header("Content-Encoding", detail::encoding_name(type));
  10338. res.set_header("Vary", "Accept-Encoding");
  10339. }
  10340. }
  10341. }
  10342. auto length = std::to_string(res.body.size());
  10343. res.set_header("Content-Length", length);
  10344. }
  10345. }
  10346. inline bool Server::dispatch_request_for_content_reader(
  10347. Request &req, Response &res, ContentReader content_reader,
  10348. const HandlersForContentReader &handlers) const {
  10349. for (const auto &x : handlers) {
  10350. const auto &matcher = x.first;
  10351. const auto &handler = x.second;
  10352. if (matcher->match(req)) {
  10353. req.matched_route = matcher->pattern();
  10354. if (!pre_request_handler_ ||
  10355. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10356. handler(req, res, content_reader);
  10357. }
  10358. return true;
  10359. }
  10360. }
  10361. return false;
  10362. }
  10363. inline std::string
  10364. get_client_ip(const std::string &x_forwarded_for,
  10365. const std::vector<std::string> &trusted_proxies) {
  10366. // X-Forwarded-For is a comma-separated list per RFC 7239
  10367. std::vector<std::string> ip_list;
  10368. detail::split(x_forwarded_for.data(),
  10369. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10370. [&](const char *b, const char *e) {
  10371. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10372. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10373. });
  10374. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10375. // no segments. Signal "no client IP derived" with an empty string so the
  10376. // caller can fall back to the connection-level remote address.
  10377. if (ip_list.empty()) { return std::string(); }
  10378. for (size_t i = 0; i < ip_list.size(); ++i) {
  10379. auto ip = ip_list[i];
  10380. auto is_trusted_proxy =
  10381. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10382. [&](const std::string &proxy) { return ip == proxy; });
  10383. if (is_trusted_proxy) {
  10384. if (i == 0) {
  10385. // If the trusted proxy is the first IP, there's no preceding client IP
  10386. return ip;
  10387. } else {
  10388. // Return the IP immediately before the trusted proxy
  10389. return ip_list[i - 1];
  10390. }
  10391. }
  10392. }
  10393. // If no trusted proxy is found, return the first IP in the list
  10394. return ip_list.front();
  10395. }
  10396. inline bool
  10397. Server::process_request(Stream &strm, const std::string &remote_addr,
  10398. int remote_port, const std::string &local_addr,
  10399. int local_port, bool close_connection,
  10400. bool &connection_closed,
  10401. const std::function<void(Request &)> &setup_request,
  10402. bool *websocket_upgraded) {
  10403. std::array<char, 2048> buf{};
  10404. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10405. // Connection has been closed on client
  10406. if (!line_reader.getline()) { return false; }
  10407. Request req;
  10408. req.start_time_ = std::chrono::steady_clock::now();
  10409. req.remote_addr = remote_addr;
  10410. req.remote_port = remote_port;
  10411. req.local_addr = local_addr;
  10412. req.local_port = local_port;
  10413. Response res;
  10414. res.version = "HTTP/1.1";
  10415. res.headers = default_headers_;
  10416. // Request line and headers
  10417. if (!parse_request_line(line_reader.ptr(), req)) {
  10418. res.status = StatusCode::BadRequest_400;
  10419. output_error_log(Error::InvalidRequestLine, &req);
  10420. return write_response(strm, close_connection, req, res);
  10421. }
  10422. // Request headers
  10423. if (!detail::read_headers(strm, req.headers)) {
  10424. res.status = StatusCode::BadRequest_400;
  10425. output_error_log(Error::InvalidHeaders, &req);
  10426. return write_response(strm, close_connection, req, res);
  10427. }
  10428. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10429. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10430. // tolerated for compatibility with existing clients.
  10431. if (req.get_header_value_u64("Content-Length") > 0 &&
  10432. req.has_header("Transfer-Encoding")) {
  10433. connection_closed = true;
  10434. res.status = StatusCode::BadRequest_400;
  10435. return write_response(strm, close_connection, req, res);
  10436. }
  10437. // Check if the request URI doesn't exceed the limit
  10438. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10439. connection_closed = true;
  10440. res.status = StatusCode::UriTooLong_414;
  10441. output_error_log(Error::ExceedUriMaxLength, &req);
  10442. return write_response(strm, close_connection, req, res);
  10443. }
  10444. if (req.get_header_value("Connection") == "close") {
  10445. connection_closed = true;
  10446. }
  10447. if (req.version == "HTTP/1.0" &&
  10448. req.get_header_value("Connection") != "Keep-Alive") {
  10449. connection_closed = true;
  10450. }
  10451. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10452. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10453. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10454. req.remote_addr = derived.empty() ? remote_addr : derived;
  10455. } else {
  10456. req.remote_addr = remote_addr;
  10457. }
  10458. req.remote_port = remote_port;
  10459. req.local_addr = local_addr;
  10460. req.local_port = local_port;
  10461. if (req.has_header("Accept")) {
  10462. const auto &accept_header = req.get_header_value("Accept");
  10463. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10464. connection_closed = true;
  10465. res.status = StatusCode::BadRequest_400;
  10466. output_error_log(Error::HTTPParsing, &req);
  10467. return write_response(strm, close_connection, req, res);
  10468. }
  10469. }
  10470. if (req.has_header("Range")) {
  10471. const auto &range_header_value = req.get_header_value("Range");
  10472. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10473. connection_closed = true;
  10474. res.status = StatusCode::RangeNotSatisfiable_416;
  10475. output_error_log(Error::InvalidRangeHeader, &req);
  10476. return write_response(strm, close_connection, req, res);
  10477. }
  10478. }
  10479. if (setup_request) { setup_request(req); }
  10480. if (req.get_header_value("Expect") == "100-continue") {
  10481. int status = StatusCode::Continue_100;
  10482. if (expect_100_continue_handler_) {
  10483. status = expect_100_continue_handler_(req, res);
  10484. }
  10485. switch (status) {
  10486. case StatusCode::Continue_100:
  10487. case StatusCode::ExpectationFailed_417:
  10488. detail::write_response_line(strm, status);
  10489. strm.write("\r\n");
  10490. break;
  10491. default:
  10492. connection_closed = true;
  10493. return write_response(strm, true, req, res);
  10494. }
  10495. }
  10496. // Setup `is_connection_closed` method
  10497. auto sock = strm.socket();
  10498. req.is_connection_closed = [sock]() {
  10499. return !detail::is_socket_alive(sock);
  10500. };
  10501. // WebSocket upgrade
  10502. // Check pre_routing_handler_ before upgrading so that authentication
  10503. // and other middleware can reject the request with an HTTP response
  10504. // (e.g., 401) before the protocol switches.
  10505. if (detail::is_websocket_upgrade(req)) {
  10506. if (pre_routing_handler_ &&
  10507. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10508. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10509. return write_response(strm, close_connection, req, res);
  10510. }
  10511. // Find matching WebSocket handler
  10512. for (const auto &entry : websocket_handlers_) {
  10513. if (entry.matcher->match(req)) {
  10514. // Compute accept key
  10515. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10516. auto accept_key = detail::websocket_accept_key(client_key);
  10517. // Negotiate subprotocol
  10518. std::string selected_subprotocol;
  10519. if (entry.sub_protocol_selector) {
  10520. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10521. if (!protocol_header.empty()) {
  10522. std::vector<std::string> protocols;
  10523. std::istringstream iss(protocol_header);
  10524. std::string token;
  10525. while (std::getline(iss, token, ',')) {
  10526. // Trim whitespace
  10527. auto start = token.find_first_not_of(' ');
  10528. auto end = token.find_last_not_of(' ');
  10529. if (start != std::string::npos) {
  10530. protocols.push_back(token.substr(start, end - start + 1));
  10531. }
  10532. }
  10533. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10534. }
  10535. }
  10536. // Send 101 Switching Protocols
  10537. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10538. "Upgrade: websocket\r\n"
  10539. "Connection: Upgrade\r\n"
  10540. "Sec-WebSocket-Accept: " +
  10541. accept_key + "\r\n";
  10542. if (!selected_subprotocol.empty()) {
  10543. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10544. return false;
  10545. }
  10546. handshake_response +=
  10547. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10548. }
  10549. handshake_response += "\r\n";
  10550. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10551. 0) {
  10552. return false;
  10553. }
  10554. connection_closed = true;
  10555. if (websocket_upgraded) { *websocket_upgraded = true; }
  10556. {
  10557. // Use WebSocket-specific read timeout instead of HTTP timeout
  10558. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10559. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10560. websocket_max_missed_pongs_);
  10561. entry.handler(req, ws);
  10562. }
  10563. return true;
  10564. }
  10565. }
  10566. // No matching handler - fall through to 404
  10567. }
  10568. // Routing
  10569. auto routed = false;
  10570. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10571. routed = routing(req, res, strm);
  10572. #else
  10573. try {
  10574. routed = routing(req, res, strm);
  10575. } catch (std::exception &) {
  10576. if (exception_handler_) {
  10577. auto ep = std::current_exception();
  10578. exception_handler_(req, res, ep);
  10579. routed = true;
  10580. } else {
  10581. res.status = StatusCode::InternalServerError_500;
  10582. }
  10583. } catch (...) {
  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. }
  10592. #endif
  10593. auto ret = false;
  10594. if (routed) {
  10595. if (res.status == -1) {
  10596. res.status = req.ranges.empty() ? StatusCode::OK_200
  10597. : StatusCode::PartialContent_206;
  10598. }
  10599. // Serve file content by using a content provider
  10600. auto file_open_error = false;
  10601. if (!res.file_content_path_.empty()) {
  10602. const auto &path = res.file_content_path_;
  10603. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10604. if (!mm->is_open()) {
  10605. res.body.clear();
  10606. res.content_length_ = 0;
  10607. res.content_provider_ = nullptr;
  10608. res.status = StatusCode::NotFound_404;
  10609. output_error_log(Error::OpenFile, &req);
  10610. file_open_error = true;
  10611. } else {
  10612. auto content_type = res.file_content_content_type_;
  10613. if (content_type.empty()) {
  10614. content_type = detail::find_content_type(
  10615. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10616. }
  10617. res.set_content_provider(
  10618. mm->size(), content_type,
  10619. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10620. sink.write(mm->data() + offset, length);
  10621. return true;
  10622. });
  10623. }
  10624. }
  10625. if (file_open_error) {
  10626. ret = write_response(strm, close_connection, req, res);
  10627. } else if (detail::range_error(req, res)) {
  10628. res.body.clear();
  10629. res.content_length_ = 0;
  10630. res.content_provider_ = nullptr;
  10631. res.status = StatusCode::RangeNotSatisfiable_416;
  10632. ret = write_response(strm, close_connection, req, res);
  10633. } else {
  10634. ret = write_response_with_content(strm, close_connection, req, res);
  10635. }
  10636. } else {
  10637. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10638. ret = write_response(strm, close_connection, req, res);
  10639. }
  10640. // Drain any unconsumed framed body to prevent request smuggling on
  10641. // keep-alive. Without framing there is no body to drain — reading would
  10642. // consume the next request (issue #2450).
  10643. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10644. int dummy_status;
  10645. if (!detail::read_content(
  10646. strm, req, payload_max_length_, dummy_status, nullptr,
  10647. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10648. connection_closed = true;
  10649. }
  10650. }
  10651. return ret;
  10652. }
  10653. inline bool Server::is_valid() const { return true; }
  10654. inline bool Server::process_and_close_socket(socket_t sock) {
  10655. std::string remote_addr;
  10656. int remote_port = 0;
  10657. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10658. std::string local_addr;
  10659. int local_port = 0;
  10660. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10661. bool websocket_upgraded = false;
  10662. auto ret = detail::process_server_socket(
  10663. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10664. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10665. write_timeout_usec_,
  10666. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10667. return process_request(strm, remote_addr, remote_port, local_addr,
  10668. local_port, close_connection, connection_closed,
  10669. nullptr, &websocket_upgraded);
  10670. });
  10671. detail::shutdown_socket(sock);
  10672. detail::close_socket(sock);
  10673. return ret;
  10674. }
  10675. inline void Server::output_log(const Request &req, const Response &res) const {
  10676. if (logger_) {
  10677. std::lock_guard<std::mutex> guard(logger_mutex_);
  10678. logger_(req, res);
  10679. }
  10680. }
  10681. inline void Server::output_pre_compression_log(const Request &req,
  10682. const Response &res) const {
  10683. if (pre_compression_logger_) {
  10684. std::lock_guard<std::mutex> guard(logger_mutex_);
  10685. pre_compression_logger_(req, res);
  10686. }
  10687. }
  10688. inline void Server::output_error_log(const Error &err,
  10689. const Request *req) const {
  10690. if (error_logger_) {
  10691. std::lock_guard<std::mutex> guard(logger_mutex_);
  10692. error_logger_(err, req);
  10693. }
  10694. }
  10695. /*
  10696. * Group 5: ClientImpl and Client (Universal) implementation
  10697. */
  10698. // HTTP client implementation
  10699. inline ClientImpl::ClientImpl(const std::string &host)
  10700. : ClientImpl(host, 80, std::string(), std::string()) {}
  10701. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10702. : ClientImpl(host, port, std::string(), std::string()) {}
  10703. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10704. const std::string &client_cert_path,
  10705. const std::string &client_key_path)
  10706. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10707. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10708. inline ClientImpl::~ClientImpl() {
  10709. // Wait until all the requests in flight are handled.
  10710. size_t retry_count = 10;
  10711. while (retry_count-- > 0) {
  10712. {
  10713. std::lock_guard<std::mutex> guard(socket_mutex_);
  10714. if (socket_requests_in_flight_ == 0) { break; }
  10715. }
  10716. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10717. }
  10718. std::lock_guard<std::mutex> guard(socket_mutex_);
  10719. shutdown_socket(socket_);
  10720. close_socket(socket_);
  10721. }
  10722. inline bool ClientImpl::is_valid() const { return true; }
  10723. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10724. client_cert_path_ = rhs.client_cert_path_;
  10725. client_key_path_ = rhs.client_key_path_;
  10726. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10727. read_timeout_sec_ = rhs.read_timeout_sec_;
  10728. read_timeout_usec_ = rhs.read_timeout_usec_;
  10729. write_timeout_sec_ = rhs.write_timeout_sec_;
  10730. write_timeout_usec_ = rhs.write_timeout_usec_;
  10731. max_timeout_msec_ = rhs.max_timeout_msec_;
  10732. basic_auth_username_ = rhs.basic_auth_username_;
  10733. basic_auth_password_ = rhs.basic_auth_password_;
  10734. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10735. keep_alive_ = rhs.keep_alive_;
  10736. follow_location_ = rhs.follow_location_;
  10737. path_encode_ = rhs.path_encode_;
  10738. address_family_ = rhs.address_family_;
  10739. tcp_nodelay_ = rhs.tcp_nodelay_;
  10740. ipv6_v6only_ = rhs.ipv6_v6only_;
  10741. socket_options_ = rhs.socket_options_;
  10742. compress_ = rhs.compress_;
  10743. decompress_ = rhs.decompress_;
  10744. payload_max_length_ = rhs.payload_max_length_;
  10745. has_payload_max_length_ = rhs.has_payload_max_length_;
  10746. interface_ = rhs.interface_;
  10747. proxy_host_ = rhs.proxy_host_;
  10748. proxy_port_ = rhs.proxy_port_;
  10749. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10750. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10751. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10752. no_proxy_entries_ = rhs.no_proxy_entries_;
  10753. logger_ = rhs.logger_;
  10754. error_logger_ = rhs.error_logger_;
  10755. #ifdef CPPHTTPLIB_SSL_ENABLED
  10756. digest_auth_username_ = rhs.digest_auth_username_;
  10757. digest_auth_password_ = rhs.digest_auth_password_;
  10758. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10759. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10760. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10761. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10762. server_certificate_verification_ = rhs.server_certificate_verification_;
  10763. server_hostname_verification_ = rhs.server_hostname_verification_;
  10764. system_ca_mode_ = rhs.system_ca_mode_;
  10765. #endif
  10766. }
  10767. inline bool
  10768. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10769. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10770. if (no_proxy_entries_.empty()) { return true; }
  10771. // host_ is const so its normalized form is invariant; cache it. The
  10772. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10773. if (host == host_) {
  10774. if (!host_normalized_valid_) {
  10775. host_normalized_ = detail::normalize_target(host_);
  10776. host_normalized_valid_ = true;
  10777. }
  10778. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10779. }
  10780. auto target = detail::normalize_target(host);
  10781. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10782. }
  10783. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10784. if (is_proxy_enabled_for_host(host_)) {
  10785. return detail::create_client_socket(
  10786. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10787. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10788. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10789. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10790. }
  10791. // Check is custom IP specified for host_
  10792. std::string ip;
  10793. auto it = addr_map_.find(host_);
  10794. if (it != addr_map_.end()) { ip = it->second; }
  10795. return detail::create_client_socket(
  10796. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10797. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10798. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10799. write_timeout_usec_, interface_, error);
  10800. }
  10801. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10802. Error &error) {
  10803. auto sock = create_client_socket(error);
  10804. if (sock == INVALID_SOCKET) { return false; }
  10805. socket.sock = sock;
  10806. return true;
  10807. }
  10808. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10809. return create_and_connect_socket(socket, error);
  10810. }
  10811. inline bool ClientImpl::setup_proxy_connection(
  10812. Socket & /*socket*/,
  10813. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10814. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10815. return true;
  10816. }
  10817. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10818. bool /*shutdown_gracefully*/) {
  10819. // If there are any requests in flight from threads other than us, then it's
  10820. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10821. assert(socket_requests_in_flight_ == 0 ||
  10822. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10823. }
  10824. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10825. if (socket.sock == INVALID_SOCKET) { return; }
  10826. detail::shutdown_socket(socket.sock);
  10827. }
  10828. inline void ClientImpl::close_socket(Socket &socket) {
  10829. // If there are requests in flight in another thread, usually closing
  10830. // the socket will be fine and they will simply receive an error when
  10831. // using the closed socket, but it is still a bug since rarely the OS
  10832. // may reassign the socket id to be used for a new socket, and then
  10833. // suddenly they will be operating on a live socket that is different
  10834. // than the one they intended!
  10835. assert(socket_requests_in_flight_ == 0 ||
  10836. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10837. // It is also a bug if this happens while SSL is still active
  10838. #ifdef CPPHTTPLIB_SSL_ENABLED
  10839. assert(socket.ssl == nullptr);
  10840. #endif
  10841. if (socket.sock == INVALID_SOCKET) { return; }
  10842. detail::close_socket(socket.sock);
  10843. socket.sock = INVALID_SOCKET;
  10844. }
  10845. inline void ClientImpl::disconnect(bool gracefully) {
  10846. shutdown_ssl(socket_, gracefully);
  10847. shutdown_socket(socket_);
  10848. close_socket(socket_);
  10849. }
  10850. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10851. Response &res,
  10852. bool skip_100_continue) const {
  10853. std::array<char, 2048> buf{};
  10854. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10855. if (!line_reader.getline()) { return false; }
  10856. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10857. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10858. #else
  10859. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10860. #endif
  10861. std::cmatch m;
  10862. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10863. return req.method == "CONNECT";
  10864. }
  10865. res.version = std::string(m[1]);
  10866. res.status = std::stoi(std::string(m[2]));
  10867. res.reason = std::string(m[3]);
  10868. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10869. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10870. if (!line_reader.getline()) { return false; } // CRLF
  10871. if (!line_reader.getline()) { return false; } // next response line
  10872. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10873. res.version = std::string(m[1]);
  10874. res.status = std::stoi(std::string(m[2]));
  10875. res.reason = std::string(m[3]);
  10876. }
  10877. return true;
  10878. }
  10879. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10880. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10881. auto ret = send_(req, res, error);
  10882. if (error == Error::SSLPeerCouldBeClosed_) {
  10883. assert(!ret);
  10884. ret = send_(req, res, error);
  10885. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10886. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10887. }
  10888. return ret;
  10889. }
  10890. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10891. {
  10892. std::lock_guard<std::mutex> guard(socket_mutex_);
  10893. // Set this to false immediately - if it ever gets set to true by the end
  10894. // of the request, we know another thread instructed us to close the
  10895. // socket.
  10896. socket_should_be_closed_when_request_is_done_ = false;
  10897. auto is_alive = false;
  10898. if (socket_.is_open()) {
  10899. is_alive = detail::is_socket_alive(socket_.sock);
  10900. #ifdef CPPHTTPLIB_SSL_ENABLED
  10901. if (is_alive && is_ssl()) {
  10902. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10903. is_alive = false;
  10904. }
  10905. }
  10906. #endif
  10907. if (!is_alive) {
  10908. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10909. disconnect(/*gracefully=*/false);
  10910. }
  10911. }
  10912. if (!is_alive) {
  10913. if (!ensure_socket_connection(socket_, error)) {
  10914. output_error_log(error, &req);
  10915. return false;
  10916. }
  10917. {
  10918. auto success = true;
  10919. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10920. error)) {
  10921. if (!success) { output_error_log(error, &req); }
  10922. return success;
  10923. }
  10924. }
  10925. }
  10926. // Mark the current socket as being in use so that it cannot be closed by
  10927. // anyone else while this request is ongoing, even though we will be
  10928. // releasing the mutex.
  10929. if (socket_requests_in_flight_ > 1) {
  10930. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10931. }
  10932. socket_requests_in_flight_ += 1;
  10933. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10934. }
  10935. for (const auto &header : default_headers_) {
  10936. if (req.headers.find(header.first) == req.headers.end()) {
  10937. req.headers.insert(header);
  10938. }
  10939. }
  10940. auto ret = false;
  10941. auto close_connection = !keep_alive_;
  10942. auto se = detail::scope_exit([&]() {
  10943. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10944. std::lock_guard<std::mutex> guard(socket_mutex_);
  10945. socket_requests_in_flight_ -= 1;
  10946. if (socket_requests_in_flight_ <= 0) {
  10947. assert(socket_requests_in_flight_ == 0);
  10948. socket_requests_are_from_thread_ = std::thread::id();
  10949. }
  10950. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10951. !ret) {
  10952. disconnect(/*gracefully=*/true);
  10953. }
  10954. });
  10955. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10956. return handle_request(strm, req, res, close_connection, error);
  10957. });
  10958. if (!ret) {
  10959. if (error == Error::Success) {
  10960. error = Error::Unknown;
  10961. output_error_log(error, &req);
  10962. }
  10963. }
  10964. return ret;
  10965. }
  10966. inline Result ClientImpl::send(const Request &req) {
  10967. auto req2 = req;
  10968. return send_(std::move(req2));
  10969. }
  10970. inline Result ClientImpl::send_(Request &&req) {
  10971. auto res = detail::make_unique<Response>();
  10972. auto error = Error::Success;
  10973. auto ret = send(req, *res, error);
  10974. #ifdef CPPHTTPLIB_SSL_ENABLED
  10975. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10976. last_ssl_error_, last_backend_error_};
  10977. #else
  10978. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10979. #endif
  10980. }
  10981. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10982. const std::string &ct) {
  10983. (void)for_stream;
  10984. for (const auto &header : default_headers_) {
  10985. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10986. }
  10987. if (!r.has_header("Host")) {
  10988. if (address_family_ == AF_UNIX) {
  10989. r.headers.emplace("Host", "localhost");
  10990. } else {
  10991. r.headers.emplace(
  10992. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10993. }
  10994. }
  10995. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10996. if (!r.content_receiver) {
  10997. if (!r.has_header("Accept-Encoding")) {
  10998. std::string accept_encoding;
  10999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11000. accept_encoding = "br";
  11001. #endif
  11002. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11003. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11004. accept_encoding += "gzip, deflate";
  11005. #endif
  11006. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11007. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11008. accept_encoding += "zstd";
  11009. #endif
  11010. r.set_header("Accept-Encoding", accept_encoding);
  11011. }
  11012. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11013. if (!r.has_header("User-Agent")) {
  11014. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11015. r.set_header("User-Agent", agent);
  11016. }
  11017. #endif
  11018. }
  11019. if (!r.body.empty()) {
  11020. if (!ct.empty() && !r.has_header("Content-Type")) {
  11021. r.headers.emplace("Content-Type", ct);
  11022. }
  11023. if (!r.has_header("Content-Length")) {
  11024. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11025. }
  11026. }
  11027. }
  11028. inline ClientImpl::StreamHandle
  11029. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11030. const Params &params, const Headers &headers,
  11031. const std::string &body,
  11032. const std::string &content_type) {
  11033. StreamHandle handle;
  11034. handle.response = detail::make_unique<Response>();
  11035. handle.error = Error::Success;
  11036. auto query_path = params.empty() ? path : append_query_params(path, params);
  11037. handle.connection_ = detail::make_unique<ClientConnection>();
  11038. {
  11039. std::lock_guard<std::mutex> guard(socket_mutex_);
  11040. auto is_alive = false;
  11041. if (socket_.is_open()) {
  11042. is_alive = detail::is_socket_alive(socket_.sock);
  11043. #ifdef CPPHTTPLIB_SSL_ENABLED
  11044. if (is_alive && is_ssl()) {
  11045. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11046. is_alive = false;
  11047. }
  11048. }
  11049. #endif
  11050. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11051. }
  11052. if (!is_alive) {
  11053. if (!ensure_socket_connection(socket_, handle.error)) {
  11054. handle.response.reset();
  11055. return handle;
  11056. }
  11057. {
  11058. auto success = true;
  11059. auto start_time = std::chrono::steady_clock::now();
  11060. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11061. success, handle.error)) {
  11062. if (!success) { handle.response.reset(); }
  11063. return handle;
  11064. }
  11065. }
  11066. }
  11067. transfer_socket_ownership_to_handle(handle);
  11068. }
  11069. #ifdef CPPHTTPLIB_SSL_ENABLED
  11070. if (is_ssl() && handle.connection_->session) {
  11071. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11072. handle.connection_->sock, handle.connection_->session,
  11073. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11074. write_timeout_usec_);
  11075. } else {
  11076. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11077. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11078. write_timeout_sec_, write_timeout_usec_);
  11079. }
  11080. #else
  11081. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11082. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11083. write_timeout_sec_, write_timeout_usec_);
  11084. #endif
  11085. handle.stream_ = handle.socket_stream_.get();
  11086. Request req;
  11087. req.method = method;
  11088. req.path = query_path;
  11089. req.headers = headers;
  11090. req.body = body;
  11091. prepare_default_headers(req, true, content_type);
  11092. auto &strm = *handle.stream_;
  11093. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11094. handle.error = Error::Write;
  11095. handle.response.reset();
  11096. return handle;
  11097. }
  11098. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11099. handle.error)) {
  11100. handle.response.reset();
  11101. return handle;
  11102. }
  11103. if (!body.empty()) {
  11104. if (strm.write(body.data(), body.size()) < 0) {
  11105. handle.error = Error::Write;
  11106. handle.response.reset();
  11107. return handle;
  11108. }
  11109. }
  11110. if (!read_response_line(strm, req, *handle.response) ||
  11111. !detail::read_headers(strm, handle.response->headers)) {
  11112. handle.error = Error::Read;
  11113. handle.response.reset();
  11114. return handle;
  11115. }
  11116. handle.body_reader_.stream = handle.stream_;
  11117. handle.body_reader_.payload_max_length = payload_max_length_;
  11118. if (handle.response->has_header("Content-Length")) {
  11119. bool is_invalid = false;
  11120. auto content_length = detail::get_header_value_u64(
  11121. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11122. if (is_invalid) {
  11123. handle.error = Error::Read;
  11124. handle.response.reset();
  11125. return handle;
  11126. }
  11127. handle.body_reader_.has_content_length = true;
  11128. handle.body_reader_.content_length = content_length;
  11129. }
  11130. auto transfer_encoding =
  11131. handle.response->get_header_value("Transfer-Encoding");
  11132. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  11133. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11134. if (!content_encoding.empty()) {
  11135. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11136. }
  11137. return handle;
  11138. }
  11139. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11140. if (!is_valid() || !response) { return -1; }
  11141. if (decompressor_) { return read_with_decompression(buf, len); }
  11142. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11143. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11144. trailers_parsed_ = true;
  11145. if (body_reader_.chunked_decoder) {
  11146. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11147. response->trailers, response->headers)) {
  11148. return n;
  11149. }
  11150. } else {
  11151. detail::ChunkedDecoder dec(*stream_);
  11152. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11153. return n;
  11154. }
  11155. }
  11156. }
  11157. return n;
  11158. }
  11159. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11160. size_t len) {
  11161. if (decompress_offset_ < decompress_buffer_.size()) {
  11162. auto available = decompress_buffer_.size() - decompress_offset_;
  11163. auto to_copy = (std::min)(len, available);
  11164. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11165. decompress_offset_ += to_copy;
  11166. decompressed_bytes_read_ += to_copy;
  11167. return static_cast<ssize_t>(to_copy);
  11168. }
  11169. decompress_buffer_.clear();
  11170. decompress_offset_ = 0;
  11171. constexpr size_t kDecompressionBufferSize = 8192;
  11172. char compressed_buf[kDecompressionBufferSize];
  11173. while (true) {
  11174. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11175. sizeof(compressed_buf));
  11176. if (n <= 0) { return n; }
  11177. bool decompress_ok = decompressor_->decompress(
  11178. compressed_buf, static_cast<size_t>(n),
  11179. [this](const char *data, size_t data_len) {
  11180. decompress_buffer_.append(data, data_len);
  11181. auto limit = body_reader_.payload_max_length;
  11182. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11183. return false;
  11184. }
  11185. return true;
  11186. });
  11187. if (!decompress_ok) {
  11188. body_reader_.last_error = Error::Read;
  11189. return -1;
  11190. }
  11191. if (!decompress_buffer_.empty()) { break; }
  11192. }
  11193. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11194. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11195. decompress_offset_ = to_copy;
  11196. decompressed_bytes_read_ += to_copy;
  11197. return static_cast<ssize_t>(to_copy);
  11198. }
  11199. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11200. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11201. return;
  11202. }
  11203. trailers_parsed_ = true;
  11204. const auto bufsiz = 128;
  11205. char line_buf[bufsiz];
  11206. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11207. if (!line_reader.getline()) { return; }
  11208. if (!detail::parse_trailers(line_reader, response->trailers,
  11209. response->headers)) {
  11210. return;
  11211. }
  11212. }
  11213. namespace detail {
  11214. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11215. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11216. size_t &out_chunk_offset,
  11217. size_t &out_chunk_total) {
  11218. if (finished) { return 0; }
  11219. if (chunk_remaining == 0) {
  11220. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11221. if (!lr.getline()) { return -1; }
  11222. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11223. const char *p = lr.ptr();
  11224. int v = 0;
  11225. if (!is_hex(*p, v)) { return -1; }
  11226. size_t chunk_len = 0;
  11227. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11228. for (; is_hex(*p, v); ++p) {
  11229. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11230. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11231. }
  11232. while (is_space_or_tab(*p)) {
  11233. ++p;
  11234. }
  11235. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11236. if (chunk_len == 0) {
  11237. chunk_remaining = 0;
  11238. finished = true;
  11239. out_chunk_offset = 0;
  11240. out_chunk_total = 0;
  11241. return 0;
  11242. }
  11243. chunk_remaining = chunk_len;
  11244. last_chunk_total = chunk_remaining;
  11245. last_chunk_offset = 0;
  11246. }
  11247. auto to_read = (std::min)(chunk_remaining, len);
  11248. auto n = strm.read(buf, to_read);
  11249. if (n <= 0) { return -1; }
  11250. auto offset_before = last_chunk_offset;
  11251. last_chunk_offset += static_cast<size_t>(n);
  11252. chunk_remaining -= static_cast<size_t>(n);
  11253. out_chunk_offset = offset_before;
  11254. out_chunk_total = last_chunk_total;
  11255. if (chunk_remaining == 0) {
  11256. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11257. if (!lr.getline()) { return -1; }
  11258. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11259. }
  11260. return n;
  11261. }
  11262. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11263. const Headers &src_headers) {
  11264. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11265. if (!lr.getline()) { return false; }
  11266. return parse_trailers(lr, dest, src_headers);
  11267. }
  11268. } // namespace detail
  11269. inline void
  11270. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11271. handle.connection_->sock = socket_.sock;
  11272. #ifdef CPPHTTPLIB_SSL_ENABLED
  11273. handle.connection_->session = socket_.ssl;
  11274. socket_.ssl = nullptr;
  11275. #endif
  11276. socket_.sock = INVALID_SOCKET;
  11277. }
  11278. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11279. Response &res, bool close_connection,
  11280. Error &error) {
  11281. if (req.path.empty()) {
  11282. error = Error::Connection;
  11283. output_error_log(error, &req);
  11284. return false;
  11285. }
  11286. auto req_save = req;
  11287. bool ret;
  11288. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11289. auto req2 = req;
  11290. req2.path = "http://" +
  11291. detail::make_host_and_port_string(host_, port_, false) +
  11292. req.path;
  11293. ret = process_request(strm, req2, res, close_connection, error);
  11294. req = std::move(req2);
  11295. req.path = req_save.path;
  11296. } else {
  11297. ret = process_request(strm, req, res, close_connection, error);
  11298. }
  11299. if (!ret) { return false; }
  11300. if (res.get_header_value("Connection") == "close" ||
  11301. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11302. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11303. // for this to be safe.
  11304. // This is safe to call because handle_request is only called by send_
  11305. // which locks the request mutex during the process. It would be a bug
  11306. // to call it from a different thread since it's a thread-safety issue
  11307. // to do these things to the socket if another thread is using the socket.
  11308. std::lock_guard<std::mutex> guard(socket_mutex_);
  11309. disconnect(/*gracefully=*/true);
  11310. }
  11311. if (300 < res.status && res.status < 400 && follow_location_) {
  11312. req = std::move(req_save);
  11313. ret = redirect(req, res, error);
  11314. }
  11315. #ifdef CPPHTTPLIB_SSL_ENABLED
  11316. if ((res.status == StatusCode::Unauthorized_401 ||
  11317. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11318. req.authorization_count_ < 5) {
  11319. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11320. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11321. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11322. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11323. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11324. return ret;
  11325. }
  11326. const auto &username =
  11327. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11328. const auto &password =
  11329. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11330. if (!username.empty() && !password.empty()) {
  11331. std::map<std::string, std::string> auth;
  11332. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11333. Request new_req = req;
  11334. new_req.authorization_count_ += 1;
  11335. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11336. : "Authorization");
  11337. new_req.headers.insert(detail::make_digest_authentication_header(
  11338. req, auth, new_req.authorization_count_, detail::random_string(10),
  11339. username, password, is_proxy));
  11340. Response new_res;
  11341. ret = send(new_req, new_res, error);
  11342. if (ret) { res = std::move(new_res); }
  11343. }
  11344. }
  11345. }
  11346. #endif
  11347. return ret;
  11348. }
  11349. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11350. if (req.redirect_count_ == 0) {
  11351. error = Error::ExceedRedirectCount;
  11352. output_error_log(error, &req);
  11353. return false;
  11354. }
  11355. auto location = res.get_header_value("location");
  11356. if (location.empty()) { return false; }
  11357. detail::UrlComponents uc;
  11358. if (!detail::parse_url(location, uc)) { return false; }
  11359. // Only follow http/https redirects
  11360. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11361. return false;
  11362. }
  11363. auto scheme = is_ssl() ? "https" : "http";
  11364. auto next_scheme = std::move(uc.scheme);
  11365. auto next_host = std::move(uc.host);
  11366. auto port_str = std::move(uc.port);
  11367. auto next_path = std::move(uc.path);
  11368. auto next_query = std::move(uc.query);
  11369. auto next_port = port_;
  11370. if (!port_str.empty()) {
  11371. if (!detail::parse_port(port_str, next_port)) { return false; }
  11372. } else if (!next_scheme.empty()) {
  11373. next_port = next_scheme == "https" ? 443 : 80;
  11374. }
  11375. if (next_scheme.empty()) { next_scheme = scheme; }
  11376. if (next_host.empty()) { next_host = host_; }
  11377. if (next_path.empty()) { next_path = "/"; }
  11378. auto path = decode_path_component(next_path) + next_query;
  11379. // Same host redirect - use current client
  11380. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11381. return detail::redirect(*this, req, res, path, location, error);
  11382. }
  11383. // Cross-host/scheme redirect - create new client with robust setup
  11384. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11385. path, location, error);
  11386. }
  11387. // New method for robust redirect client creation
  11388. inline bool ClientImpl::create_redirect_client(
  11389. const std::string &scheme, const std::string &host, int port, Request &req,
  11390. Response &res, const std::string &path, const std::string &location,
  11391. Error &error) {
  11392. // Determine if we need SSL
  11393. auto need_ssl = (scheme == "https");
  11394. // Clean up request headers that are host/client specific
  11395. // Remove headers that should not be carried over to new host
  11396. auto headers_to_remove =
  11397. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  11398. for (const auto &header_name : headers_to_remove) {
  11399. auto it = req.headers.find(header_name);
  11400. while (it != req.headers.end()) {
  11401. it = req.headers.erase(it);
  11402. it = req.headers.find(header_name);
  11403. }
  11404. }
  11405. // Create appropriate client type and handle redirect
  11406. if (need_ssl) {
  11407. #ifdef CPPHTTPLIB_SSL_ENABLED
  11408. // Create SSL client for HTTPS redirect
  11409. SSLClient redirect_client(host, port);
  11410. // Setup basic client configuration first
  11411. setup_redirect_client(redirect_client);
  11412. redirect_client.enable_server_certificate_verification(
  11413. server_certificate_verification_);
  11414. redirect_client.enable_server_hostname_verification(
  11415. server_hostname_verification_);
  11416. redirect_client.system_ca_mode_ = system_ca_mode_;
  11417. // Transfer CA certificate to redirect client
  11418. if (!ca_cert_pem_.empty()) {
  11419. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11420. ca_cert_pem_.size());
  11421. }
  11422. if (!ca_cert_file_path_.empty()) {
  11423. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11424. }
  11425. // Client certificates are set through constructor for SSLClient
  11426. // NOTE: SSLClient constructor already takes client_cert_path and
  11427. // client_key_path so we need to create it properly if client certs are
  11428. // needed
  11429. // Execute the redirect
  11430. return detail::redirect(redirect_client, req, res, path, location, error);
  11431. #else
  11432. // SSL not supported - set appropriate error
  11433. error = Error::SSLConnection;
  11434. output_error_log(error, &req);
  11435. return false;
  11436. #endif
  11437. } else {
  11438. // HTTP redirect
  11439. ClientImpl redirect_client(host, port);
  11440. // Setup client with robust configuration
  11441. setup_redirect_client(redirect_client);
  11442. // Execute the redirect
  11443. return detail::redirect(redirect_client, req, res, path, location, error);
  11444. }
  11445. }
  11446. // New method for robust client setup (based on basic_manual_redirect.cpp
  11447. // logic)
  11448. template <typename ClientType>
  11449. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11450. // Copy basic settings first
  11451. client.set_connection_timeout(connection_timeout_sec_);
  11452. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11453. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11454. client.set_keep_alive(keep_alive_);
  11455. client.set_follow_location(
  11456. true); // Enable redirects to handle multi-step redirects
  11457. client.set_path_encode(path_encode_);
  11458. client.set_compress(compress_);
  11459. client.set_decompress(decompress_);
  11460. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11461. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11462. // 15.4, credentials must not be forwarded when redirecting to a different
  11463. // host. This function is only called for cross-host redirects; same-host
  11464. // redirects are handled directly in ClientImpl::redirect().
  11465. // Copy the proxy configuration unconditionally; the per-target bypass is
  11466. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11467. // still use the proxy.
  11468. client.no_proxy_entries_ = no_proxy_entries_;
  11469. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11470. client.set_proxy(proxy_host_, proxy_port_);
  11471. if (!proxy_basic_auth_username_.empty()) {
  11472. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11473. proxy_basic_auth_password_);
  11474. }
  11475. if (!proxy_bearer_token_auth_token_.empty()) {
  11476. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11477. }
  11478. #ifdef CPPHTTPLIB_SSL_ENABLED
  11479. if (!proxy_digest_auth_username_.empty()) {
  11480. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11481. proxy_digest_auth_password_);
  11482. }
  11483. #endif
  11484. }
  11485. // Copy network and socket settings
  11486. client.set_address_family(address_family_);
  11487. client.set_tcp_nodelay(tcp_nodelay_);
  11488. client.set_ipv6_v6only(ipv6_v6only_);
  11489. if (socket_options_) { client.set_socket_options(socket_options_); }
  11490. if (!interface_.empty()) { client.set_interface(interface_); }
  11491. // Copy logging and headers
  11492. if (logger_) { client.set_logger(logger_); }
  11493. if (error_logger_) { client.set_error_logger(error_logger_); }
  11494. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11495. // Each new client should generate its own headers based on its target host
  11496. }
  11497. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11498. const Request &req,
  11499. Error &error) const {
  11500. auto is_shutting_down = []() { return false; };
  11501. if (req.is_chunked_content_provider_) {
  11502. auto compressor = compress_ ? detail::create_compressor().first
  11503. : std::unique_ptr<detail::compressor>();
  11504. if (!compressor) {
  11505. compressor = detail::make_unique<detail::nocompressor>();
  11506. }
  11507. return detail::write_content_chunked(strm, req.content_provider_,
  11508. is_shutting_down, *compressor, error);
  11509. } else {
  11510. return detail::write_content_with_progress(
  11511. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11512. req.upload_progress, error);
  11513. }
  11514. }
  11515. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11516. bool close_connection, Error &error,
  11517. bool skip_body) {
  11518. // Prepare additional headers
  11519. if (close_connection) {
  11520. if (!req.has_header("Connection")) {
  11521. req.set_header("Connection", "close");
  11522. }
  11523. }
  11524. std::string ct_for_defaults;
  11525. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11526. ct_for_defaults = "text/plain";
  11527. }
  11528. prepare_default_headers(req, false, ct_for_defaults);
  11529. if (req.body.empty()) {
  11530. if (req.content_provider_) {
  11531. if (!req.is_chunked_content_provider_) {
  11532. if (!req.has_header("Content-Length")) {
  11533. auto length = std::to_string(req.content_length_);
  11534. req.set_header("Content-Length", length);
  11535. }
  11536. }
  11537. } else {
  11538. if (req.method == "POST" || req.method == "PUT" ||
  11539. req.method == "PATCH") {
  11540. req.set_header("Content-Length", "0");
  11541. }
  11542. }
  11543. }
  11544. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11545. if (!req.has_header("Authorization")) {
  11546. req.headers.insert(make_basic_authentication_header(
  11547. basic_auth_username_, basic_auth_password_, false));
  11548. }
  11549. }
  11550. if (!bearer_token_auth_token_.empty()) {
  11551. if (!req.has_header("Authorization")) {
  11552. req.headers.insert(make_bearer_token_authentication_header(
  11553. bearer_token_auth_token_, false));
  11554. }
  11555. }
  11556. // Proxy-Authorization is only sent when the proxy is actually used for
  11557. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11558. // credentials directly to the destination server.
  11559. if (is_proxy_enabled_for_host(host_)) {
  11560. if (!proxy_basic_auth_username_.empty() &&
  11561. !proxy_basic_auth_password_.empty() &&
  11562. !req.has_header("Proxy-Authorization")) {
  11563. req.headers.insert(make_basic_authentication_header(
  11564. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11565. }
  11566. if (!proxy_bearer_token_auth_token_.empty() &&
  11567. !req.has_header("Proxy-Authorization")) {
  11568. req.headers.insert(make_bearer_token_authentication_header(
  11569. proxy_bearer_token_auth_token_, true));
  11570. }
  11571. }
  11572. // Request line and headers
  11573. {
  11574. detail::BufferStream bstrm;
  11575. // Extract path and query from req.path
  11576. std::string path_part, query_part;
  11577. auto query_pos = req.path.find('?');
  11578. if (query_pos != std::string::npos) {
  11579. path_part = req.path.substr(0, query_pos);
  11580. query_part = req.path.substr(query_pos + 1);
  11581. } else {
  11582. path_part = req.path;
  11583. query_part = "";
  11584. }
  11585. // Encode path part. If the original `req.path` already contained a
  11586. // query component, preserve its raw query string (including parameter
  11587. // order) instead of reparsing and reassembling it which may reorder
  11588. // parameters due to container ordering (e.g. `Params` uses
  11589. // `std::multimap`). When there is no query in `req.path`, fall back to
  11590. // building a query from `req.params` so existing callers that pass
  11591. // `Params` continue to work.
  11592. auto path_with_query =
  11593. path_encode_ ? detail::encode_path(path_part) : path_part;
  11594. if (!query_part.empty()) {
  11595. // Normalize the query string (decode then re-encode) while preserving
  11596. // the original parameter order. When path encoding is disabled the
  11597. // caller has supplied an already-encoded target and expects the exact
  11598. // bytes to be sent on the wire, so skip normalization for the query
  11599. // too. Normalizing here would decode-then-re-encode the query and
  11600. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11601. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11602. if (path_encode_) {
  11603. auto normalized = detail::normalize_query_string(query_part);
  11604. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11605. } else {
  11606. path_with_query += '?' + query_part;
  11607. }
  11608. // Still populate req.params for handlers/users who read them.
  11609. detail::parse_query_text(query_part, req.params);
  11610. } else {
  11611. // No query in path; parse any query_part (empty) and append params
  11612. // from `req.params` when present (preserves prior behavior for
  11613. // callers who provide Params separately).
  11614. detail::parse_query_text(query_part, req.params);
  11615. if (!req.params.empty()) {
  11616. path_with_query = append_query_params(path_with_query, req.params);
  11617. }
  11618. }
  11619. // Write request line and headers
  11620. detail::write_request_line(bstrm, req.method, path_with_query);
  11621. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11622. error)) {
  11623. output_error_log(error, &req);
  11624. return false;
  11625. }
  11626. // Flush buffer
  11627. auto &data = bstrm.get_buffer();
  11628. if (!detail::write_data(strm, data.data(), data.size())) {
  11629. error = Error::Write;
  11630. output_error_log(error, &req);
  11631. return false;
  11632. }
  11633. }
  11634. // After sending request line and headers, wait briefly for an early server
  11635. // response (e.g. 4xx) and avoid sending a potentially large request body
  11636. // unnecessarily. This workaround is only enabled on Windows because Unix
  11637. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11638. // buffering can accept large writes even when the peer already responded.
  11639. // Check the stream first (which covers SSL via `is_readable()`), then
  11640. // fall back to select on the socket. Only perform the wait for very large
  11641. // request bodies to avoid interfering with normal small requests and
  11642. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11643. // response. Skip this check when using Expect: 100-continue, as the protocol
  11644. // handles early responses properly.
  11645. #if defined(_WIN32)
  11646. if (!skip_body &&
  11647. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11648. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11649. auto start = std::chrono::high_resolution_clock::now();
  11650. for (;;) {
  11651. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11652. // from SSL internals. If the underlying socket is readable, assume an
  11653. // early response may be present.
  11654. auto sock = strm.socket();
  11655. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11656. return false;
  11657. }
  11658. // Fallback to stream-level check for non-socket streams or when the
  11659. // socket isn't reporting readable. Avoid using `is_readable()` for
  11660. // SSL, since `SSL_pending()` may report buffered records that do not
  11661. // indicate a complete application-level response yet.
  11662. if (!is_ssl() && strm.is_readable()) { return false; }
  11663. auto now = std::chrono::high_resolution_clock::now();
  11664. auto elapsed =
  11665. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11666. .count();
  11667. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11668. break;
  11669. }
  11670. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11671. }
  11672. }
  11673. #endif
  11674. // Body
  11675. if (skip_body) { return true; }
  11676. return write_request_body(strm, req, error);
  11677. }
  11678. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11679. Error &error) {
  11680. if (req.body.empty()) {
  11681. return write_content_with_provider(strm, req, error);
  11682. }
  11683. if (req.upload_progress) {
  11684. auto body_size = req.body.size();
  11685. size_t written = 0;
  11686. auto data = req.body.data();
  11687. while (written < body_size) {
  11688. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11689. if (!detail::write_data(strm, data + written, to_write)) {
  11690. error = Error::Write;
  11691. output_error_log(error, &req);
  11692. return false;
  11693. }
  11694. written += to_write;
  11695. if (!req.upload_progress(written, body_size)) {
  11696. error = Error::Canceled;
  11697. output_error_log(error, &req);
  11698. return false;
  11699. }
  11700. }
  11701. } else {
  11702. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11703. error = Error::Write;
  11704. output_error_log(error, &req);
  11705. return false;
  11706. }
  11707. }
  11708. return true;
  11709. }
  11710. inline std::unique_ptr<Response>
  11711. ClientImpl::send_with_content_provider_and_receiver(
  11712. Request &req, const char *body, size_t content_length,
  11713. ContentProvider content_provider,
  11714. ContentProviderWithoutLength content_provider_without_length,
  11715. const std::string &content_type, ContentReceiver content_receiver,
  11716. Error &error) {
  11717. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11718. auto enc = compress_
  11719. ? detail::create_compressor()
  11720. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11721. nullptr, nullptr);
  11722. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11723. if (enc.first && !content_provider_without_length) {
  11724. auto &compressor = enc.first;
  11725. if (content_provider) {
  11726. auto ok = true;
  11727. size_t offset = 0;
  11728. DataSink data_sink;
  11729. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11730. if (ok) {
  11731. auto last = offset + data_len == content_length;
  11732. auto ret = compressor->compress(
  11733. data, data_len, last,
  11734. [&](const char *compressed_data, size_t compressed_data_len) {
  11735. req.body.append(compressed_data, compressed_data_len);
  11736. return true;
  11737. });
  11738. if (ret) {
  11739. offset += data_len;
  11740. } else {
  11741. ok = false;
  11742. }
  11743. }
  11744. return ok;
  11745. };
  11746. while (ok && offset < content_length) {
  11747. if (!content_provider(offset, content_length - offset, data_sink)) {
  11748. error = Error::Canceled;
  11749. output_error_log(error, &req);
  11750. return nullptr;
  11751. }
  11752. }
  11753. } else {
  11754. if (!compressor->compress(body, content_length, true,
  11755. [&](const char *data, size_t data_len) {
  11756. req.body.append(data, data_len);
  11757. return true;
  11758. })) {
  11759. error = Error::Compression;
  11760. output_error_log(error, &req);
  11761. return nullptr;
  11762. }
  11763. }
  11764. } else {
  11765. if (content_provider) {
  11766. req.content_length_ = content_length;
  11767. req.content_provider_ = std::move(content_provider);
  11768. req.is_chunked_content_provider_ = false;
  11769. } else if (content_provider_without_length) {
  11770. req.content_length_ = 0;
  11771. req.content_provider_ = detail::ContentProviderAdapter(
  11772. std::move(content_provider_without_length));
  11773. req.is_chunked_content_provider_ = true;
  11774. req.set_header("Transfer-Encoding", "chunked");
  11775. } else {
  11776. req.body.assign(body, content_length);
  11777. }
  11778. }
  11779. if (content_receiver) {
  11780. req.content_receiver =
  11781. [content_receiver](const char *data, size_t data_length,
  11782. size_t /*offset*/, size_t /*total_length*/) {
  11783. return content_receiver(data, data_length);
  11784. };
  11785. }
  11786. auto res = detail::make_unique<Response>();
  11787. return send(req, *res, error) ? std::move(res) : nullptr;
  11788. }
  11789. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11790. const std::string &method, const std::string &path, const Headers &headers,
  11791. const char *body, size_t content_length, ContentProvider content_provider,
  11792. ContentProviderWithoutLength content_provider_without_length,
  11793. const std::string &content_type, ContentReceiver content_receiver,
  11794. UploadProgress progress) {
  11795. Request req;
  11796. req.method = method;
  11797. req.headers = headers;
  11798. req.path = path;
  11799. req.upload_progress = std::move(progress);
  11800. if (max_timeout_msec_ > 0) {
  11801. req.start_time_ = std::chrono::steady_clock::now();
  11802. }
  11803. auto error = Error::Success;
  11804. auto res = send_with_content_provider_and_receiver(
  11805. req, body, content_length, std::move(content_provider),
  11806. std::move(content_provider_without_length), content_type,
  11807. std::move(content_receiver), error);
  11808. #ifdef CPPHTTPLIB_SSL_ENABLED
  11809. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11810. last_backend_error_};
  11811. #else
  11812. return Result{std::move(res), error, std::move(req.headers)};
  11813. #endif
  11814. }
  11815. inline void ClientImpl::output_log(const Request &req,
  11816. const Response &res) const {
  11817. if (logger_) {
  11818. std::lock_guard<std::mutex> guard(logger_mutex_);
  11819. logger_(req, res);
  11820. }
  11821. }
  11822. inline void ClientImpl::output_error_log(const Error &err,
  11823. const Request *req) const {
  11824. if (error_logger_) {
  11825. std::lock_guard<std::mutex> guard(logger_mutex_);
  11826. error_logger_(err, req);
  11827. }
  11828. }
  11829. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11830. Response &res, bool close_connection,
  11831. Error &error) {
  11832. // Auto-add Expect: 100-continue for large bodies
  11833. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11834. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11835. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11836. req.set_header("Expect", "100-continue");
  11837. }
  11838. }
  11839. // Check for Expect: 100-continue
  11840. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11841. // Send request (skip body if using Expect: 100-continue)
  11842. auto write_request_success =
  11843. write_request(strm, req, close_connection, error, expect_100_continue);
  11844. #ifdef CPPHTTPLIB_SSL_ENABLED
  11845. if (is_ssl() && !expect_100_continue) {
  11846. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11847. if (!is_proxy_enabled) {
  11848. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11849. error = Error::SSLPeerCouldBeClosed_;
  11850. output_error_log(error, &req);
  11851. return false;
  11852. }
  11853. }
  11854. }
  11855. #endif
  11856. // Handle Expect: 100-continue.
  11857. //
  11858. // Wait for an interim/early response by attempting to read the status line
  11859. // under a short timeout, instead of trusting raw socket readability. Over
  11860. // TLS, post-handshake records (e.g. session tickets) make the socket
  11861. // readable without any HTTP response being available; relying on
  11862. // `select_read` there caused the body to be withheld forever and the
  11863. // request to fail with `Read` (#2458). If no status line arrives within the
  11864. // timeout, send the body anyway (matching curl's behavior).
  11865. auto status_line_read = false;
  11866. if (expect_100_continue && write_request_success) {
  11867. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11868. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11869. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11870. strm.set_read_timeout(sec, usec);
  11871. status_line_read = read_response_line(strm, req, res, false);
  11872. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11873. }
  11874. if (!status_line_read) {
  11875. // No interim response within the timeout: send the body and handle the
  11876. // response as usual.
  11877. if (!write_request_body(strm, req, error)) { return false; }
  11878. expect_100_continue = false; // Switch to normal response handling
  11879. }
  11880. }
  11881. // Receive response and headers
  11882. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11883. if ((!status_line_read &&
  11884. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11885. !detail::read_headers(strm, res.headers)) {
  11886. if (write_request_success) { error = Error::Read; }
  11887. output_error_log(error, &req);
  11888. return false;
  11889. }
  11890. if (!write_request_success) { return false; }
  11891. // Handle Expect: 100-continue response
  11892. if (expect_100_continue) {
  11893. if (res.status == StatusCode::Continue_100) {
  11894. // Server accepted, send the body
  11895. if (!write_request_body(strm, req, error)) { return false; }
  11896. // Read the actual response
  11897. res.headers.clear();
  11898. res.body.clear();
  11899. if (!read_response_line(strm, req, res) ||
  11900. !detail::read_headers(strm, res.headers)) {
  11901. error = Error::Read;
  11902. output_error_log(error, &req);
  11903. return false;
  11904. }
  11905. }
  11906. // If not 100 Continue, server returned an error; proceed with that response
  11907. }
  11908. // Body
  11909. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11910. req.method != "CONNECT") {
  11911. auto redirect = 300 < res.status && res.status < 400 &&
  11912. res.status != StatusCode::NotModified_304 &&
  11913. follow_location_;
  11914. if (req.response_handler && !redirect) {
  11915. if (!req.response_handler(res)) {
  11916. error = Error::Canceled;
  11917. output_error_log(error, &req);
  11918. return false;
  11919. }
  11920. }
  11921. auto out =
  11922. req.content_receiver
  11923. ? static_cast<ContentReceiverWithProgress>(
  11924. [&](const char *buf, size_t n, size_t off, size_t len) {
  11925. if (redirect) { return true; }
  11926. auto ret = req.content_receiver(buf, n, off, len);
  11927. if (!ret) {
  11928. error = Error::Canceled;
  11929. output_error_log(error, &req);
  11930. }
  11931. return ret;
  11932. })
  11933. : static_cast<ContentReceiverWithProgress>(
  11934. [&](const char *buf, size_t n, size_t /*off*/,
  11935. size_t /*len*/) {
  11936. assert(res.body.size() + n <= res.body.max_size());
  11937. if (payload_max_length_ > 0 &&
  11938. (res.body.size() >= payload_max_length_ ||
  11939. n > payload_max_length_ - res.body.size())) {
  11940. return false;
  11941. }
  11942. res.body.append(buf, n);
  11943. return true;
  11944. });
  11945. auto progress = [&](size_t current, size_t total) {
  11946. if (!req.download_progress || redirect) { return true; }
  11947. auto ret = req.download_progress(current, total);
  11948. if (!ret) {
  11949. error = Error::Canceled;
  11950. output_error_log(error, &req);
  11951. }
  11952. return ret;
  11953. };
  11954. if (res.has_header("Content-Length")) {
  11955. if (!req.content_receiver) {
  11956. auto len = res.get_header_value_u64("Content-Length");
  11957. if (len > res.body.max_size()) {
  11958. error = Error::Read;
  11959. output_error_log(error, &req);
  11960. return false;
  11961. }
  11962. // Cap the reservation by payload_max_length_ to avoid OOM when a
  11963. // hostile or malformed server sends an enormous Content-Length.
  11964. // The actual body read below is bounded by payload_max_length_,
  11965. // so reserving more than that is never useful.
  11966. auto reserve_len = static_cast<size_t>(len);
  11967. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  11968. reserve_len = payload_max_length_;
  11969. }
  11970. res.body.reserve(reserve_len);
  11971. }
  11972. }
  11973. if (res.status != StatusCode::NotModified_304) {
  11974. int dummy_status;
  11975. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11976. ? (std::numeric_limits<size_t>::max)()
  11977. : payload_max_length_;
  11978. if (!detail::read_content(strm, res, max_length, dummy_status,
  11979. std::move(progress), std::move(out),
  11980. decompress_)) {
  11981. if (error != Error::Canceled) { error = Error::Read; }
  11982. output_error_log(error, &req);
  11983. return false;
  11984. }
  11985. }
  11986. }
  11987. // Log
  11988. output_log(req, res);
  11989. return true;
  11990. }
  11991. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11992. const std::string &boundary, const UploadFormDataItems &items,
  11993. const FormDataProviderItems &provider_items) const {
  11994. size_t cur_item = 0;
  11995. size_t cur_start = 0;
  11996. // cur_item and cur_start are copied to within the std::function and
  11997. // maintain state between successive calls
  11998. return [&, cur_item, cur_start](size_t offset,
  11999. DataSink &sink) mutable -> bool {
  12000. if (!offset && !items.empty()) {
  12001. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12002. return true;
  12003. } else if (cur_item < provider_items.size()) {
  12004. if (!cur_start) {
  12005. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12006. provider_items[cur_item], boundary);
  12007. offset += begin.size();
  12008. cur_start = offset;
  12009. sink.os << begin;
  12010. }
  12011. DataSink cur_sink;
  12012. auto has_data = true;
  12013. cur_sink.write = sink.write;
  12014. cur_sink.done = [&]() { has_data = false; };
  12015. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12016. return false;
  12017. }
  12018. if (!has_data) {
  12019. sink.os << detail::serialize_multipart_formdata_item_end();
  12020. cur_item++;
  12021. cur_start = 0;
  12022. }
  12023. return true;
  12024. } else {
  12025. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12026. sink.done();
  12027. return true;
  12028. }
  12029. };
  12030. }
  12031. inline bool ClientImpl::process_socket(
  12032. const Socket &socket,
  12033. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12034. std::function<bool(Stream &strm)> callback) {
  12035. return detail::process_client_socket(
  12036. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12037. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12038. }
  12039. inline bool ClientImpl::is_ssl() const { return false; }
  12040. inline Result ClientImpl::Get(const std::string &path,
  12041. DownloadProgress progress) {
  12042. return Get(path, Headers(), std::move(progress));
  12043. }
  12044. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12045. const Headers &headers,
  12046. DownloadProgress progress) {
  12047. if (params.empty()) { return Get(path, headers); }
  12048. std::string path_with_query = append_query_params(path, params);
  12049. return Get(path_with_query, headers, std::move(progress));
  12050. }
  12051. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12052. DownloadProgress progress) {
  12053. Request req;
  12054. req.method = "GET";
  12055. req.path = path;
  12056. req.headers = headers;
  12057. req.download_progress = std::move(progress);
  12058. if (max_timeout_msec_ > 0) {
  12059. req.start_time_ = std::chrono::steady_clock::now();
  12060. }
  12061. return send_(std::move(req));
  12062. }
  12063. inline Result ClientImpl::Get(const std::string &path,
  12064. ContentReceiver content_receiver,
  12065. DownloadProgress progress) {
  12066. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12067. std::move(progress));
  12068. }
  12069. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12070. ContentReceiver content_receiver,
  12071. DownloadProgress progress) {
  12072. return Get(path, headers, nullptr, std::move(content_receiver),
  12073. std::move(progress));
  12074. }
  12075. inline Result ClientImpl::Get(const std::string &path,
  12076. ResponseHandler response_handler,
  12077. ContentReceiver content_receiver,
  12078. DownloadProgress progress) {
  12079. return Get(path, Headers(), std::move(response_handler),
  12080. std::move(content_receiver), std::move(progress));
  12081. }
  12082. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12083. ResponseHandler response_handler,
  12084. ContentReceiver content_receiver,
  12085. DownloadProgress progress) {
  12086. Request req;
  12087. req.method = "GET";
  12088. req.path = path;
  12089. req.headers = headers;
  12090. req.response_handler = std::move(response_handler);
  12091. req.content_receiver =
  12092. [content_receiver](const char *data, size_t data_length,
  12093. size_t /*offset*/, size_t /*total_length*/) {
  12094. return content_receiver(data, data_length);
  12095. };
  12096. req.download_progress = std::move(progress);
  12097. if (max_timeout_msec_ > 0) {
  12098. req.start_time_ = std::chrono::steady_clock::now();
  12099. }
  12100. return send_(std::move(req));
  12101. }
  12102. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12103. const Headers &headers,
  12104. ContentReceiver content_receiver,
  12105. DownloadProgress progress) {
  12106. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12107. std::move(progress));
  12108. }
  12109. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12110. const Headers &headers,
  12111. ResponseHandler response_handler,
  12112. ContentReceiver content_receiver,
  12113. DownloadProgress progress) {
  12114. if (params.empty()) {
  12115. return Get(path, headers, std::move(response_handler),
  12116. std::move(content_receiver), std::move(progress));
  12117. }
  12118. std::string path_with_query = append_query_params(path, params);
  12119. return Get(path_with_query, headers, std::move(response_handler),
  12120. std::move(content_receiver), std::move(progress));
  12121. }
  12122. inline Result ClientImpl::Head(const std::string &path) {
  12123. return Head(path, Headers());
  12124. }
  12125. inline Result ClientImpl::Head(const std::string &path,
  12126. const Headers &headers) {
  12127. Request req;
  12128. req.method = "HEAD";
  12129. req.headers = headers;
  12130. req.path = path;
  12131. if (max_timeout_msec_ > 0) {
  12132. req.start_time_ = std::chrono::steady_clock::now();
  12133. }
  12134. return send_(std::move(req));
  12135. }
  12136. inline Result ClientImpl::Post(const std::string &path) {
  12137. return Post(path, std::string(), std::string());
  12138. }
  12139. inline Result ClientImpl::Post(const std::string &path,
  12140. const Headers &headers) {
  12141. return Post(path, headers, nullptr, 0, std::string());
  12142. }
  12143. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12144. size_t content_length,
  12145. const std::string &content_type,
  12146. UploadProgress progress) {
  12147. return Post(path, Headers(), body, content_length, content_type, progress);
  12148. }
  12149. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12150. const std::string &content_type,
  12151. UploadProgress progress) {
  12152. return Post(path, Headers(), body, content_type, progress);
  12153. }
  12154. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12155. return Post(path, Headers(), params);
  12156. }
  12157. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12158. ContentProvider content_provider,
  12159. const std::string &content_type,
  12160. UploadProgress progress) {
  12161. return Post(path, Headers(), content_length, std::move(content_provider),
  12162. content_type, progress);
  12163. }
  12164. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12165. ContentProvider content_provider,
  12166. const std::string &content_type,
  12167. ContentReceiver content_receiver,
  12168. UploadProgress progress) {
  12169. return Post(path, Headers(), content_length, std::move(content_provider),
  12170. content_type, std::move(content_receiver), progress);
  12171. }
  12172. inline Result ClientImpl::Post(const std::string &path,
  12173. ContentProviderWithoutLength content_provider,
  12174. const std::string &content_type,
  12175. UploadProgress progress) {
  12176. return Post(path, Headers(), std::move(content_provider), content_type,
  12177. progress);
  12178. }
  12179. inline Result ClientImpl::Post(const std::string &path,
  12180. ContentProviderWithoutLength content_provider,
  12181. const std::string &content_type,
  12182. ContentReceiver content_receiver,
  12183. UploadProgress progress) {
  12184. return Post(path, Headers(), std::move(content_provider), content_type,
  12185. std::move(content_receiver), progress);
  12186. }
  12187. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12188. const Params &params) {
  12189. auto query = detail::params_to_query_str(params);
  12190. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12191. }
  12192. inline Result ClientImpl::Post(const std::string &path,
  12193. const UploadFormDataItems &items,
  12194. UploadProgress progress) {
  12195. return Post(path, Headers(), items, progress);
  12196. }
  12197. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12198. const UploadFormDataItems &items,
  12199. UploadProgress progress) {
  12200. const auto &boundary = detail::make_multipart_data_boundary();
  12201. const auto &content_type =
  12202. detail::serialize_multipart_formdata_get_content_type(boundary);
  12203. auto content_length = detail::get_multipart_content_length(items, boundary);
  12204. return Post(path, headers, content_length,
  12205. detail::make_multipart_content_provider(items, boundary),
  12206. content_type, progress);
  12207. }
  12208. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12209. const UploadFormDataItems &items,
  12210. const std::string &boundary,
  12211. UploadProgress progress) {
  12212. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12213. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12214. }
  12215. const auto &content_type =
  12216. detail::serialize_multipart_formdata_get_content_type(boundary);
  12217. auto content_length = detail::get_multipart_content_length(items, boundary);
  12218. return Post(path, headers, content_length,
  12219. detail::make_multipart_content_provider(items, boundary),
  12220. content_type, progress);
  12221. }
  12222. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12223. const char *body, size_t content_length,
  12224. const std::string &content_type,
  12225. UploadProgress progress) {
  12226. return send_with_content_provider_and_receiver(
  12227. "POST", path, headers, body, content_length, nullptr, nullptr,
  12228. content_type, nullptr, progress);
  12229. }
  12230. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12231. const std::string &body,
  12232. const std::string &content_type,
  12233. UploadProgress progress) {
  12234. return send_with_content_provider_and_receiver(
  12235. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12236. content_type, nullptr, progress);
  12237. }
  12238. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12239. size_t content_length,
  12240. ContentProvider content_provider,
  12241. const std::string &content_type,
  12242. UploadProgress progress) {
  12243. return send_with_content_provider_and_receiver(
  12244. "POST", path, headers, nullptr, content_length,
  12245. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12246. }
  12247. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12248. size_t content_length,
  12249. ContentProvider content_provider,
  12250. const std::string &content_type,
  12251. ContentReceiver content_receiver,
  12252. DownloadProgress progress) {
  12253. return send_with_content_provider_and_receiver(
  12254. "POST", path, headers, nullptr, content_length,
  12255. std::move(content_provider), nullptr, content_type,
  12256. std::move(content_receiver), std::move(progress));
  12257. }
  12258. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12259. ContentProviderWithoutLength content_provider,
  12260. const std::string &content_type,
  12261. UploadProgress progress) {
  12262. return send_with_content_provider_and_receiver(
  12263. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12264. content_type, nullptr, progress);
  12265. }
  12266. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12267. ContentProviderWithoutLength content_provider,
  12268. const std::string &content_type,
  12269. ContentReceiver content_receiver,
  12270. DownloadProgress progress) {
  12271. return send_with_content_provider_and_receiver(
  12272. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12273. content_type, std::move(content_receiver), std::move(progress));
  12274. }
  12275. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12276. const UploadFormDataItems &items,
  12277. const FormDataProviderItems &provider_items,
  12278. UploadProgress progress) {
  12279. const auto &boundary = detail::make_multipart_data_boundary();
  12280. const auto &content_type =
  12281. detail::serialize_multipart_formdata_get_content_type(boundary);
  12282. return send_with_content_provider_and_receiver(
  12283. "POST", path, headers, nullptr, 0, nullptr,
  12284. get_multipart_content_provider(boundary, items, provider_items),
  12285. content_type, nullptr, progress);
  12286. }
  12287. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12288. const std::string &body,
  12289. const std::string &content_type,
  12290. ContentReceiver content_receiver,
  12291. DownloadProgress progress) {
  12292. Request req;
  12293. req.method = "POST";
  12294. req.path = path;
  12295. req.headers = headers;
  12296. req.body = body;
  12297. req.content_receiver =
  12298. [content_receiver](const char *data, size_t data_length,
  12299. size_t /*offset*/, size_t /*total_length*/) {
  12300. return content_receiver(data, data_length);
  12301. };
  12302. req.download_progress = std::move(progress);
  12303. if (max_timeout_msec_ > 0) {
  12304. req.start_time_ = std::chrono::steady_clock::now();
  12305. }
  12306. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12307. return send_(std::move(req));
  12308. }
  12309. inline Result ClientImpl::Put(const std::string &path) {
  12310. return Put(path, std::string(), std::string());
  12311. }
  12312. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12313. return Put(path, headers, nullptr, 0, std::string());
  12314. }
  12315. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12316. size_t content_length,
  12317. const std::string &content_type,
  12318. UploadProgress progress) {
  12319. return Put(path, Headers(), body, content_length, content_type, progress);
  12320. }
  12321. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12322. const std::string &content_type,
  12323. UploadProgress progress) {
  12324. return Put(path, Headers(), body, content_type, progress);
  12325. }
  12326. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12327. return Put(path, Headers(), params);
  12328. }
  12329. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12330. ContentProvider content_provider,
  12331. const std::string &content_type,
  12332. UploadProgress progress) {
  12333. return Put(path, Headers(), content_length, std::move(content_provider),
  12334. content_type, progress);
  12335. }
  12336. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12337. ContentProvider content_provider,
  12338. const std::string &content_type,
  12339. ContentReceiver content_receiver,
  12340. UploadProgress progress) {
  12341. return Put(path, Headers(), content_length, std::move(content_provider),
  12342. content_type, std::move(content_receiver), progress);
  12343. }
  12344. inline Result ClientImpl::Put(const std::string &path,
  12345. ContentProviderWithoutLength content_provider,
  12346. const std::string &content_type,
  12347. UploadProgress progress) {
  12348. return Put(path, Headers(), std::move(content_provider), content_type,
  12349. progress);
  12350. }
  12351. inline Result ClientImpl::Put(const std::string &path,
  12352. ContentProviderWithoutLength content_provider,
  12353. const std::string &content_type,
  12354. ContentReceiver content_receiver,
  12355. UploadProgress progress) {
  12356. return Put(path, Headers(), std::move(content_provider), content_type,
  12357. std::move(content_receiver), progress);
  12358. }
  12359. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12360. const Params &params) {
  12361. auto query = detail::params_to_query_str(params);
  12362. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12363. }
  12364. inline Result ClientImpl::Put(const std::string &path,
  12365. const UploadFormDataItems &items,
  12366. UploadProgress progress) {
  12367. return Put(path, Headers(), items, progress);
  12368. }
  12369. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12370. const UploadFormDataItems &items,
  12371. UploadProgress progress) {
  12372. const auto &boundary = detail::make_multipart_data_boundary();
  12373. const auto &content_type =
  12374. detail::serialize_multipart_formdata_get_content_type(boundary);
  12375. auto content_length = detail::get_multipart_content_length(items, boundary);
  12376. return Put(path, headers, content_length,
  12377. detail::make_multipart_content_provider(items, boundary),
  12378. content_type, progress);
  12379. }
  12380. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12381. const UploadFormDataItems &items,
  12382. const std::string &boundary,
  12383. UploadProgress progress) {
  12384. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12385. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12386. }
  12387. const auto &content_type =
  12388. detail::serialize_multipart_formdata_get_content_type(boundary);
  12389. auto content_length = detail::get_multipart_content_length(items, boundary);
  12390. return Put(path, headers, content_length,
  12391. detail::make_multipart_content_provider(items, boundary),
  12392. content_type, progress);
  12393. }
  12394. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12395. const char *body, size_t content_length,
  12396. const std::string &content_type,
  12397. UploadProgress progress) {
  12398. return send_with_content_provider_and_receiver(
  12399. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12400. content_type, nullptr, progress);
  12401. }
  12402. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12403. const std::string &body,
  12404. const std::string &content_type,
  12405. UploadProgress progress) {
  12406. return send_with_content_provider_and_receiver(
  12407. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12408. content_type, nullptr, progress);
  12409. }
  12410. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12411. size_t content_length,
  12412. ContentProvider content_provider,
  12413. const std::string &content_type,
  12414. UploadProgress progress) {
  12415. return send_with_content_provider_and_receiver(
  12416. "PUT", path, headers, nullptr, content_length,
  12417. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12418. }
  12419. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12420. size_t content_length,
  12421. ContentProvider content_provider,
  12422. const std::string &content_type,
  12423. ContentReceiver content_receiver,
  12424. UploadProgress progress) {
  12425. return send_with_content_provider_and_receiver(
  12426. "PUT", path, headers, nullptr, content_length,
  12427. std::move(content_provider), nullptr, content_type,
  12428. std::move(content_receiver), progress);
  12429. }
  12430. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12431. ContentProviderWithoutLength content_provider,
  12432. const std::string &content_type,
  12433. UploadProgress progress) {
  12434. return send_with_content_provider_and_receiver(
  12435. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12436. content_type, nullptr, progress);
  12437. }
  12438. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12439. ContentProviderWithoutLength content_provider,
  12440. const std::string &content_type,
  12441. ContentReceiver content_receiver,
  12442. UploadProgress progress) {
  12443. return send_with_content_provider_and_receiver(
  12444. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12445. content_type, std::move(content_receiver), progress);
  12446. }
  12447. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12448. const UploadFormDataItems &items,
  12449. const FormDataProviderItems &provider_items,
  12450. UploadProgress progress) {
  12451. const auto &boundary = detail::make_multipart_data_boundary();
  12452. const auto &content_type =
  12453. detail::serialize_multipart_formdata_get_content_type(boundary);
  12454. return send_with_content_provider_and_receiver(
  12455. "PUT", path, headers, nullptr, 0, nullptr,
  12456. get_multipart_content_provider(boundary, items, provider_items),
  12457. content_type, nullptr, progress);
  12458. }
  12459. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12460. const std::string &body,
  12461. const std::string &content_type,
  12462. ContentReceiver content_receiver,
  12463. DownloadProgress progress) {
  12464. Request req;
  12465. req.method = "PUT";
  12466. req.path = path;
  12467. req.headers = headers;
  12468. req.body = body;
  12469. req.content_receiver =
  12470. [content_receiver](const char *data, size_t data_length,
  12471. size_t /*offset*/, size_t /*total_length*/) {
  12472. return content_receiver(data, data_length);
  12473. };
  12474. req.download_progress = std::move(progress);
  12475. if (max_timeout_msec_ > 0) {
  12476. req.start_time_ = std::chrono::steady_clock::now();
  12477. }
  12478. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12479. return send_(std::move(req));
  12480. }
  12481. inline Result ClientImpl::Patch(const std::string &path) {
  12482. return Patch(path, std::string(), std::string());
  12483. }
  12484. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12485. UploadProgress progress) {
  12486. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12487. }
  12488. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12489. size_t content_length,
  12490. const std::string &content_type,
  12491. UploadProgress progress) {
  12492. return Patch(path, Headers(), body, content_length, content_type, progress);
  12493. }
  12494. inline Result ClientImpl::Patch(const std::string &path,
  12495. const std::string &body,
  12496. const std::string &content_type,
  12497. UploadProgress progress) {
  12498. return Patch(path, Headers(), body, content_type, progress);
  12499. }
  12500. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12501. return Patch(path, Headers(), params);
  12502. }
  12503. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12504. ContentProvider content_provider,
  12505. const std::string &content_type,
  12506. UploadProgress progress) {
  12507. return Patch(path, Headers(), content_length, std::move(content_provider),
  12508. content_type, progress);
  12509. }
  12510. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12511. ContentProvider content_provider,
  12512. const std::string &content_type,
  12513. ContentReceiver content_receiver,
  12514. UploadProgress progress) {
  12515. return Patch(path, Headers(), content_length, std::move(content_provider),
  12516. content_type, std::move(content_receiver), progress);
  12517. }
  12518. inline Result ClientImpl::Patch(const std::string &path,
  12519. ContentProviderWithoutLength content_provider,
  12520. const std::string &content_type,
  12521. UploadProgress progress) {
  12522. return Patch(path, Headers(), std::move(content_provider), content_type,
  12523. progress);
  12524. }
  12525. inline Result ClientImpl::Patch(const std::string &path,
  12526. ContentProviderWithoutLength content_provider,
  12527. const std::string &content_type,
  12528. ContentReceiver content_receiver,
  12529. UploadProgress progress) {
  12530. return Patch(path, Headers(), std::move(content_provider), content_type,
  12531. std::move(content_receiver), progress);
  12532. }
  12533. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12534. const Params &params) {
  12535. auto query = detail::params_to_query_str(params);
  12536. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12537. }
  12538. inline Result ClientImpl::Patch(const std::string &path,
  12539. const UploadFormDataItems &items,
  12540. UploadProgress progress) {
  12541. return Patch(path, Headers(), items, progress);
  12542. }
  12543. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12544. const UploadFormDataItems &items,
  12545. UploadProgress progress) {
  12546. const auto &boundary = detail::make_multipart_data_boundary();
  12547. const auto &content_type =
  12548. detail::serialize_multipart_formdata_get_content_type(boundary);
  12549. auto content_length = detail::get_multipart_content_length(items, boundary);
  12550. return Patch(path, headers, content_length,
  12551. detail::make_multipart_content_provider(items, boundary),
  12552. content_type, progress);
  12553. }
  12554. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12555. const UploadFormDataItems &items,
  12556. const std::string &boundary,
  12557. UploadProgress progress) {
  12558. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12559. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12560. }
  12561. const auto &content_type =
  12562. detail::serialize_multipart_formdata_get_content_type(boundary);
  12563. auto content_length = detail::get_multipart_content_length(items, boundary);
  12564. return Patch(path, headers, content_length,
  12565. detail::make_multipart_content_provider(items, boundary),
  12566. content_type, progress);
  12567. }
  12568. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12569. const char *body, size_t content_length,
  12570. const std::string &content_type,
  12571. UploadProgress progress) {
  12572. return send_with_content_provider_and_receiver(
  12573. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12574. content_type, nullptr, progress);
  12575. }
  12576. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12577. const std::string &body,
  12578. const std::string &content_type,
  12579. UploadProgress progress) {
  12580. return send_with_content_provider_and_receiver(
  12581. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12582. content_type, nullptr, progress);
  12583. }
  12584. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12585. size_t content_length,
  12586. ContentProvider content_provider,
  12587. const std::string &content_type,
  12588. UploadProgress progress) {
  12589. return send_with_content_provider_and_receiver(
  12590. "PATCH", path, headers, nullptr, content_length,
  12591. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12592. }
  12593. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12594. size_t content_length,
  12595. ContentProvider content_provider,
  12596. const std::string &content_type,
  12597. ContentReceiver content_receiver,
  12598. UploadProgress progress) {
  12599. return send_with_content_provider_and_receiver(
  12600. "PATCH", path, headers, nullptr, content_length,
  12601. std::move(content_provider), nullptr, content_type,
  12602. std::move(content_receiver), progress);
  12603. }
  12604. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12605. ContentProviderWithoutLength content_provider,
  12606. const std::string &content_type,
  12607. UploadProgress progress) {
  12608. return send_with_content_provider_and_receiver(
  12609. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12610. content_type, nullptr, progress);
  12611. }
  12612. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12613. ContentProviderWithoutLength content_provider,
  12614. const std::string &content_type,
  12615. ContentReceiver content_receiver,
  12616. UploadProgress progress) {
  12617. return send_with_content_provider_and_receiver(
  12618. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12619. content_type, std::move(content_receiver), progress);
  12620. }
  12621. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12622. const UploadFormDataItems &items,
  12623. const FormDataProviderItems &provider_items,
  12624. UploadProgress progress) {
  12625. const auto &boundary = detail::make_multipart_data_boundary();
  12626. const auto &content_type =
  12627. detail::serialize_multipart_formdata_get_content_type(boundary);
  12628. return send_with_content_provider_and_receiver(
  12629. "PATCH", path, headers, nullptr, 0, nullptr,
  12630. get_multipart_content_provider(boundary, items, provider_items),
  12631. content_type, nullptr, progress);
  12632. }
  12633. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12634. const std::string &body,
  12635. const std::string &content_type,
  12636. ContentReceiver content_receiver,
  12637. DownloadProgress progress) {
  12638. Request req;
  12639. req.method = "PATCH";
  12640. req.path = path;
  12641. req.headers = headers;
  12642. req.body = body;
  12643. req.content_receiver =
  12644. [content_receiver](const char *data, size_t data_length,
  12645. size_t /*offset*/, size_t /*total_length*/) {
  12646. return content_receiver(data, data_length);
  12647. };
  12648. req.download_progress = std::move(progress);
  12649. if (max_timeout_msec_ > 0) {
  12650. req.start_time_ = std::chrono::steady_clock::now();
  12651. }
  12652. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12653. return send_(std::move(req));
  12654. }
  12655. inline Result ClientImpl::Delete(const std::string &path,
  12656. DownloadProgress progress) {
  12657. return Delete(path, Headers(), std::string(), std::string(), progress);
  12658. }
  12659. inline Result ClientImpl::Delete(const std::string &path,
  12660. const Headers &headers,
  12661. DownloadProgress progress) {
  12662. return Delete(path, headers, std::string(), std::string(), progress);
  12663. }
  12664. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12665. size_t content_length,
  12666. const std::string &content_type,
  12667. DownloadProgress progress) {
  12668. return Delete(path, Headers(), body, content_length, content_type, progress);
  12669. }
  12670. inline Result ClientImpl::Delete(const std::string &path,
  12671. const std::string &body,
  12672. const std::string &content_type,
  12673. DownloadProgress progress) {
  12674. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12675. progress);
  12676. }
  12677. inline Result ClientImpl::Delete(const std::string &path,
  12678. const Headers &headers,
  12679. const std::string &body,
  12680. const std::string &content_type,
  12681. DownloadProgress progress) {
  12682. return Delete(path, headers, body.data(), body.size(), content_type,
  12683. progress);
  12684. }
  12685. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12686. DownloadProgress progress) {
  12687. return Delete(path, Headers(), params, progress);
  12688. }
  12689. inline Result ClientImpl::Delete(const std::string &path,
  12690. const Headers &headers, const Params &params,
  12691. DownloadProgress progress) {
  12692. auto query = detail::params_to_query_str(params);
  12693. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12694. progress);
  12695. }
  12696. inline Result ClientImpl::Delete(const std::string &path,
  12697. const Headers &headers, const char *body,
  12698. size_t content_length,
  12699. const std::string &content_type,
  12700. DownloadProgress progress) {
  12701. Request req;
  12702. req.method = "DELETE";
  12703. req.headers = headers;
  12704. req.path = path;
  12705. req.download_progress = std::move(progress);
  12706. if (max_timeout_msec_ > 0) {
  12707. req.start_time_ = std::chrono::steady_clock::now();
  12708. }
  12709. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12710. req.body.assign(body, content_length);
  12711. return send_(std::move(req));
  12712. }
  12713. inline Result ClientImpl::Options(const std::string &path) {
  12714. return Options(path, Headers());
  12715. }
  12716. inline Result ClientImpl::Options(const std::string &path,
  12717. const Headers &headers) {
  12718. Request req;
  12719. req.method = "OPTIONS";
  12720. req.headers = headers;
  12721. req.path = path;
  12722. if (max_timeout_msec_ > 0) {
  12723. req.start_time_ = std::chrono::steady_clock::now();
  12724. }
  12725. return send_(std::move(req));
  12726. }
  12727. inline void ClientImpl::stop() {
  12728. std::lock_guard<std::mutex> guard(socket_mutex_);
  12729. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12730. // do is to shutdown_socket, so that threads using this socket suddenly
  12731. // discover they can't read/write any more and error out. Everything else
  12732. // (closing the socket, shutting ssl down) is unsafe because these actions
  12733. // are not thread-safe.
  12734. if (socket_requests_in_flight_ > 0) {
  12735. shutdown_socket(socket_);
  12736. // Aside from that, we set a flag for the socket to be closed when we're
  12737. // done.
  12738. socket_should_be_closed_when_request_is_done_ = true;
  12739. return;
  12740. }
  12741. disconnect(/*gracefully=*/true);
  12742. }
  12743. inline std::string ClientImpl::host() const { return host_; }
  12744. inline int ClientImpl::port() const { return port_; }
  12745. inline size_t ClientImpl::is_socket_open() const {
  12746. std::lock_guard<std::mutex> guard(socket_mutex_);
  12747. return socket_.is_open();
  12748. }
  12749. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12750. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12751. connection_timeout_sec_ = sec;
  12752. connection_timeout_usec_ = usec;
  12753. }
  12754. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12755. read_timeout_sec_ = sec;
  12756. read_timeout_usec_ = usec;
  12757. }
  12758. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12759. write_timeout_sec_ = sec;
  12760. write_timeout_usec_ = usec;
  12761. }
  12762. inline void ClientImpl::set_max_timeout(time_t msec) {
  12763. max_timeout_msec_ = msec;
  12764. }
  12765. inline void ClientImpl::set_basic_auth(const std::string &username,
  12766. const std::string &password) {
  12767. basic_auth_username_ = username;
  12768. basic_auth_password_ = password;
  12769. }
  12770. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12771. bearer_token_auth_token_ = token;
  12772. }
  12773. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12774. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12775. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12776. inline void
  12777. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12778. addr_map_ = std::move(addr_map);
  12779. }
  12780. inline void ClientImpl::set_default_headers(Headers headers) {
  12781. default_headers_ = std::move(headers);
  12782. }
  12783. inline void ClientImpl::set_header_writer(
  12784. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12785. header_writer_ = writer;
  12786. }
  12787. inline void ClientImpl::set_address_family(int family) {
  12788. address_family_ = family;
  12789. }
  12790. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12791. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12792. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12793. socket_options_ = std::move(socket_options);
  12794. }
  12795. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12796. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12797. inline void ClientImpl::set_payload_max_length(size_t length) {
  12798. payload_max_length_ = length;
  12799. has_payload_max_length_ = true;
  12800. }
  12801. inline void ClientImpl::set_interface(const std::string &intf) {
  12802. interface_ = intf;
  12803. }
  12804. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12805. proxy_host_ = host;
  12806. proxy_port_ = port;
  12807. std::lock_guard<std::mutex> guard(socket_mutex_);
  12808. disconnect(/*gracefully=*/true);
  12809. }
  12810. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12811. const std::string &password) {
  12812. proxy_basic_auth_username_ = username;
  12813. proxy_basic_auth_password_ = password;
  12814. }
  12815. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12816. proxy_bearer_token_auth_token_ = token;
  12817. }
  12818. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12819. std::vector<detail::NoProxyEntry> parsed;
  12820. parsed.reserve(patterns.size());
  12821. for (const auto &p : patterns) {
  12822. auto trimmed = detail::trim_copy(p);
  12823. if (trimmed.empty()) { continue; }
  12824. detail::NoProxyEntry entry;
  12825. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12826. parsed.push_back(std::move(entry));
  12827. }
  12828. }
  12829. no_proxy_entries_ = std::move(parsed);
  12830. std::lock_guard<std::mutex> guard(socket_mutex_);
  12831. disconnect(/*gracefully=*/true);
  12832. }
  12833. #ifdef CPPHTTPLIB_SSL_ENABLED
  12834. inline void ClientImpl::set_digest_auth(const std::string &username,
  12835. const std::string &password) {
  12836. digest_auth_username_ = username;
  12837. digest_auth_password_ = password;
  12838. }
  12839. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12840. const std::string &ca_cert_dir_path) {
  12841. ca_cert_file_path_ = ca_cert_file_path;
  12842. ca_cert_dir_path_ = ca_cert_dir_path;
  12843. }
  12844. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12845. const std::string &password) {
  12846. proxy_digest_auth_username_ = username;
  12847. proxy_digest_auth_password_ = password;
  12848. }
  12849. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12850. server_certificate_verification_ = enabled;
  12851. }
  12852. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12853. server_hostname_verification_ = enabled;
  12854. }
  12855. inline void ClientImpl::enable_system_ca(bool enabled) {
  12856. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12857. }
  12858. #endif
  12859. inline void ClientImpl::set_logger(Logger logger) {
  12860. logger_ = std::move(logger);
  12861. }
  12862. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12863. error_logger_ = std::move(error_logger);
  12864. }
  12865. /*
  12866. * SSL/TLS Common Implementation
  12867. */
  12868. inline ClientConnection::~ClientConnection() {
  12869. #ifdef CPPHTTPLIB_SSL_ENABLED
  12870. if (session) {
  12871. tls::shutdown(session, true);
  12872. tls::free_session(session);
  12873. session = nullptr;
  12874. }
  12875. #endif
  12876. if (sock != INVALID_SOCKET) {
  12877. detail::close_socket(sock);
  12878. sock = INVALID_SOCKET;
  12879. }
  12880. }
  12881. // Universal client implementation
  12882. inline Client::Client(const std::string &scheme_host_port)
  12883. : Client(scheme_host_port, std::string(), std::string()) {}
  12884. inline Client::Client(const std::string &scheme_host_port,
  12885. const std::string &client_cert_path,
  12886. const std::string &client_key_path) {
  12887. detail::UrlComponents uc;
  12888. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12889. auto &scheme = uc.scheme;
  12890. #ifdef CPPHTTPLIB_SSL_ENABLED
  12891. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12892. #else
  12893. if (!scheme.empty() && scheme != "http") {
  12894. #endif
  12895. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12896. std::string msg = "'" + scheme + "' scheme is not supported.";
  12897. throw std::invalid_argument(msg);
  12898. #endif
  12899. return;
  12900. }
  12901. auto is_ssl = scheme == "https";
  12902. auto host = std::move(uc.host);
  12903. auto port = is_ssl ? 443 : 80;
  12904. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12905. if (is_ssl) {
  12906. #ifdef CPPHTTPLIB_SSL_ENABLED
  12907. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12908. client_key_path);
  12909. is_ssl_ = is_ssl;
  12910. #endif
  12911. } else {
  12912. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12913. client_key_path);
  12914. }
  12915. } else {
  12916. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12917. // if port param below changes.
  12918. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12919. client_cert_path, client_key_path);
  12920. }
  12921. }
  12922. inline Client::Client(const std::string &host, int port)
  12923. : Client(host, port, std::string(), std::string()) {}
  12924. inline Client::Client(const std::string &host, int port,
  12925. const std::string &client_cert_path,
  12926. const std::string &client_key_path)
  12927. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12928. client_key_path)) {}
  12929. inline Client::~Client() = default;
  12930. inline bool Client::is_valid() const {
  12931. return cli_ != nullptr && cli_->is_valid();
  12932. }
  12933. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12934. return cli_->Get(path, std::move(progress));
  12935. }
  12936. inline Result Client::Get(const std::string &path, const Headers &headers,
  12937. DownloadProgress progress) {
  12938. return cli_->Get(path, headers, std::move(progress));
  12939. }
  12940. inline Result Client::Get(const std::string &path,
  12941. ContentReceiver content_receiver,
  12942. DownloadProgress progress) {
  12943. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12944. }
  12945. inline Result Client::Get(const std::string &path, const Headers &headers,
  12946. ContentReceiver content_receiver,
  12947. DownloadProgress progress) {
  12948. return cli_->Get(path, headers, std::move(content_receiver),
  12949. std::move(progress));
  12950. }
  12951. inline Result Client::Get(const std::string &path,
  12952. ResponseHandler response_handler,
  12953. ContentReceiver content_receiver,
  12954. DownloadProgress progress) {
  12955. return cli_->Get(path, std::move(response_handler),
  12956. std::move(content_receiver), std::move(progress));
  12957. }
  12958. inline Result Client::Get(const std::string &path, const Headers &headers,
  12959. ResponseHandler response_handler,
  12960. ContentReceiver content_receiver,
  12961. DownloadProgress progress) {
  12962. return cli_->Get(path, headers, std::move(response_handler),
  12963. std::move(content_receiver), std::move(progress));
  12964. }
  12965. inline Result Client::Get(const std::string &path, const Params &params,
  12966. const Headers &headers, DownloadProgress progress) {
  12967. return cli_->Get(path, params, headers, std::move(progress));
  12968. }
  12969. inline Result Client::Get(const std::string &path, const Params &params,
  12970. const Headers &headers,
  12971. ContentReceiver content_receiver,
  12972. DownloadProgress progress) {
  12973. return cli_->Get(path, params, headers, std::move(content_receiver),
  12974. std::move(progress));
  12975. }
  12976. inline Result Client::Get(const std::string &path, const Params &params,
  12977. const Headers &headers,
  12978. ResponseHandler response_handler,
  12979. ContentReceiver content_receiver,
  12980. DownloadProgress progress) {
  12981. return cli_->Get(path, params, headers, std::move(response_handler),
  12982. std::move(content_receiver), std::move(progress));
  12983. }
  12984. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12985. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12986. return cli_->Head(path, headers);
  12987. }
  12988. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12989. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12990. return cli_->Post(path, headers);
  12991. }
  12992. inline Result Client::Post(const std::string &path, const char *body,
  12993. size_t content_length,
  12994. const std::string &content_type,
  12995. UploadProgress progress) {
  12996. return cli_->Post(path, body, content_length, content_type, progress);
  12997. }
  12998. inline Result Client::Post(const std::string &path, const Headers &headers,
  12999. const char *body, size_t content_length,
  13000. const std::string &content_type,
  13001. UploadProgress progress) {
  13002. return cli_->Post(path, headers, body, content_length, content_type,
  13003. progress);
  13004. }
  13005. inline Result Client::Post(const std::string &path, const std::string &body,
  13006. const std::string &content_type,
  13007. UploadProgress progress) {
  13008. return cli_->Post(path, body, content_type, progress);
  13009. }
  13010. inline Result Client::Post(const std::string &path, const Headers &headers,
  13011. const std::string &body,
  13012. const std::string &content_type,
  13013. UploadProgress progress) {
  13014. return cli_->Post(path, headers, body, content_type, progress);
  13015. }
  13016. inline Result Client::Post(const std::string &path, size_t content_length,
  13017. ContentProvider content_provider,
  13018. const std::string &content_type,
  13019. UploadProgress progress) {
  13020. return cli_->Post(path, content_length, std::move(content_provider),
  13021. content_type, progress);
  13022. }
  13023. inline Result Client::Post(const std::string &path, size_t content_length,
  13024. ContentProvider content_provider,
  13025. const std::string &content_type,
  13026. ContentReceiver content_receiver,
  13027. UploadProgress progress) {
  13028. return cli_->Post(path, content_length, std::move(content_provider),
  13029. content_type, std::move(content_receiver), progress);
  13030. }
  13031. inline Result Client::Post(const std::string &path,
  13032. ContentProviderWithoutLength content_provider,
  13033. const std::string &content_type,
  13034. UploadProgress progress) {
  13035. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13036. }
  13037. inline Result Client::Post(const std::string &path,
  13038. ContentProviderWithoutLength content_provider,
  13039. const std::string &content_type,
  13040. ContentReceiver content_receiver,
  13041. UploadProgress progress) {
  13042. return cli_->Post(path, std::move(content_provider), content_type,
  13043. std::move(content_receiver), progress);
  13044. }
  13045. inline Result Client::Post(const std::string &path, const Headers &headers,
  13046. size_t content_length,
  13047. ContentProvider content_provider,
  13048. const std::string &content_type,
  13049. UploadProgress progress) {
  13050. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13051. content_type, progress);
  13052. }
  13053. inline Result Client::Post(const std::string &path, const Headers &headers,
  13054. size_t content_length,
  13055. ContentProvider content_provider,
  13056. const std::string &content_type,
  13057. ContentReceiver content_receiver,
  13058. DownloadProgress progress) {
  13059. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13060. content_type, std::move(content_receiver), progress);
  13061. }
  13062. inline Result Client::Post(const std::string &path, const Headers &headers,
  13063. ContentProviderWithoutLength content_provider,
  13064. const std::string &content_type,
  13065. UploadProgress progress) {
  13066. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13067. progress);
  13068. }
  13069. inline Result Client::Post(const std::string &path, const Headers &headers,
  13070. ContentProviderWithoutLength content_provider,
  13071. const std::string &content_type,
  13072. ContentReceiver content_receiver,
  13073. DownloadProgress progress) {
  13074. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13075. std::move(content_receiver), progress);
  13076. }
  13077. inline Result Client::Post(const std::string &path, const Params &params) {
  13078. return cli_->Post(path, params);
  13079. }
  13080. inline Result Client::Post(const std::string &path, const Headers &headers,
  13081. const Params &params) {
  13082. return cli_->Post(path, headers, params);
  13083. }
  13084. inline Result Client::Post(const std::string &path,
  13085. const UploadFormDataItems &items,
  13086. UploadProgress progress) {
  13087. return cli_->Post(path, items, progress);
  13088. }
  13089. inline Result Client::Post(const std::string &path, const Headers &headers,
  13090. const UploadFormDataItems &items,
  13091. UploadProgress progress) {
  13092. return cli_->Post(path, headers, items, progress);
  13093. }
  13094. inline Result Client::Post(const std::string &path, const Headers &headers,
  13095. const UploadFormDataItems &items,
  13096. const std::string &boundary,
  13097. UploadProgress progress) {
  13098. return cli_->Post(path, headers, items, boundary, progress);
  13099. }
  13100. inline Result Client::Post(const std::string &path, const Headers &headers,
  13101. const UploadFormDataItems &items,
  13102. const FormDataProviderItems &provider_items,
  13103. UploadProgress progress) {
  13104. return cli_->Post(path, headers, items, provider_items, progress);
  13105. }
  13106. inline Result Client::Post(const std::string &path, const Headers &headers,
  13107. const std::string &body,
  13108. const std::string &content_type,
  13109. ContentReceiver content_receiver,
  13110. DownloadProgress progress) {
  13111. return cli_->Post(path, headers, body, content_type,
  13112. std::move(content_receiver), progress);
  13113. }
  13114. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13115. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13116. return cli_->Put(path, headers);
  13117. }
  13118. inline Result Client::Put(const std::string &path, const char *body,
  13119. size_t content_length,
  13120. const std::string &content_type,
  13121. UploadProgress progress) {
  13122. return cli_->Put(path, body, content_length, content_type, progress);
  13123. }
  13124. inline Result Client::Put(const std::string &path, const Headers &headers,
  13125. const char *body, size_t content_length,
  13126. const std::string &content_type,
  13127. UploadProgress progress) {
  13128. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13129. }
  13130. inline Result Client::Put(const std::string &path, const std::string &body,
  13131. const std::string &content_type,
  13132. UploadProgress progress) {
  13133. return cli_->Put(path, body, content_type, progress);
  13134. }
  13135. inline Result Client::Put(const std::string &path, const Headers &headers,
  13136. const std::string &body,
  13137. const std::string &content_type,
  13138. UploadProgress progress) {
  13139. return cli_->Put(path, headers, body, content_type, progress);
  13140. }
  13141. inline Result Client::Put(const std::string &path, size_t content_length,
  13142. ContentProvider content_provider,
  13143. const std::string &content_type,
  13144. UploadProgress progress) {
  13145. return cli_->Put(path, content_length, std::move(content_provider),
  13146. content_type, progress);
  13147. }
  13148. inline Result Client::Put(const std::string &path, size_t content_length,
  13149. ContentProvider content_provider,
  13150. const std::string &content_type,
  13151. ContentReceiver content_receiver,
  13152. UploadProgress progress) {
  13153. return cli_->Put(path, content_length, std::move(content_provider),
  13154. content_type, std::move(content_receiver), progress);
  13155. }
  13156. inline Result Client::Put(const std::string &path,
  13157. ContentProviderWithoutLength content_provider,
  13158. const std::string &content_type,
  13159. UploadProgress progress) {
  13160. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13161. }
  13162. inline Result Client::Put(const std::string &path,
  13163. ContentProviderWithoutLength content_provider,
  13164. const std::string &content_type,
  13165. ContentReceiver content_receiver,
  13166. UploadProgress progress) {
  13167. return cli_->Put(path, std::move(content_provider), content_type,
  13168. std::move(content_receiver), progress);
  13169. }
  13170. inline Result Client::Put(const std::string &path, const Headers &headers,
  13171. size_t content_length,
  13172. ContentProvider content_provider,
  13173. const std::string &content_type,
  13174. UploadProgress progress) {
  13175. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13176. content_type, progress);
  13177. }
  13178. inline Result Client::Put(const std::string &path, const Headers &headers,
  13179. size_t content_length,
  13180. ContentProvider content_provider,
  13181. const std::string &content_type,
  13182. ContentReceiver content_receiver,
  13183. UploadProgress progress) {
  13184. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13185. content_type, std::move(content_receiver), progress);
  13186. }
  13187. inline Result Client::Put(const std::string &path, const Headers &headers,
  13188. ContentProviderWithoutLength content_provider,
  13189. const std::string &content_type,
  13190. UploadProgress progress) {
  13191. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13192. progress);
  13193. }
  13194. inline Result Client::Put(const std::string &path, const Headers &headers,
  13195. ContentProviderWithoutLength content_provider,
  13196. const std::string &content_type,
  13197. ContentReceiver content_receiver,
  13198. UploadProgress progress) {
  13199. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13200. std::move(content_receiver), progress);
  13201. }
  13202. inline Result Client::Put(const std::string &path, const Params &params) {
  13203. return cli_->Put(path, params);
  13204. }
  13205. inline Result Client::Put(const std::string &path, const Headers &headers,
  13206. const Params &params) {
  13207. return cli_->Put(path, headers, params);
  13208. }
  13209. inline Result Client::Put(const std::string &path,
  13210. const UploadFormDataItems &items,
  13211. UploadProgress progress) {
  13212. return cli_->Put(path, items, progress);
  13213. }
  13214. inline Result Client::Put(const std::string &path, const Headers &headers,
  13215. const UploadFormDataItems &items,
  13216. UploadProgress progress) {
  13217. return cli_->Put(path, headers, items, progress);
  13218. }
  13219. inline Result Client::Put(const std::string &path, const Headers &headers,
  13220. const UploadFormDataItems &items,
  13221. const std::string &boundary,
  13222. UploadProgress progress) {
  13223. return cli_->Put(path, headers, items, boundary, progress);
  13224. }
  13225. inline Result Client::Put(const std::string &path, const Headers &headers,
  13226. const UploadFormDataItems &items,
  13227. const FormDataProviderItems &provider_items,
  13228. UploadProgress progress) {
  13229. return cli_->Put(path, headers, items, provider_items, progress);
  13230. }
  13231. inline Result Client::Put(const std::string &path, const Headers &headers,
  13232. const std::string &body,
  13233. const std::string &content_type,
  13234. ContentReceiver content_receiver,
  13235. DownloadProgress progress) {
  13236. return cli_->Put(path, headers, body, content_type, content_receiver,
  13237. progress);
  13238. }
  13239. inline Result Client::Patch(const std::string &path) {
  13240. return cli_->Patch(path);
  13241. }
  13242. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13243. return cli_->Patch(path, headers);
  13244. }
  13245. inline Result Client::Patch(const std::string &path, const char *body,
  13246. size_t content_length,
  13247. const std::string &content_type,
  13248. UploadProgress progress) {
  13249. return cli_->Patch(path, body, content_length, content_type, progress);
  13250. }
  13251. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13252. const char *body, size_t content_length,
  13253. const std::string &content_type,
  13254. UploadProgress progress) {
  13255. return cli_->Patch(path, headers, body, content_length, content_type,
  13256. progress);
  13257. }
  13258. inline Result Client::Patch(const std::string &path, const std::string &body,
  13259. const std::string &content_type,
  13260. UploadProgress progress) {
  13261. return cli_->Patch(path, body, content_type, progress);
  13262. }
  13263. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13264. const std::string &body,
  13265. const std::string &content_type,
  13266. UploadProgress progress) {
  13267. return cli_->Patch(path, headers, body, content_type, progress);
  13268. }
  13269. inline Result Client::Patch(const std::string &path, size_t content_length,
  13270. ContentProvider content_provider,
  13271. const std::string &content_type,
  13272. UploadProgress progress) {
  13273. return cli_->Patch(path, content_length, std::move(content_provider),
  13274. content_type, progress);
  13275. }
  13276. inline Result Client::Patch(const std::string &path, size_t content_length,
  13277. ContentProvider content_provider,
  13278. const std::string &content_type,
  13279. ContentReceiver content_receiver,
  13280. UploadProgress progress) {
  13281. return cli_->Patch(path, content_length, std::move(content_provider),
  13282. content_type, std::move(content_receiver), progress);
  13283. }
  13284. inline Result Client::Patch(const std::string &path,
  13285. ContentProviderWithoutLength content_provider,
  13286. const std::string &content_type,
  13287. UploadProgress progress) {
  13288. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13289. }
  13290. inline Result Client::Patch(const std::string &path,
  13291. ContentProviderWithoutLength content_provider,
  13292. const std::string &content_type,
  13293. ContentReceiver content_receiver,
  13294. UploadProgress progress) {
  13295. return cli_->Patch(path, std::move(content_provider), content_type,
  13296. std::move(content_receiver), progress);
  13297. }
  13298. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13299. size_t content_length,
  13300. ContentProvider content_provider,
  13301. const std::string &content_type,
  13302. UploadProgress progress) {
  13303. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13304. content_type, progress);
  13305. }
  13306. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13307. size_t content_length,
  13308. ContentProvider content_provider,
  13309. const std::string &content_type,
  13310. ContentReceiver content_receiver,
  13311. UploadProgress progress) {
  13312. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13313. content_type, std::move(content_receiver), progress);
  13314. }
  13315. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13316. ContentProviderWithoutLength content_provider,
  13317. const std::string &content_type,
  13318. UploadProgress progress) {
  13319. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13320. progress);
  13321. }
  13322. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13323. ContentProviderWithoutLength content_provider,
  13324. const std::string &content_type,
  13325. ContentReceiver content_receiver,
  13326. UploadProgress progress) {
  13327. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13328. std::move(content_receiver), progress);
  13329. }
  13330. inline Result Client::Patch(const std::string &path, const Params &params) {
  13331. return cli_->Patch(path, params);
  13332. }
  13333. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13334. const Params &params) {
  13335. return cli_->Patch(path, headers, params);
  13336. }
  13337. inline Result Client::Patch(const std::string &path,
  13338. const UploadFormDataItems &items,
  13339. UploadProgress progress) {
  13340. return cli_->Patch(path, items, progress);
  13341. }
  13342. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13343. const UploadFormDataItems &items,
  13344. UploadProgress progress) {
  13345. return cli_->Patch(path, headers, items, progress);
  13346. }
  13347. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13348. const UploadFormDataItems &items,
  13349. const std::string &boundary,
  13350. UploadProgress progress) {
  13351. return cli_->Patch(path, headers, items, boundary, progress);
  13352. }
  13353. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13354. const UploadFormDataItems &items,
  13355. const FormDataProviderItems &provider_items,
  13356. UploadProgress progress) {
  13357. return cli_->Patch(path, headers, items, provider_items, progress);
  13358. }
  13359. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13360. const std::string &body,
  13361. const std::string &content_type,
  13362. ContentReceiver content_receiver,
  13363. DownloadProgress progress) {
  13364. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13365. progress);
  13366. }
  13367. inline Result Client::Delete(const std::string &path,
  13368. DownloadProgress progress) {
  13369. return cli_->Delete(path, progress);
  13370. }
  13371. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13372. DownloadProgress progress) {
  13373. return cli_->Delete(path, headers, progress);
  13374. }
  13375. inline Result Client::Delete(const std::string &path, const char *body,
  13376. size_t content_length,
  13377. const std::string &content_type,
  13378. DownloadProgress progress) {
  13379. return cli_->Delete(path, body, content_length, content_type, progress);
  13380. }
  13381. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13382. const char *body, size_t content_length,
  13383. const std::string &content_type,
  13384. DownloadProgress progress) {
  13385. return cli_->Delete(path, headers, body, content_length, content_type,
  13386. progress);
  13387. }
  13388. inline Result Client::Delete(const std::string &path, const std::string &body,
  13389. const std::string &content_type,
  13390. DownloadProgress progress) {
  13391. return cli_->Delete(path, body, content_type, progress);
  13392. }
  13393. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13394. const std::string &body,
  13395. const std::string &content_type,
  13396. DownloadProgress progress) {
  13397. return cli_->Delete(path, headers, body, content_type, progress);
  13398. }
  13399. inline Result Client::Delete(const std::string &path, const Params &params,
  13400. DownloadProgress progress) {
  13401. return cli_->Delete(path, params, progress);
  13402. }
  13403. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13404. const Params &params, DownloadProgress progress) {
  13405. return cli_->Delete(path, headers, params, progress);
  13406. }
  13407. inline Result Client::Options(const std::string &path) {
  13408. return cli_->Options(path);
  13409. }
  13410. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13411. return cli_->Options(path, headers);
  13412. }
  13413. inline ClientImpl::StreamHandle
  13414. Client::open_stream(const std::string &method, const std::string &path,
  13415. const Params &params, const Headers &headers,
  13416. const std::string &body, const std::string &content_type) {
  13417. return cli_->open_stream(method, path, params, headers, body, content_type);
  13418. }
  13419. inline bool Client::send(Request &req, Response &res, Error &error) {
  13420. return cli_->send(req, res, error);
  13421. }
  13422. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13423. inline void Client::stop() { cli_->stop(); }
  13424. inline std::string Client::host() const { return cli_->host(); }
  13425. inline int Client::port() const { return cli_->port(); }
  13426. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13427. inline socket_t Client::socket() const { return cli_->socket(); }
  13428. inline void
  13429. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13430. cli_->set_hostname_addr_map(std::move(addr_map));
  13431. }
  13432. inline void Client::set_default_headers(Headers headers) {
  13433. cli_->set_default_headers(std::move(headers));
  13434. }
  13435. inline void Client::set_header_writer(
  13436. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13437. cli_->set_header_writer(writer);
  13438. }
  13439. inline void Client::set_address_family(int family) {
  13440. cli_->set_address_family(family);
  13441. }
  13442. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13443. inline void Client::set_socket_options(SocketOptions socket_options) {
  13444. cli_->set_socket_options(std::move(socket_options));
  13445. }
  13446. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13447. cli_->set_connection_timeout(sec, usec);
  13448. }
  13449. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13450. cli_->set_read_timeout(sec, usec);
  13451. }
  13452. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13453. cli_->set_write_timeout(sec, usec);
  13454. }
  13455. inline void Client::set_basic_auth(const std::string &username,
  13456. const std::string &password) {
  13457. cli_->set_basic_auth(username, password);
  13458. }
  13459. inline void Client::set_bearer_token_auth(const std::string &token) {
  13460. cli_->set_bearer_token_auth(token);
  13461. }
  13462. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13463. inline void Client::set_follow_location(bool on) {
  13464. cli_->set_follow_location(on);
  13465. }
  13466. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13467. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13468. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13469. inline void Client::set_payload_max_length(size_t length) {
  13470. cli_->set_payload_max_length(length);
  13471. }
  13472. inline void Client::set_interface(const std::string &intf) {
  13473. cli_->set_interface(intf);
  13474. }
  13475. inline void Client::set_proxy(const std::string &host, int port) {
  13476. cli_->set_proxy(host, port);
  13477. }
  13478. inline void Client::set_proxy_basic_auth(const std::string &username,
  13479. const std::string &password) {
  13480. cli_->set_proxy_basic_auth(username, password);
  13481. }
  13482. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13483. cli_->set_proxy_bearer_token_auth(token);
  13484. }
  13485. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13486. cli_->set_no_proxy(patterns);
  13487. }
  13488. inline void Client::set_logger(Logger logger) {
  13489. cli_->set_logger(std::move(logger));
  13490. }
  13491. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13492. cli_->set_error_logger(std::move(error_logger));
  13493. }
  13494. /*
  13495. * Group 6: SSL Server and Client implementation
  13496. */
  13497. #ifdef CPPHTTPLIB_SSL_ENABLED
  13498. // SSL HTTP server implementation
  13499. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13500. const char *client_ca_cert_file_path,
  13501. const char *client_ca_cert_dir_path,
  13502. const char *private_key_password) {
  13503. using namespace tls;
  13504. ctx_ = create_server_context();
  13505. if (!ctx_) { return; }
  13506. // Load server certificate and private key
  13507. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13508. private_key_password)) {
  13509. last_ssl_error_ = static_cast<int>(get_error());
  13510. free_context(ctx_);
  13511. ctx_ = nullptr;
  13512. return;
  13513. }
  13514. // Load client CA certificates for client authentication
  13515. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13516. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13517. client_ca_cert_dir_path)) {
  13518. last_ssl_error_ = static_cast<int>(get_error());
  13519. free_context(ctx_);
  13520. ctx_ = nullptr;
  13521. return;
  13522. }
  13523. // Enable client certificate verification
  13524. set_verify_client(ctx_, true);
  13525. }
  13526. }
  13527. inline SSLServer::SSLServer(const PemMemory &pem) {
  13528. using namespace tls;
  13529. ctx_ = create_server_context();
  13530. if (ctx_) {
  13531. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13532. pem.private_key_password)) {
  13533. last_ssl_error_ = static_cast<int>(get_error());
  13534. free_context(ctx_);
  13535. ctx_ = nullptr;
  13536. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13537. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13538. last_ssl_error_ = static_cast<int>(get_error());
  13539. free_context(ctx_);
  13540. ctx_ = nullptr;
  13541. } else {
  13542. set_verify_client(ctx_, true);
  13543. }
  13544. }
  13545. }
  13546. }
  13547. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13548. using namespace tls;
  13549. ctx_ = create_server_context();
  13550. if (ctx_) {
  13551. if (!setup_callback(ctx_)) {
  13552. free_context(ctx_);
  13553. ctx_ = nullptr;
  13554. }
  13555. }
  13556. }
  13557. inline SSLServer::~SSLServer() {
  13558. if (ctx_) { tls::free_context(ctx_); }
  13559. }
  13560. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13561. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13562. using namespace tls;
  13563. // Create TLS session with mutex protection
  13564. session_t session = nullptr;
  13565. {
  13566. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13567. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13568. }
  13569. if (!session) {
  13570. last_ssl_error_ = static_cast<int>(get_error());
  13571. detail::shutdown_socket(sock);
  13572. detail::close_socket(sock);
  13573. return false;
  13574. }
  13575. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13576. bool handshake_done = false;
  13577. bool ret = false;
  13578. bool websocket_upgraded = false;
  13579. auto cleanup = detail::scope_exit([&] {
  13580. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13581. free_session(session);
  13582. detail::shutdown_socket(sock);
  13583. detail::close_socket(sock);
  13584. });
  13585. // Perform TLS accept handshake with timeout
  13586. TlsError tls_err;
  13587. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13588. &tls_err)) {
  13589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13590. // Map TlsError to legacy ssl_error for backward compatibility
  13591. if (tls_err.code == ErrorCode::WantRead) {
  13592. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13593. } else if (tls_err.code == ErrorCode::WantWrite) {
  13594. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13595. } else {
  13596. last_ssl_error_ = SSL_ERROR_SSL;
  13597. }
  13598. #else
  13599. last_ssl_error_ = static_cast<int>(get_error());
  13600. #endif
  13601. return false;
  13602. }
  13603. handshake_done = true;
  13604. std::string remote_addr;
  13605. int remote_port = 0;
  13606. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13607. std::string local_addr;
  13608. int local_port = 0;
  13609. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13610. ret = detail::process_server_socket_ssl(
  13611. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13612. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13613. write_timeout_usec_,
  13614. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13615. return process_request(
  13616. strm, remote_addr, remote_port, local_addr, local_port,
  13617. close_connection, connection_closed,
  13618. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13619. });
  13620. return ret;
  13621. }
  13622. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13623. const char *key_pem,
  13624. const char *client_ca_pem,
  13625. const char *password) {
  13626. if (!ctx_) { return false; }
  13627. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13628. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13629. return false;
  13630. }
  13631. if (client_ca_pem) {
  13632. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13633. }
  13634. return true;
  13635. }
  13636. // SSL HTTP client implementation
  13637. inline SSLClient::~SSLClient() {
  13638. if (ctx_) { tls::free_context(ctx_); }
  13639. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13640. // base function rather than the derived function once we get to the
  13641. // base class destructor, and won't free the SSL (causing a leak).
  13642. shutdown_ssl_impl(socket_, true);
  13643. }
  13644. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13645. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13646. shutdown_ssl_impl(socket, shutdown_gracefully);
  13647. }
  13648. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13649. bool shutdown_gracefully) {
  13650. if (socket.sock == INVALID_SOCKET) {
  13651. assert(socket.ssl == nullptr);
  13652. return;
  13653. }
  13654. if (socket.ssl) {
  13655. tls::shutdown(socket.ssl, shutdown_gracefully);
  13656. {
  13657. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13658. tls::free_session(socket.ssl);
  13659. }
  13660. socket.ssl = nullptr;
  13661. }
  13662. assert(socket.ssl == nullptr);
  13663. }
  13664. inline bool SSLClient::process_socket(
  13665. const Socket &socket,
  13666. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13667. std::function<bool(Stream &strm)> callback) {
  13668. assert(socket.ssl);
  13669. return detail::process_client_socket_ssl(
  13670. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13671. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13672. std::move(callback));
  13673. }
  13674. inline bool SSLClient::is_ssl() const { return true; }
  13675. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13676. if (!is_valid()) {
  13677. error = Error::SSLConnection;
  13678. return false;
  13679. }
  13680. return ClientImpl::create_and_connect_socket(socket, error);
  13681. }
  13682. inline bool SSLClient::setup_proxy_connection(
  13683. Socket &socket,
  13684. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13685. Response &res, bool &success, Error &error) {
  13686. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13687. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13688. return false;
  13689. }
  13690. if (!initialize_ssl(socket, error)) {
  13691. success = false;
  13692. return false;
  13693. }
  13694. return true;
  13695. }
  13696. // Assumes that socket_mutex_ is locked and that there are no requests in
  13697. // flight
  13698. inline bool SSLClient::connect_with_proxy(
  13699. Socket &socket,
  13700. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13701. Response &res, bool &success, Error &error) {
  13702. success = true;
  13703. Response proxy_res;
  13704. if (!detail::process_client_socket(
  13705. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13706. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13707. start_time, [&](Stream &strm) {
  13708. Request req2;
  13709. req2.method = "CONNECT";
  13710. req2.path =
  13711. detail::make_host_and_port_string_always_port(host_, port_);
  13712. if (max_timeout_msec_ > 0) {
  13713. req2.start_time_ = std::chrono::steady_clock::now();
  13714. }
  13715. return process_request(strm, req2, proxy_res, false, error);
  13716. })) {
  13717. // Thread-safe to close everything because we are assuming there are no
  13718. // requests in flight
  13719. shutdown_ssl(socket, true);
  13720. shutdown_socket(socket);
  13721. close_socket(socket);
  13722. success = false;
  13723. return false;
  13724. }
  13725. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13726. if (!proxy_digest_auth_username_.empty() &&
  13727. !proxy_digest_auth_password_.empty()) {
  13728. std::map<std::string, std::string> auth;
  13729. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13730. // Close the current socket and create a new one for the authenticated
  13731. // request
  13732. shutdown_ssl(socket, true);
  13733. shutdown_socket(socket);
  13734. close_socket(socket);
  13735. // Create a new socket for the authenticated CONNECT request
  13736. if (!ensure_socket_connection(socket, error)) {
  13737. success = false;
  13738. output_error_log(error, nullptr);
  13739. return false;
  13740. }
  13741. proxy_res = Response();
  13742. if (!detail::process_client_socket(
  13743. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13744. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13745. start_time, [&](Stream &strm) {
  13746. Request req3;
  13747. req3.method = "CONNECT";
  13748. req3.path = detail::make_host_and_port_string_always_port(
  13749. host_, port_);
  13750. req3.headers.insert(detail::make_digest_authentication_header(
  13751. req3, auth, 1, detail::random_string(10),
  13752. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13753. true));
  13754. if (max_timeout_msec_ > 0) {
  13755. req3.start_time_ = std::chrono::steady_clock::now();
  13756. }
  13757. return process_request(strm, req3, proxy_res, false, error);
  13758. })) {
  13759. // Thread-safe to close everything because we are assuming there are
  13760. // no requests in flight
  13761. shutdown_ssl(socket, true);
  13762. shutdown_socket(socket);
  13763. close_socket(socket);
  13764. success = false;
  13765. return false;
  13766. }
  13767. }
  13768. }
  13769. }
  13770. // If status code is not 200, proxy request is failed.
  13771. // Set error to ProxyConnection and return proxy response
  13772. // as the response of the request
  13773. if (proxy_res.status != StatusCode::OK_200) {
  13774. error = Error::ProxyConnection;
  13775. output_error_log(error, nullptr);
  13776. res = std::move(proxy_res);
  13777. // Thread-safe to close everything because we are assuming there are
  13778. // no requests in flight
  13779. shutdown_ssl(socket, true);
  13780. shutdown_socket(socket);
  13781. close_socket(socket);
  13782. return false;
  13783. }
  13784. return true;
  13785. }
  13786. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13787. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13788. if (is_proxy_enabled_for_host(host_)) { return true; }
  13789. if (!initialize_ssl(socket, error)) {
  13790. shutdown_socket(socket);
  13791. close_socket(socket);
  13792. return false;
  13793. }
  13794. return true;
  13795. }
  13796. // SSL HTTP client implementation
  13797. inline SSLClient::SSLClient(const std::string &host)
  13798. : SSLClient(host, 443, std::string(), std::string()) {}
  13799. inline SSLClient::SSLClient(const std::string &host, int port)
  13800. : SSLClient(host, port, std::string(), std::string()) {}
  13801. inline void SSLClient::init_ctx() {
  13802. ctx_ = tls::create_client_context();
  13803. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13804. }
  13805. inline void SSLClient::reset_ctx_on_error() {
  13806. last_backend_error_ = tls::get_error();
  13807. tls::free_context(ctx_);
  13808. ctx_ = nullptr;
  13809. }
  13810. inline SSLClient::SSLClient(const std::string &host, int port,
  13811. const std::string &client_cert_path,
  13812. const std::string &client_key_path,
  13813. const std::string &private_key_password)
  13814. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13815. init_ctx();
  13816. if (!ctx_) { return; }
  13817. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13818. const char *password =
  13819. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13820. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13821. client_key_path.c_str(), password)) {
  13822. reset_ctx_on_error();
  13823. }
  13824. }
  13825. }
  13826. inline SSLClient::SSLClient(const std::string &host, int port,
  13827. const PemMemory &pem)
  13828. : ClientImpl(host, port) {
  13829. init_ctx();
  13830. if (!ctx_) { return; }
  13831. if (pem.cert_pem && pem.key_pem) {
  13832. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13833. pem.private_key_password)) {
  13834. reset_ctx_on_error();
  13835. }
  13836. }
  13837. }
  13838. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13839. if (ca_cert_store && ctx_) {
  13840. // set_ca_store takes ownership of ca_cert_store
  13841. tls::set_ca_store(ctx_, ca_cert_store);
  13842. ca_cert_store_set_ = true;
  13843. } else if (ca_cert_store) {
  13844. tls::free_ca_store(ca_cert_store);
  13845. }
  13846. }
  13847. inline void
  13848. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13849. if (!ctx_) { return; }
  13850. tls::set_verify_callback(ctx_, verifier);
  13851. }
  13852. inline void SSLClient::set_session_verifier(
  13853. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13854. session_verifier_ = std::move(verifier);
  13855. }
  13856. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13857. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13858. enable_windows_cert_verification_ = enabled;
  13859. }
  13860. #endif
  13861. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13862. std::size_t size) {
  13863. if (ctx_ && ca_cert && size > 0) {
  13864. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13865. tls::load_ca_pem(ctx_, ca_cert, size);
  13866. }
  13867. }
  13868. inline bool SSLClient::load_certs() {
  13869. auto ret = true;
  13870. std::call_once(initialize_cert_, [&]() {
  13871. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13872. ret = detail::load_client_ca_config(
  13873. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13874. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13875. last_backend_error_);
  13876. });
  13877. return ret;
  13878. }
  13879. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13880. using namespace tls;
  13881. // Load CA certificates if server verification is enabled
  13882. if (server_certificate_verification_) {
  13883. if (!load_certs()) {
  13884. error = Error::SSLLoadingCerts;
  13885. output_error_log(error, nullptr);
  13886. return false;
  13887. }
  13888. }
  13889. bool is_ip = detail::is_ip_address(host_);
  13890. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13891. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13892. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13893. // Chain verification happens during the handshake even for IP hosts; the
  13894. // certificate identity is verified post-handshake via verify_hostname().
  13895. set_verify_client(ctx_, server_certificate_verification_);
  13896. #endif
  13897. // Create TLS session
  13898. session_t session = nullptr;
  13899. {
  13900. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13901. session = create_session(ctx_, socket.sock);
  13902. }
  13903. if (!session) {
  13904. error = Error::SSLConnection;
  13905. last_backend_error_ = get_error();
  13906. return false;
  13907. }
  13908. // Use scope_exit to ensure session is freed on error paths
  13909. bool success = false;
  13910. auto session_guard = detail::scope_exit([&] {
  13911. if (!success) { free_session(session); }
  13912. });
  13913. // Set SNI extension (skip for IP addresses per RFC 6066).
  13914. // On MbedTLS, set_sni also enables hostname verification internally.
  13915. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13916. if (!is_ip) {
  13917. if (!set_sni(session, host_.c_str())) {
  13918. error = Error::SSLConnection;
  13919. last_backend_error_ = get_error();
  13920. return false;
  13921. }
  13922. }
  13923. // Perform non-blocking TLS handshake with timeout
  13924. TlsError tls_err;
  13925. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13926. connection_timeout_usec_, &tls_err)) {
  13927. last_ssl_error_ = static_cast<int>(tls_err.code);
  13928. last_backend_error_ = tls_err.backend_code;
  13929. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13930. error = Error::SSLServerVerification;
  13931. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13932. error = Error::SSLServerHostnameVerification;
  13933. } else {
  13934. error = Error::SSLConnection;
  13935. }
  13936. output_error_log(error, nullptr);
  13937. return false;
  13938. }
  13939. // Post-handshake session verifier callback
  13940. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13941. if (session_verifier_) { verification_status = session_verifier_(session); }
  13942. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13943. last_backend_error_ = get_error();
  13944. error = Error::SSLServerVerification;
  13945. output_error_log(error, nullptr);
  13946. return false;
  13947. }
  13948. // Default server certificate verification
  13949. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13950. server_certificate_verification_) {
  13951. verify_result_ = tls::get_verify_result(session);
  13952. if (verify_result_ != 0) {
  13953. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13954. error = Error::SSLServerVerification;
  13955. output_error_log(error, nullptr);
  13956. return false;
  13957. }
  13958. auto server_cert = get_peer_cert(session);
  13959. if (!server_cert) {
  13960. last_backend_error_ = get_error();
  13961. error = Error::SSLServerVerification;
  13962. output_error_log(error, nullptr);
  13963. return false;
  13964. }
  13965. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13966. // Hostname verification (post-handshake for all cases).
  13967. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13968. // On MbedTLS, set_sni already enabled hostname verification during
  13969. // handshake for non-IP hosts, but this check is still needed for IP
  13970. // addresses where SNI is not set.
  13971. if (server_hostname_verification_) {
  13972. if (!verify_hostname(server_cert, host_.c_str())) {
  13973. last_backend_error_ = hostname_mismatch_code();
  13974. error = Error::SSLServerHostnameVerification;
  13975. output_error_log(error, nullptr);
  13976. return false;
  13977. }
  13978. }
  13979. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13980. // Additional Windows Schannel verification.
  13981. // This provides real-time certificate validation with Windows Update
  13982. // integration, working with both OpenSSL and MbedTLS backends.
  13983. // Skip when a custom CA cert is specified, as the Windows certificate
  13984. // store would not know about user-provided CA certificates. Also skip
  13985. // when system CA trust is explicitly disabled.
  13986. if (enable_windows_cert_verification_ &&
  13987. system_ca_mode_ != SystemCAMode::Disabled &&
  13988. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  13989. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  13990. std::vector<unsigned char> der;
  13991. if (get_cert_der(server_cert, der)) {
  13992. uint64_t wincrypt_error = 0;
  13993. if (!detail::verify_cert_with_windows_schannel(
  13994. der, host_, server_hostname_verification_, wincrypt_error)) {
  13995. last_backend_error_ = wincrypt_error;
  13996. error = Error::SSLServerVerification;
  13997. output_error_log(error, nullptr);
  13998. return false;
  13999. }
  14000. }
  14001. }
  14002. #endif
  14003. }
  14004. success = true;
  14005. socket.ssl = session;
  14006. return true;
  14007. }
  14008. inline void Client::set_digest_auth(const std::string &username,
  14009. const std::string &password) {
  14010. cli_->set_digest_auth(username, password);
  14011. }
  14012. inline void Client::set_proxy_digest_auth(const std::string &username,
  14013. const std::string &password) {
  14014. cli_->set_proxy_digest_auth(username, password);
  14015. }
  14016. inline void Client::enable_server_certificate_verification(bool enabled) {
  14017. cli_->enable_server_certificate_verification(enabled);
  14018. }
  14019. inline void Client::enable_server_hostname_verification(bool enabled) {
  14020. cli_->enable_server_hostname_verification(enabled);
  14021. }
  14022. inline void Client::enable_system_ca(bool enabled) {
  14023. cli_->enable_system_ca(enabled);
  14024. }
  14025. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14026. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14027. if (is_ssl_) {
  14028. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14029. enabled);
  14030. }
  14031. }
  14032. #endif
  14033. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14034. const std::string &ca_cert_dir_path) {
  14035. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14036. }
  14037. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14038. if (is_ssl_) {
  14039. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14040. } else if (ca_cert_store) {
  14041. tls::free_ca_store(ca_cert_store);
  14042. }
  14043. }
  14044. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14045. if (is_ssl_) {
  14046. // Use the PEM-based path so the CA data is retained for redirect transfer
  14047. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14048. }
  14049. }
  14050. inline void
  14051. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14052. if (is_ssl_) {
  14053. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14054. std::move(verifier));
  14055. }
  14056. }
  14057. inline void Client::set_session_verifier(
  14058. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14059. if (is_ssl_) {
  14060. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14061. }
  14062. }
  14063. inline tls::ctx_t Client::tls_context() const {
  14064. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14065. return nullptr;
  14066. }
  14067. #endif // CPPHTTPLIB_SSL_ENABLED
  14068. /*
  14069. * Group 7: TLS abstraction layer - Common API
  14070. */
  14071. #ifdef CPPHTTPLIB_SSL_ENABLED
  14072. namespace tls {
  14073. // Helper for PeerCert construction
  14074. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14075. return PeerCert(get_peer_cert(session));
  14076. }
  14077. namespace impl {
  14078. inline VerifyCallback &get_verify_callback() {
  14079. static thread_local VerifyCallback callback;
  14080. return callback;
  14081. }
  14082. inline VerifyCallback &get_mbedtls_verify_callback() {
  14083. static thread_local VerifyCallback callback;
  14084. return callback;
  14085. }
  14086. // Check if a string is an IPv4 address
  14087. inline bool is_ipv4_address(const std::string &str) {
  14088. int dots = 0;
  14089. for (char c : str) {
  14090. if (c == '.') {
  14091. dots++;
  14092. } else if (!detail::is_ascii_digit(c)) {
  14093. return false;
  14094. }
  14095. }
  14096. return dots == 3;
  14097. }
  14098. // Parse IPv4 address string to bytes
  14099. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14100. const char *p = str.c_str();
  14101. for (int i = 0; i < 4; i++) {
  14102. if (i > 0) {
  14103. if (*p != '.') { return false; }
  14104. p++;
  14105. }
  14106. int val = 0;
  14107. int digits = 0;
  14108. while (detail::is_ascii_digit(*p)) {
  14109. val = val * 10 + (*p - '0');
  14110. if (val > 255) { return false; }
  14111. p++;
  14112. digits++;
  14113. }
  14114. if (digits == 0) { return false; }
  14115. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14116. if (digits > 1 && *(p - digits) == '0') { return false; }
  14117. out[i] = static_cast<unsigned char>(val);
  14118. }
  14119. return *p == '\0';
  14120. }
  14121. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14122. // `out` must have room for at least 16 bytes. Returns the address length
  14123. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14124. // literal. Used to match a host against iPAddress SANs the same way the
  14125. // OpenSSL backend does via X509_check_ip.
  14126. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14127. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14128. struct in6_addr addr6 = {};
  14129. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14130. memcpy(out, &addr6, 16);
  14131. return 16;
  14132. }
  14133. return 0;
  14134. }
  14135. #ifdef _WIN32
  14136. // Enumerate Windows system certificates and call callback with DER data
  14137. template <typename Callback>
  14138. inline bool enumerate_windows_system_certs(Callback cb) {
  14139. bool loaded = false;
  14140. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14141. for (auto store_name : store_names) {
  14142. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14143. if (hStore) {
  14144. PCCERT_CONTEXT pContext = nullptr;
  14145. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14146. nullptr) {
  14147. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14148. loaded = true;
  14149. }
  14150. }
  14151. CertCloseStore(hStore, 0);
  14152. }
  14153. }
  14154. return loaded;
  14155. }
  14156. #endif
  14157. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14158. // Enumerate macOS Keychain certificates and call callback with DER data
  14159. template <typename Callback>
  14160. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14161. bool loaded = false;
  14162. const SecTrustSettingsDomain domains[] = {
  14163. kSecTrustSettingsDomainSystem,
  14164. kSecTrustSettingsDomainAdmin,
  14165. kSecTrustSettingsDomainUser,
  14166. };
  14167. for (auto domain : domains) {
  14168. CFArrayRef certs = nullptr;
  14169. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14170. if (status != errSecSuccess || !certs) {
  14171. if (certs) CFRelease(certs);
  14172. continue;
  14173. }
  14174. CFIndex count = CFArrayGetCount(certs);
  14175. for (CFIndex i = 0; i < count; i++) {
  14176. SecCertificateRef cert =
  14177. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14178. CFDataRef data = SecCertificateCopyData(cert);
  14179. if (data) {
  14180. if (cb(CFDataGetBytePtr(data),
  14181. static_cast<size_t>(CFDataGetLength(data)))) {
  14182. loaded = true;
  14183. }
  14184. CFRelease(data);
  14185. }
  14186. }
  14187. CFRelease(certs);
  14188. }
  14189. return loaded;
  14190. }
  14191. #endif
  14192. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14193. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14194. // Common CA certificate file paths on Linux/Unix
  14195. inline const char **system_ca_paths() {
  14196. static const char *paths[] = {
  14197. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14198. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14199. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14200. "/etc/pki/tls/cacert.pem", // OpenELEC
  14201. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14202. nullptr};
  14203. return paths;
  14204. }
  14205. // Common CA certificate directory paths on Linux/Unix
  14206. inline const char **system_ca_dirs() {
  14207. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14208. "/etc/pki/tls/certs", // RHEL/CentOS
  14209. "/usr/share/ca-certificates", // Other
  14210. nullptr};
  14211. return dirs;
  14212. }
  14213. #endif
  14214. } // namespace impl
  14215. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14216. const char *ca_dir) {
  14217. if (!ctx) { return false; }
  14218. bool success = true;
  14219. if (ca_file && *ca_file) {
  14220. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14221. }
  14222. if (ca_dir && *ca_dir) {
  14223. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14224. }
  14225. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14226. // Set CA list for client certificate request (CertificateRequest message)
  14227. if (ca_file && *ca_file) {
  14228. auto list = SSL_load_client_CA_file(ca_file);
  14229. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14230. }
  14231. #endif
  14232. return success;
  14233. }
  14234. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14235. const char *password) {
  14236. return set_client_cert_pem(ctx, cert, key, password);
  14237. }
  14238. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14239. const char *key_path, const char *password) {
  14240. return set_client_cert_file(ctx, cert_path, key_path, password);
  14241. }
  14242. // PeerCert implementation
  14243. inline PeerCert::PeerCert() = default;
  14244. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14245. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14246. other.cert_ = nullptr;
  14247. }
  14248. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14249. if (this != &other) {
  14250. if (cert_) { free_cert(cert_); }
  14251. cert_ = other.cert_;
  14252. other.cert_ = nullptr;
  14253. }
  14254. return *this;
  14255. }
  14256. inline PeerCert::~PeerCert() {
  14257. if (cert_) { free_cert(cert_); }
  14258. }
  14259. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14260. inline std::string PeerCert::subject_cn() const {
  14261. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14262. }
  14263. inline std::string PeerCert::issuer_name() const {
  14264. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14265. }
  14266. inline bool PeerCert::check_hostname(const char *hostname) const {
  14267. return cert_ ? verify_hostname(cert_, hostname) : false;
  14268. }
  14269. inline std::vector<SanEntry> PeerCert::sans() const {
  14270. std::vector<SanEntry> result;
  14271. if (cert_) { get_cert_sans(cert_, result); }
  14272. return result;
  14273. }
  14274. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14275. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14276. }
  14277. inline std::string PeerCert::serial() const {
  14278. return cert_ ? get_cert_serial(cert_) : std::string();
  14279. }
  14280. // VerifyContext method implementations
  14281. inline std::string VerifyContext::subject_cn() const {
  14282. return cert ? get_cert_subject_cn(cert) : std::string();
  14283. }
  14284. inline std::string VerifyContext::issuer_name() const {
  14285. return cert ? get_cert_issuer_name(cert) : std::string();
  14286. }
  14287. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14288. return cert ? verify_hostname(cert, hostname) : false;
  14289. }
  14290. inline std::vector<SanEntry> VerifyContext::sans() const {
  14291. std::vector<SanEntry> result;
  14292. if (cert) { get_cert_sans(cert, result); }
  14293. return result;
  14294. }
  14295. inline bool VerifyContext::validity(time_t &not_before,
  14296. time_t &not_after) const {
  14297. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14298. }
  14299. inline std::string VerifyContext::serial() const {
  14300. return cert ? get_cert_serial(cert) : std::string();
  14301. }
  14302. // TlsError static method implementation
  14303. inline std::string TlsError::verify_error_to_string(long error_code) {
  14304. return verify_error_string(error_code);
  14305. }
  14306. } // namespace tls
  14307. // Request::peer_cert() implementation
  14308. inline tls::PeerCert Request::peer_cert() const {
  14309. return tls::get_peer_cert_from_session(ssl);
  14310. }
  14311. // Request::sni() implementation
  14312. inline std::string Request::sni() const {
  14313. if (!ssl) { return std::string(); }
  14314. const char *s = tls::get_sni(ssl);
  14315. return s ? std::string(s) : std::string();
  14316. }
  14317. #endif // CPPHTTPLIB_SSL_ENABLED
  14318. /*
  14319. * Group 8: TLS abstraction layer - OpenSSL backend
  14320. */
  14321. /*
  14322. * OpenSSL Backend Implementation
  14323. */
  14324. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14325. namespace tls {
  14326. namespace impl {
  14327. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14328. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14329. switch (ssl_error) {
  14330. case SSL_ERROR_NONE: return ErrorCode::Success;
  14331. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14332. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14333. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14334. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14335. case SSL_ERROR_SSL:
  14336. default: return ErrorCode::Fatal;
  14337. }
  14338. }
  14339. // Helper: Create client CA list from PEM string
  14340. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14341. // Caller takes ownership of returned list
  14342. inline STACK_OF(X509_NAME) *
  14343. create_client_ca_list_from_pem(const char *ca_pem) {
  14344. if (!ca_pem) { return nullptr; }
  14345. auto ca_list = sk_X509_NAME_new_null();
  14346. if (!ca_list) { return nullptr; }
  14347. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14348. if (!bio) {
  14349. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14350. return nullptr;
  14351. }
  14352. X509 *cert = nullptr;
  14353. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14354. nullptr) {
  14355. const X509_NAME *name = X509_get_subject_name(cert);
  14356. if (name) {
  14357. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14358. }
  14359. X509_free(cert);
  14360. }
  14361. BIO_free(bio);
  14362. return ca_list;
  14363. }
  14364. // OpenSSL verify callback wrapper
  14365. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14366. auto &callback = get_verify_callback();
  14367. if (!callback) { return preverify_ok; }
  14368. // Get SSL object from X509_STORE_CTX
  14369. auto ssl = static_cast<SSL *>(
  14370. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14371. if (!ssl) { return preverify_ok; }
  14372. // Get current certificate and depth
  14373. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14374. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14375. int error = X509_STORE_CTX_get_error(ctx);
  14376. // Build context
  14377. VerifyContext verify_ctx;
  14378. verify_ctx.session = static_cast<session_t>(ssl);
  14379. verify_ctx.cert = static_cast<cert_t>(cert);
  14380. verify_ctx.depth = depth;
  14381. verify_ctx.preverify_ok = (preverify_ok != 0);
  14382. verify_ctx.error_code = error;
  14383. verify_ctx.error_string =
  14384. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14385. return callback(verify_ctx) ? 1 : 0;
  14386. }
  14387. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14388. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14389. // that must be released with release_store_objects
  14390. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14391. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14392. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14393. #endif
  14394. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14395. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14396. return X509_STORE_get1_objects(store);
  14397. #else
  14398. return X509_STORE_get0_objects(store);
  14399. #endif
  14400. }
  14401. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14402. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14403. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14404. #else
  14405. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14406. #endif
  14407. }
  14408. } // namespace impl
  14409. inline ctx_t create_client_context() {
  14410. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14411. if (ctx) {
  14412. // Disable auto-retry to properly handle non-blocking I/O
  14413. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14414. // Set minimum TLS version
  14415. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14416. }
  14417. return static_cast<ctx_t>(ctx);
  14418. }
  14419. inline void free_context(ctx_t ctx) {
  14420. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14421. }
  14422. inline bool set_min_version(ctx_t ctx, Version version) {
  14423. if (!ctx) return false;
  14424. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14425. static_cast<int>(version)) == 1;
  14426. }
  14427. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14428. if (!ctx || !pem || len == 0) return false;
  14429. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14430. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14431. if (!store) return false;
  14432. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14433. if (!bio) return false;
  14434. bool ok = true;
  14435. X509 *cert = nullptr;
  14436. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14437. nullptr) {
  14438. if (X509_STORE_add_cert(store, cert) != 1) {
  14439. // Ignore duplicate errors
  14440. auto err = ERR_peek_last_error();
  14441. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14442. ok = false;
  14443. }
  14444. }
  14445. X509_free(cert);
  14446. if (!ok) break;
  14447. }
  14448. BIO_free(bio);
  14449. // Clear any "no more certificates" errors
  14450. ERR_clear_error();
  14451. return ok;
  14452. }
  14453. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14454. if (!ctx || !file_path) return false;
  14455. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14456. nullptr) == 1;
  14457. }
  14458. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14459. if (!ctx || !dir_path) return false;
  14460. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14461. dir_path) == 1;
  14462. }
  14463. inline bool load_system_certs(ctx_t ctx) {
  14464. if (!ctx) return false;
  14465. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14466. #ifdef _WIN32
  14467. // Windows: Load from system certificate store (ROOT and CA)
  14468. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14469. if (!store) return false;
  14470. bool loaded_any = false;
  14471. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14472. for (auto store_name : store_names) {
  14473. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14474. if (!hStore) continue;
  14475. PCCERT_CONTEXT pContext = nullptr;
  14476. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14477. nullptr) {
  14478. const unsigned char *data = pContext->pbCertEncoded;
  14479. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14480. if (x509) {
  14481. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14482. X509_free(x509);
  14483. }
  14484. }
  14485. CertCloseStore(hStore, 0);
  14486. }
  14487. return loaded_any;
  14488. #elif defined(__APPLE__)
  14489. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14490. // macOS: Load from Keychain
  14491. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14492. if (!store) return false;
  14493. bool loaded_any = false;
  14494. const SecTrustSettingsDomain domains[] = {
  14495. kSecTrustSettingsDomainSystem,
  14496. kSecTrustSettingsDomainAdmin,
  14497. kSecTrustSettingsDomainUser,
  14498. };
  14499. for (auto domain : domains) {
  14500. CFArrayRef certs = nullptr;
  14501. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14502. !certs) {
  14503. if (certs) CFRelease(certs);
  14504. continue;
  14505. }
  14506. auto count = CFArrayGetCount(certs);
  14507. for (CFIndex i = 0; i < count; i++) {
  14508. auto cert = reinterpret_cast<SecCertificateRef>(
  14509. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14510. CFDataRef der = SecCertificateCopyData(cert);
  14511. if (der) {
  14512. const unsigned char *data = CFDataGetBytePtr(der);
  14513. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14514. if (x509) {
  14515. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14516. X509_free(x509);
  14517. }
  14518. CFRelease(der);
  14519. }
  14520. }
  14521. CFRelease(certs);
  14522. }
  14523. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14524. #else
  14525. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14526. #endif
  14527. #else
  14528. // Other Unix: use default verify paths
  14529. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14530. #endif
  14531. }
  14532. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14533. const char *password) {
  14534. if (!ctx || !cert || !key) return false;
  14535. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14536. // Load certificate
  14537. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14538. if (!cert_bio) return false;
  14539. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14540. BIO_free(cert_bio);
  14541. if (!x509) return false;
  14542. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14543. X509_free(x509);
  14544. if (!cert_ok) return false;
  14545. // Load private key
  14546. auto key_bio = BIO_new_mem_buf(key, -1);
  14547. if (!key_bio) return false;
  14548. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14549. password ? const_cast<char *>(password)
  14550. : nullptr);
  14551. BIO_free(key_bio);
  14552. if (!pkey) return false;
  14553. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14554. EVP_PKEY_free(pkey);
  14555. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14556. }
  14557. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14558. const char *key_path, const char *password) {
  14559. if (!ctx || !cert_path || !key_path) return false;
  14560. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14561. if (password && password[0] != '\0') {
  14562. SSL_CTX_set_default_passwd_cb_userdata(
  14563. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14564. }
  14565. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14566. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14567. }
  14568. inline ctx_t create_server_context() {
  14569. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14570. if (ctx) {
  14571. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14572. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14573. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14574. }
  14575. return static_cast<ctx_t>(ctx);
  14576. }
  14577. inline void set_verify_client(ctx_t ctx, bool require) {
  14578. if (!ctx) return;
  14579. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14580. require
  14581. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14582. : SSL_VERIFY_NONE,
  14583. nullptr);
  14584. }
  14585. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14586. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14587. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14588. SSL *ssl = SSL_new(ssl_ctx);
  14589. if (!ssl) return nullptr;
  14590. // Disable auto-retry for proper non-blocking I/O handling
  14591. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14592. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14593. if (!bio) {
  14594. SSL_free(ssl);
  14595. return nullptr;
  14596. }
  14597. SSL_set_bio(ssl, bio, bio);
  14598. return static_cast<session_t>(ssl);
  14599. }
  14600. inline void free_session(session_t session) {
  14601. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14602. }
  14603. inline bool set_sni(session_t session, const char *hostname) {
  14604. if (!session || !hostname) return false;
  14605. auto ssl = static_cast<SSL *>(session);
  14606. // Set SNI (Server Name Indication) only - does not enable verification
  14607. #if defined(OPENSSL_IS_BORINGSSL)
  14608. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14609. #else
  14610. // Direct call instead of macro to suppress -Wold-style-cast warning
  14611. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14612. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14613. #endif
  14614. }
  14615. inline bool set_hostname(session_t session, const char *hostname) {
  14616. if (!session || !hostname) return false;
  14617. auto ssl = static_cast<SSL *>(session);
  14618. // Enable hostname verification
  14619. auto param = SSL_get0_param(ssl);
  14620. if (!param) return false;
  14621. if (detail::is_ip_address(hostname)) {
  14622. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14623. // certificate's IP SANs instead of its DNS names
  14624. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14625. } else {
  14626. // Set SNI (Server Name Indication)
  14627. if (!set_sni(session, hostname)) { return false; }
  14628. X509_VERIFY_PARAM_set_hostflags(param,
  14629. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14630. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14631. }
  14632. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14633. return true;
  14634. }
  14635. inline TlsError connect(session_t session) {
  14636. if (!session) { return TlsError(); }
  14637. auto ssl = static_cast<SSL *>(session);
  14638. auto ret = SSL_connect(ssl);
  14639. TlsError err;
  14640. if (ret == 1) {
  14641. err.code = ErrorCode::Success;
  14642. } else {
  14643. auto ssl_err = SSL_get_error(ssl, ret);
  14644. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14645. err.backend_code = ERR_get_error();
  14646. }
  14647. return err;
  14648. }
  14649. inline TlsError accept(session_t session) {
  14650. if (!session) { return TlsError(); }
  14651. auto ssl = static_cast<SSL *>(session);
  14652. auto ret = SSL_accept(ssl);
  14653. TlsError err;
  14654. if (ret == 1) {
  14655. err.code = ErrorCode::Success;
  14656. } else {
  14657. auto ssl_err = SSL_get_error(ssl, ret);
  14658. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14659. err.backend_code = ERR_get_error();
  14660. }
  14661. return err;
  14662. }
  14663. inline bool connect_nonblocking(session_t session, socket_t sock,
  14664. time_t timeout_sec, time_t timeout_usec,
  14665. TlsError *err) {
  14666. if (!session) {
  14667. if (err) { err->code = ErrorCode::Fatal; }
  14668. return false;
  14669. }
  14670. auto ssl = static_cast<SSL *>(session);
  14671. auto bio = SSL_get_rbio(ssl);
  14672. // Set non-blocking mode for handshake
  14673. detail::set_nonblocking(sock, true);
  14674. if (bio) { BIO_set_nbio(bio, 1); }
  14675. auto cleanup = detail::scope_exit([&]() {
  14676. // Restore blocking mode after handshake
  14677. if (bio) { BIO_set_nbio(bio, 0); }
  14678. detail::set_nonblocking(sock, false);
  14679. });
  14680. auto res = 0;
  14681. while ((res = SSL_connect(ssl)) != 1) {
  14682. auto ssl_err = SSL_get_error(ssl, res);
  14683. switch (ssl_err) {
  14684. case SSL_ERROR_WANT_READ:
  14685. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14686. continue;
  14687. }
  14688. break;
  14689. case SSL_ERROR_WANT_WRITE:
  14690. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14691. continue;
  14692. }
  14693. break;
  14694. default: break;
  14695. }
  14696. if (err) {
  14697. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14698. err->backend_code = ERR_get_error();
  14699. }
  14700. return false;
  14701. }
  14702. if (err) { err->code = ErrorCode::Success; }
  14703. return true;
  14704. }
  14705. inline bool accept_nonblocking(session_t session, socket_t sock,
  14706. time_t timeout_sec, time_t timeout_usec,
  14707. TlsError *err) {
  14708. if (!session) {
  14709. if (err) { err->code = ErrorCode::Fatal; }
  14710. return false;
  14711. }
  14712. auto ssl = static_cast<SSL *>(session);
  14713. auto bio = SSL_get_rbio(ssl);
  14714. // Set non-blocking mode for handshake
  14715. detail::set_nonblocking(sock, true);
  14716. if (bio) { BIO_set_nbio(bio, 1); }
  14717. auto cleanup = detail::scope_exit([&]() {
  14718. // Restore blocking mode after handshake
  14719. if (bio) { BIO_set_nbio(bio, 0); }
  14720. detail::set_nonblocking(sock, false);
  14721. });
  14722. auto res = 0;
  14723. while ((res = SSL_accept(ssl)) != 1) {
  14724. auto ssl_err = SSL_get_error(ssl, res);
  14725. switch (ssl_err) {
  14726. case SSL_ERROR_WANT_READ:
  14727. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14728. continue;
  14729. }
  14730. break;
  14731. case SSL_ERROR_WANT_WRITE:
  14732. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14733. continue;
  14734. }
  14735. break;
  14736. default: break;
  14737. }
  14738. if (err) {
  14739. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14740. err->backend_code = ERR_get_error();
  14741. }
  14742. return false;
  14743. }
  14744. if (err) { err->code = ErrorCode::Success; }
  14745. return true;
  14746. }
  14747. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14748. if (!session || !buf) {
  14749. err.code = ErrorCode::Fatal;
  14750. return -1;
  14751. }
  14752. auto ssl = static_cast<SSL *>(session);
  14753. constexpr auto max_len =
  14754. static_cast<size_t>((std::numeric_limits<int>::max)());
  14755. if (len > max_len) { len = max_len; }
  14756. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14757. if (ret > 0) {
  14758. err.code = ErrorCode::Success;
  14759. return ret;
  14760. }
  14761. auto ssl_err = SSL_get_error(ssl, ret);
  14762. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14763. if (err.code == ErrorCode::PeerClosed) {
  14764. return 0;
  14765. } // Gracefully handle the peer closed state.
  14766. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14767. return -1;
  14768. }
  14769. inline ssize_t write(session_t session, const void *buf, size_t len,
  14770. TlsError &err) {
  14771. if (!session || !buf) {
  14772. err.code = ErrorCode::Fatal;
  14773. return -1;
  14774. }
  14775. auto ssl = static_cast<SSL *>(session);
  14776. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14777. if (ret > 0) {
  14778. err.code = ErrorCode::Success;
  14779. return ret;
  14780. }
  14781. auto ssl_err = SSL_get_error(ssl, ret);
  14782. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14783. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14784. return -1;
  14785. }
  14786. inline int pending(const_session_t session) {
  14787. if (!session) return 0;
  14788. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14789. }
  14790. inline void shutdown(session_t session, bool graceful) {
  14791. if (!session) return;
  14792. auto ssl = static_cast<SSL *>(session);
  14793. if (graceful) {
  14794. // First call sends close_notify
  14795. if (SSL_shutdown(ssl) == 0) {
  14796. // Second call waits for peer's close_notify
  14797. SSL_shutdown(ssl);
  14798. }
  14799. }
  14800. }
  14801. inline bool is_peer_closed(session_t session, socket_t sock) {
  14802. if (!session) return true;
  14803. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14804. detail::set_nonblocking(sock, true);
  14805. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14806. auto ssl = static_cast<SSL *>(session);
  14807. char buf;
  14808. auto ret = SSL_peek(ssl, &buf, 1);
  14809. if (ret > 0) return false;
  14810. auto err = SSL_get_error(ssl, ret);
  14811. return err == SSL_ERROR_ZERO_RETURN;
  14812. }
  14813. inline cert_t get_peer_cert(const_session_t session) {
  14814. if (!session) return nullptr;
  14815. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14816. static_cast<SSL *>(const_cast<void *>(session))));
  14817. }
  14818. inline void free_cert(cert_t cert) {
  14819. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14820. }
  14821. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14822. if (!cert || !hostname) return false;
  14823. auto x509 = static_cast<X509 *>(cert);
  14824. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14825. if (detail::is_ip_address(hostname)) {
  14826. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14827. }
  14828. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14829. }
  14830. inline uint64_t hostname_mismatch_code() {
  14831. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14832. }
  14833. inline long get_verify_result(const_session_t session) {
  14834. if (!session) return X509_V_ERR_UNSPECIFIED;
  14835. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14836. }
  14837. inline std::string get_cert_subject_cn(cert_t cert) {
  14838. if (!cert) return "";
  14839. auto x509 = static_cast<X509 *>(cert);
  14840. auto subject_name = X509_get_subject_name(x509);
  14841. if (!subject_name) return "";
  14842. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14843. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14844. if (idx < 0) return "";
  14845. auto entry = X509_NAME_get_entry(subject_name, idx);
  14846. if (!entry) return "";
  14847. auto data = X509_NAME_ENTRY_get_data(entry);
  14848. if (!data) return "";
  14849. return std::string(
  14850. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14851. static_cast<size_t>(ASN1_STRING_length(data)));
  14852. }
  14853. inline std::string get_cert_issuer_name(cert_t cert) {
  14854. if (!cert) return "";
  14855. auto x509 = static_cast<X509 *>(cert);
  14856. auto issuer_name = X509_get_issuer_name(x509);
  14857. if (!issuer_name) return "";
  14858. char buf[256];
  14859. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14860. return std::string(buf);
  14861. }
  14862. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14863. sans.clear();
  14864. if (!cert) return false;
  14865. auto x509 = static_cast<X509 *>(cert);
  14866. auto names = static_cast<GENERAL_NAMES *>(
  14867. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14868. if (!names) return true; // No SANs is valid
  14869. auto count = sk_GENERAL_NAME_num(names);
  14870. for (decltype(count) i = 0; i < count; i++) {
  14871. auto gen = sk_GENERAL_NAME_value(names, i);
  14872. if (!gen) continue;
  14873. SanEntry entry;
  14874. switch (gen->type) {
  14875. case GEN_DNS:
  14876. entry.type = SanType::DNS;
  14877. if (gen->d.dNSName) {
  14878. entry.value = std::string(
  14879. reinterpret_cast<const char *>(
  14880. ASN1_STRING_get0_data(gen->d.dNSName)),
  14881. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14882. }
  14883. break;
  14884. case GEN_IPADD:
  14885. entry.type = SanType::IP;
  14886. if (gen->d.iPAddress) {
  14887. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14888. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14889. if (len == 4) {
  14890. // IPv4
  14891. char buf[INET_ADDRSTRLEN];
  14892. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14893. entry.value = buf;
  14894. } else if (len == 16) {
  14895. // IPv6
  14896. char buf[INET6_ADDRSTRLEN];
  14897. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14898. entry.value = buf;
  14899. }
  14900. }
  14901. break;
  14902. case GEN_EMAIL:
  14903. entry.type = SanType::EMAIL;
  14904. if (gen->d.rfc822Name) {
  14905. entry.value = std::string(
  14906. reinterpret_cast<const char *>(
  14907. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14908. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14909. }
  14910. break;
  14911. case GEN_URI:
  14912. entry.type = SanType::URI;
  14913. if (gen->d.uniformResourceIdentifier) {
  14914. entry.value = std::string(
  14915. reinterpret_cast<const char *>(
  14916. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14917. static_cast<size_t>(
  14918. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14919. }
  14920. break;
  14921. default: entry.type = SanType::OTHER; break;
  14922. }
  14923. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14924. }
  14925. GENERAL_NAMES_free(names);
  14926. return true;
  14927. }
  14928. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14929. time_t &not_after) {
  14930. if (!cert) return false;
  14931. auto x509 = static_cast<X509 *>(cert);
  14932. auto nb = X509_get0_notBefore(x509);
  14933. auto na = X509_get0_notAfter(x509);
  14934. if (!nb || !na) return false;
  14935. ASN1_TIME *epoch = ASN1_TIME_new();
  14936. if (!epoch) return false;
  14937. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14938. if (!ASN1_TIME_set(epoch, 0)) return false;
  14939. int pday, psec;
  14940. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14941. not_before = 86400 * (time_t)pday + psec;
  14942. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14943. not_after = 86400 * (time_t)pday + psec;
  14944. return true;
  14945. }
  14946. inline std::string get_cert_serial(cert_t cert) {
  14947. if (!cert) return "";
  14948. auto x509 = static_cast<X509 *>(cert);
  14949. auto serial = X509_get_serialNumber(x509);
  14950. if (!serial) return "";
  14951. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14952. if (!bn) return "";
  14953. auto hex = BN_bn2hex(bn);
  14954. BN_free(bn);
  14955. if (!hex) return "";
  14956. std::string result(hex);
  14957. OPENSSL_free(hex);
  14958. return result;
  14959. }
  14960. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14961. if (!cert) return false;
  14962. auto x509 = static_cast<X509 *>(cert);
  14963. auto len = i2d_X509(x509, nullptr);
  14964. if (len < 0) return false;
  14965. der.resize(static_cast<size_t>(len));
  14966. auto p = der.data();
  14967. i2d_X509(x509, &p);
  14968. return true;
  14969. }
  14970. inline const char *get_sni(const_session_t session) {
  14971. if (!session) return nullptr;
  14972. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14973. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14974. }
  14975. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14976. inline uint64_t get_error() { return ERR_get_error(); }
  14977. inline std::string error_string(uint64_t code) {
  14978. char buf[256];
  14979. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14980. return std::string(buf);
  14981. }
  14982. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14983. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14984. if (!mem) { return nullptr; }
  14985. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14986. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14987. if (!inf) { return nullptr; }
  14988. auto store = X509_STORE_new();
  14989. if (store) {
  14990. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14991. auto itmp = sk_X509_INFO_value(inf, i);
  14992. if (!itmp) { continue; }
  14993. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14994. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14995. }
  14996. }
  14997. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14998. return static_cast<ca_store_t>(store);
  14999. }
  15000. inline void free_ca_store(ca_store_t store) {
  15001. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15002. }
  15003. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15004. if (!ctx || !store) { return false; }
  15005. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15006. auto x509_store = static_cast<X509_STORE *>(store);
  15007. // Check if same store is already set
  15008. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15009. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15010. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15011. return true;
  15012. }
  15013. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15014. certs.clear();
  15015. if (!ctx) { return 0; }
  15016. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15017. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15018. if (!store) { return 0; }
  15019. auto objs = impl::get_store_objects(store);
  15020. if (!objs) { return 0; }
  15021. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15022. auto count = sk_X509_OBJECT_num(objs);
  15023. for (decltype(count) i = 0; i < count; i++) {
  15024. auto obj = sk_X509_OBJECT_value(objs, i);
  15025. if (!obj) { continue; }
  15026. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15027. auto x509 = X509_OBJECT_get0_X509(obj);
  15028. if (x509) {
  15029. // Increment reference count so caller can free it
  15030. X509_up_ref(x509);
  15031. certs.push_back(static_cast<cert_t>(x509));
  15032. }
  15033. }
  15034. }
  15035. return certs.size();
  15036. }
  15037. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15038. std::vector<std::string> names;
  15039. if (!ctx) { return names; }
  15040. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15041. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15042. if (!store) { return names; }
  15043. auto objs = impl::get_store_objects(store);
  15044. if (!objs) { return names; }
  15045. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15046. auto count = sk_X509_OBJECT_num(objs);
  15047. for (decltype(count) i = 0; i < count; i++) {
  15048. auto obj = sk_X509_OBJECT_value(objs, i);
  15049. if (!obj) { continue; }
  15050. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15051. auto x509 = X509_OBJECT_get0_X509(obj);
  15052. if (x509) {
  15053. auto subject = X509_get_subject_name(x509);
  15054. if (subject) {
  15055. char buf[512];
  15056. X509_NAME_oneline(subject, buf, sizeof(buf));
  15057. names.push_back(buf);
  15058. }
  15059. }
  15060. }
  15061. }
  15062. return names;
  15063. }
  15064. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15065. const char *key_pem, const char *password) {
  15066. if (!ctx || !cert_pem || !key_pem) { return false; }
  15067. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15068. // Load certificate from PEM
  15069. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15070. if (!cert_bio) { return false; }
  15071. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15072. BIO_free(cert_bio);
  15073. if (!cert) { return false; }
  15074. // Load private key from PEM
  15075. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15076. if (!key_bio) {
  15077. X509_free(cert);
  15078. return false;
  15079. }
  15080. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15081. password ? const_cast<char *>(password)
  15082. : nullptr);
  15083. BIO_free(key_bio);
  15084. if (!key) {
  15085. X509_free(cert);
  15086. return false;
  15087. }
  15088. // Update certificate and key
  15089. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15090. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15091. X509_free(cert);
  15092. EVP_PKEY_free(key);
  15093. return ret;
  15094. }
  15095. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15096. if (!ctx || !ca_pem) { return false; }
  15097. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15098. // Create new X509_STORE from PEM
  15099. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15100. if (!store) { return false; }
  15101. // SSL_CTX_set_cert_store takes ownership
  15102. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15103. // Set client CA list for client certificate request
  15104. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15105. if (ca_list) {
  15106. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15107. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15108. }
  15109. return true;
  15110. }
  15111. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15112. if (!ctx) { return false; }
  15113. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15114. impl::get_verify_callback() = std::move(callback);
  15115. if (impl::get_verify_callback()) {
  15116. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15117. } else {
  15118. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15119. }
  15120. return true;
  15121. }
  15122. inline long get_verify_error(const_session_t session) {
  15123. if (!session) { return -1; }
  15124. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15125. return SSL_get_verify_result(ssl);
  15126. }
  15127. inline std::string verify_error_string(long error_code) {
  15128. if (error_code == X509_V_OK) { return ""; }
  15129. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15130. return str ? str : "unknown error";
  15131. }
  15132. } // namespace tls
  15133. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15134. /*
  15135. * Group 9: TLS abstraction layer - Mbed TLS backend
  15136. */
  15137. /*
  15138. * Mbed TLS Backend Implementation
  15139. */
  15140. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15141. namespace tls {
  15142. namespace impl {
  15143. // Mbed TLS session wrapper
  15144. struct MbedTlsSession {
  15145. mbedtls_ssl_context ssl;
  15146. socket_t sock = INVALID_SOCKET;
  15147. std::string hostname; // For client: set via set_sni
  15148. std::string sni_hostname; // For server: received from client via SNI callback
  15149. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15150. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15151. MbedTlsSession(const MbedTlsSession &) = delete;
  15152. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15153. };
  15154. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15155. // queue)
  15156. inline int &mbedtls_last_error() {
  15157. static thread_local int err = 0;
  15158. return err;
  15159. }
  15160. // Helper to map Mbed TLS error to ErrorCode
  15161. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15162. if (ret == 0) { return ErrorCode::Success; }
  15163. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15164. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15165. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15166. return ErrorCode::PeerClosed;
  15167. }
  15168. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15169. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15170. out_errno = errno;
  15171. return ErrorCode::SyscallError;
  15172. }
  15173. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15174. return ErrorCode::CertVerifyFailed;
  15175. }
  15176. return ErrorCode::Fatal;
  15177. }
  15178. // BIO-like send callback for Mbed TLS
  15179. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15180. size_t len) {
  15181. auto sock = *static_cast<socket_t *>(ctx);
  15182. #ifdef _WIN32
  15183. auto ret =
  15184. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15185. if (ret == SOCKET_ERROR) {
  15186. int err = WSAGetLastError();
  15187. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15188. return MBEDTLS_ERR_NET_SEND_FAILED;
  15189. }
  15190. #else
  15191. auto ret = send(sock, buf, len, 0);
  15192. if (ret < 0) {
  15193. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15194. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15195. }
  15196. return MBEDTLS_ERR_NET_SEND_FAILED;
  15197. }
  15198. #endif
  15199. return static_cast<int>(ret);
  15200. }
  15201. // BIO-like recv callback for Mbed TLS
  15202. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15203. auto sock = *static_cast<socket_t *>(ctx);
  15204. #ifdef _WIN32
  15205. auto ret =
  15206. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15207. if (ret == SOCKET_ERROR) {
  15208. int err = WSAGetLastError();
  15209. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15210. return MBEDTLS_ERR_NET_RECV_FAILED;
  15211. }
  15212. #else
  15213. auto ret = recv(sock, buf, len, 0);
  15214. if (ret < 0) {
  15215. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15216. return MBEDTLS_ERR_SSL_WANT_READ;
  15217. }
  15218. return MBEDTLS_ERR_NET_RECV_FAILED;
  15219. }
  15220. #endif
  15221. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15222. return static_cast<int>(ret);
  15223. }
  15224. // MbedTlsContext constructor/destructor implementations
  15225. inline MbedTlsContext::MbedTlsContext() {
  15226. mbedtls_ssl_config_init(&conf);
  15227. mbedtls_entropy_init(&entropy);
  15228. mbedtls_ctr_drbg_init(&ctr_drbg);
  15229. mbedtls_x509_crt_init(&ca_chain);
  15230. mbedtls_x509_crt_init(&own_cert);
  15231. mbedtls_pk_init(&own_key);
  15232. }
  15233. inline MbedTlsContext::~MbedTlsContext() {
  15234. mbedtls_pk_free(&own_key);
  15235. mbedtls_x509_crt_free(&own_cert);
  15236. mbedtls_x509_crt_free(&ca_chain);
  15237. mbedtls_ctr_drbg_free(&ctr_drbg);
  15238. mbedtls_entropy_free(&entropy);
  15239. mbedtls_ssl_config_free(&conf);
  15240. }
  15241. // Thread-local storage for SNI captured during handshake
  15242. // This is needed because the SNI callback doesn't have a way to pass
  15243. // session-specific data before the session is fully set up
  15244. inline std::string &mbedpending_sni() {
  15245. static thread_local std::string sni;
  15246. return sni;
  15247. }
  15248. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15249. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15250. const unsigned char *name, size_t name_len) {
  15251. (void)p_ctx;
  15252. (void)ssl;
  15253. // Store SNI name in thread-local storage
  15254. // It will be retrieved and stored in the session after handshake
  15255. if (name && name_len > 0) {
  15256. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15257. } else {
  15258. mbedpending_sni().clear();
  15259. }
  15260. return 0; // Accept any SNI
  15261. }
  15262. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15263. int cert_depth, uint32_t *flags);
  15264. // MbedTLS verify callback wrapper
  15265. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15266. int cert_depth, uint32_t *flags) {
  15267. auto &callback = get_verify_callback();
  15268. if (!callback) { return 0; } // Continue with default verification
  15269. // data points to the MbedTlsSession
  15270. auto *session = static_cast<MbedTlsSession *>(data);
  15271. // Build context
  15272. VerifyContext verify_ctx;
  15273. verify_ctx.session = static_cast<session_t>(session);
  15274. verify_ctx.cert = static_cast<cert_t>(crt);
  15275. verify_ctx.depth = cert_depth;
  15276. verify_ctx.preverify_ok = (*flags == 0);
  15277. verify_ctx.error_code = static_cast<long>(*flags);
  15278. // Convert Mbed TLS flags to error string
  15279. static thread_local char error_buf[256];
  15280. if (*flags != 0) {
  15281. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15282. verify_ctx.error_string = error_buf;
  15283. } else {
  15284. verify_ctx.error_string = nullptr;
  15285. }
  15286. bool accepted = callback(verify_ctx);
  15287. if (accepted) {
  15288. *flags = 0; // Clear all error flags
  15289. return 0;
  15290. }
  15291. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15292. }
  15293. } // namespace impl
  15294. inline ctx_t create_client_context() {
  15295. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15296. if (!ctx) { return nullptr; }
  15297. ctx->is_server = false;
  15298. // Seed the random number generator
  15299. const char *pers = "httplib_client";
  15300. int ret = mbedtls_ctr_drbg_seed(
  15301. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15302. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15303. if (ret != 0) {
  15304. impl::mbedtls_last_error() = ret;
  15305. delete ctx;
  15306. return nullptr;
  15307. }
  15308. // Set up SSL config for client
  15309. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15310. MBEDTLS_SSL_TRANSPORT_STREAM,
  15311. MBEDTLS_SSL_PRESET_DEFAULT);
  15312. if (ret != 0) {
  15313. impl::mbedtls_last_error() = ret;
  15314. delete ctx;
  15315. return nullptr;
  15316. }
  15317. // Set random number generator
  15318. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15319. // Default: verify peer certificate
  15320. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15321. // Set minimum TLS version to 1.2
  15322. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15323. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15324. #else
  15325. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15326. MBEDTLS_SSL_MINOR_VERSION_3);
  15327. #endif
  15328. return static_cast<ctx_t>(ctx);
  15329. }
  15330. inline ctx_t create_server_context() {
  15331. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15332. if (!ctx) { return nullptr; }
  15333. ctx->is_server = true;
  15334. // Seed the random number generator
  15335. const char *pers = "httplib_server";
  15336. int ret = mbedtls_ctr_drbg_seed(
  15337. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15338. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15339. if (ret != 0) {
  15340. impl::mbedtls_last_error() = ret;
  15341. delete ctx;
  15342. return nullptr;
  15343. }
  15344. // Set up SSL config for server
  15345. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15346. MBEDTLS_SSL_TRANSPORT_STREAM,
  15347. MBEDTLS_SSL_PRESET_DEFAULT);
  15348. if (ret != 0) {
  15349. impl::mbedtls_last_error() = ret;
  15350. delete ctx;
  15351. return nullptr;
  15352. }
  15353. // Set random number generator
  15354. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15355. // Default: don't verify client
  15356. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15357. // Set minimum TLS version to 1.2
  15358. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15359. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15360. #else
  15361. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15362. MBEDTLS_SSL_MINOR_VERSION_3);
  15363. #endif
  15364. // Set SNI callback to capture client's SNI hostname
  15365. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15366. return static_cast<ctx_t>(ctx);
  15367. }
  15368. inline void free_context(ctx_t ctx) {
  15369. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15370. }
  15371. inline bool set_min_version(ctx_t ctx, Version version) {
  15372. if (!ctx) { return false; }
  15373. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15374. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15375. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15376. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15377. if (version >= Version::TLS1_3) {
  15378. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15379. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15380. #endif
  15381. }
  15382. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15383. #else
  15384. // Mbed TLS 2.x uses major/minor version numbers
  15385. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15386. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15387. if (version >= Version::TLS1_3) {
  15388. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15389. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15390. #else
  15391. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15392. #endif
  15393. }
  15394. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15395. #endif
  15396. return true;
  15397. }
  15398. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15399. if (!ctx || !pem) { return false; }
  15400. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15401. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15402. // Add null terminator if not present
  15403. std::string pem_str(pem, len);
  15404. int ret = mbedtls_x509_crt_parse(
  15405. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15406. pem_str.size() + 1);
  15407. if (ret != 0) {
  15408. impl::mbedtls_last_error() = ret;
  15409. return false;
  15410. }
  15411. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15412. return true;
  15413. }
  15414. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15415. if (!ctx || !file_path) { return false; }
  15416. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15417. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15418. if (ret != 0) {
  15419. impl::mbedtls_last_error() = ret;
  15420. return false;
  15421. }
  15422. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15423. return true;
  15424. }
  15425. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15426. if (!ctx || !dir_path) { return false; }
  15427. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15428. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15429. if (ret < 0) { // Returns number of certs on success, negative on error
  15430. impl::mbedtls_last_error() = ret;
  15431. return false;
  15432. }
  15433. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15434. return true;
  15435. }
  15436. inline bool load_system_certs(ctx_t ctx) {
  15437. if (!ctx) { return false; }
  15438. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15439. bool loaded = false;
  15440. #ifdef _WIN32
  15441. loaded = impl::enumerate_windows_system_certs(
  15442. [&](const unsigned char *data, size_t len) {
  15443. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15444. });
  15445. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15446. loaded = impl::enumerate_macos_keychain_certs(
  15447. [&](const unsigned char *data, size_t len) {
  15448. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15449. });
  15450. #else
  15451. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15452. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15453. loaded = true;
  15454. break;
  15455. }
  15456. }
  15457. if (!loaded) {
  15458. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15459. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15460. loaded = true;
  15461. break;
  15462. }
  15463. }
  15464. }
  15465. #endif
  15466. if (loaded) {
  15467. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15468. }
  15469. return loaded;
  15470. }
  15471. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15472. const char *password) {
  15473. if (!ctx || !cert || !key) { return false; }
  15474. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15475. // Parse certificate
  15476. std::string cert_str(cert);
  15477. int ret = mbedtls_x509_crt_parse(
  15478. &mctx->own_cert,
  15479. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15480. cert_str.size() + 1);
  15481. if (ret != 0) {
  15482. impl::mbedtls_last_error() = ret;
  15483. return false;
  15484. }
  15485. // Parse private key
  15486. std::string key_str(key);
  15487. const unsigned char *pwd =
  15488. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15489. size_t pwd_len = password ? strlen(password) : 0;
  15490. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15491. ret = mbedtls_pk_parse_key(
  15492. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15493. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15494. &mctx->ctr_drbg);
  15495. #else
  15496. ret = mbedtls_pk_parse_key(
  15497. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15498. key_str.size() + 1, pwd, pwd_len);
  15499. #endif
  15500. if (ret != 0) {
  15501. impl::mbedtls_last_error() = ret;
  15502. return false;
  15503. }
  15504. // Verify that the certificate and private key match
  15505. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15506. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15507. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15508. #else
  15509. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15510. #endif
  15511. if (ret != 0) {
  15512. impl::mbedtls_last_error() = ret;
  15513. return false;
  15514. }
  15515. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15516. if (ret != 0) {
  15517. impl::mbedtls_last_error() = ret;
  15518. return false;
  15519. }
  15520. return true;
  15521. }
  15522. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15523. const char *key_path, const char *password) {
  15524. if (!ctx || !cert_path || !key_path) { return false; }
  15525. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15526. // Parse certificate file
  15527. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15528. if (ret != 0) {
  15529. impl::mbedtls_last_error() = ret;
  15530. return false;
  15531. }
  15532. // Parse private key file
  15533. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15534. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15535. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15536. #else
  15537. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15538. #endif
  15539. if (ret != 0) {
  15540. impl::mbedtls_last_error() = ret;
  15541. return false;
  15542. }
  15543. // Verify that the certificate and private key match
  15544. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15545. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15546. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15547. #else
  15548. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15549. #endif
  15550. if (ret != 0) {
  15551. impl::mbedtls_last_error() = ret;
  15552. return false;
  15553. }
  15554. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15555. if (ret != 0) {
  15556. impl::mbedtls_last_error() = ret;
  15557. return false;
  15558. }
  15559. return true;
  15560. }
  15561. inline void set_verify_client(ctx_t ctx, bool require) {
  15562. if (!ctx) { return; }
  15563. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15564. mctx->verify_client = require;
  15565. if (require) {
  15566. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15567. } else {
  15568. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15569. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15570. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15571. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15572. : MBEDTLS_SSL_VERIFY_NONE);
  15573. }
  15574. }
  15575. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15576. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15577. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15578. auto session = new (std::nothrow) impl::MbedTlsSession();
  15579. if (!session) { return nullptr; }
  15580. session->sock = sock;
  15581. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15582. if (ret != 0) {
  15583. impl::mbedtls_last_error() = ret;
  15584. delete session;
  15585. return nullptr;
  15586. }
  15587. // Explicitly opt out of in-handshake hostname verification by default;
  15588. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15589. // fails outright when no hostname was set. set_sni() installs the real
  15590. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15591. // caller verifies the certificate identity post-handshake via
  15592. // verify_hostname().
  15593. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15594. // Set BIO callbacks
  15595. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15596. impl::mbedtls_net_recv_cb, nullptr);
  15597. // Set per-session verify callback with session pointer if callback is
  15598. // registered
  15599. if (mctx->has_verify_callback) {
  15600. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15601. session);
  15602. }
  15603. return static_cast<session_t>(session);
  15604. }
  15605. inline void free_session(session_t session) {
  15606. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15607. }
  15608. inline bool set_sni(session_t session, const char *hostname) {
  15609. if (!session || !hostname) { return false; }
  15610. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15611. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15612. if (ret != 0) {
  15613. impl::mbedtls_last_error() = ret;
  15614. return false;
  15615. }
  15616. msession->hostname = hostname;
  15617. return true;
  15618. }
  15619. inline bool set_hostname(session_t session, const char *hostname) {
  15620. // In Mbed TLS, set_hostname also sets up hostname verification
  15621. return set_sni(session, hostname);
  15622. }
  15623. inline TlsError connect(session_t session) {
  15624. TlsError err;
  15625. if (!session) {
  15626. err.code = ErrorCode::Fatal;
  15627. return err;
  15628. }
  15629. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15630. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15631. if (ret == 0) {
  15632. err.code = ErrorCode::Success;
  15633. } else {
  15634. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15635. err.backend_code = static_cast<uint64_t>(-ret);
  15636. impl::mbedtls_last_error() = ret;
  15637. }
  15638. return err;
  15639. }
  15640. inline TlsError accept(session_t session) {
  15641. // Same as connect for Mbed TLS - handshake works for both client and server
  15642. auto result = connect(session);
  15643. // After successful handshake, capture SNI from thread-local storage
  15644. if (result.code == ErrorCode::Success && session) {
  15645. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15646. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15647. impl::mbedpending_sni().clear();
  15648. }
  15649. return result;
  15650. }
  15651. inline bool connect_nonblocking(session_t session, socket_t sock,
  15652. time_t timeout_sec, time_t timeout_usec,
  15653. TlsError *err) {
  15654. if (!session) {
  15655. if (err) { err->code = ErrorCode::Fatal; }
  15656. return false;
  15657. }
  15658. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15659. // Set socket to non-blocking mode
  15660. detail::set_nonblocking(sock, true);
  15661. auto cleanup =
  15662. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15663. int ret;
  15664. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15665. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15666. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15667. continue;
  15668. }
  15669. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15670. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15671. continue;
  15672. }
  15673. }
  15674. // TlsError or timeout
  15675. if (err) {
  15676. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15677. err->backend_code = static_cast<uint64_t>(-ret);
  15678. }
  15679. impl::mbedtls_last_error() = ret;
  15680. return false;
  15681. }
  15682. if (err) { err->code = ErrorCode::Success; }
  15683. return true;
  15684. }
  15685. inline bool accept_nonblocking(session_t session, socket_t sock,
  15686. time_t timeout_sec, time_t timeout_usec,
  15687. TlsError *err) {
  15688. // Same implementation as connect for Mbed TLS
  15689. bool result =
  15690. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15691. // After successful handshake, capture SNI from thread-local storage
  15692. if (result && session) {
  15693. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15694. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15695. impl::mbedpending_sni().clear();
  15696. }
  15697. return result;
  15698. }
  15699. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15700. if (!session || !buf) {
  15701. err.code = ErrorCode::Fatal;
  15702. return -1;
  15703. }
  15704. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15705. int ret =
  15706. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15707. if (ret > 0) {
  15708. err.code = ErrorCode::Success;
  15709. return static_cast<ssize_t>(ret);
  15710. }
  15711. if (ret == 0) {
  15712. err.code = ErrorCode::PeerClosed;
  15713. return 0;
  15714. }
  15715. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15716. err.backend_code = static_cast<uint64_t>(-ret);
  15717. impl::mbedtls_last_error() = ret;
  15718. // mbedTLS signals a clean close_notify via a negative error code rather
  15719. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15720. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15721. return -1;
  15722. }
  15723. inline ssize_t write(session_t session, const void *buf, size_t len,
  15724. TlsError &err) {
  15725. if (!session || !buf) {
  15726. err.code = ErrorCode::Fatal;
  15727. return -1;
  15728. }
  15729. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15730. int ret = mbedtls_ssl_write(&msession->ssl,
  15731. static_cast<const unsigned char *>(buf), len);
  15732. if (ret > 0) {
  15733. err.code = ErrorCode::Success;
  15734. return static_cast<ssize_t>(ret);
  15735. }
  15736. if (ret == 0) {
  15737. err.code = ErrorCode::PeerClosed;
  15738. return 0;
  15739. }
  15740. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15741. err.backend_code = static_cast<uint64_t>(-ret);
  15742. impl::mbedtls_last_error() = ret;
  15743. return -1;
  15744. }
  15745. inline int pending(const_session_t session) {
  15746. if (!session) { return 0; }
  15747. auto msession =
  15748. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15749. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15750. }
  15751. inline void shutdown(session_t session, bool graceful) {
  15752. if (!session) { return; }
  15753. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15754. if (graceful) {
  15755. // Try to send close_notify, but don't block forever
  15756. int ret;
  15757. int attempts = 0;
  15758. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15759. attempts < 3) {
  15760. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15761. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15762. break;
  15763. }
  15764. attempts++;
  15765. }
  15766. }
  15767. }
  15768. inline bool is_peer_closed(session_t session, socket_t sock) {
  15769. if (!session || sock == INVALID_SOCKET) { return true; }
  15770. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15771. // Check if there's already decrypted data available in the TLS buffer
  15772. // If so, the connection is definitely alive
  15773. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15774. // Set socket to non-blocking to avoid blocking on read
  15775. detail::set_nonblocking(sock, true);
  15776. auto cleanup =
  15777. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15778. // Try a 1-byte read to check connection status
  15779. // Note: This will consume the byte if data is available, but for the
  15780. // purpose of checking if peer is closed, this should be acceptable
  15781. // since we're only called when we expect the connection might be closing
  15782. unsigned char buf;
  15783. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15784. // If we got data or WANT_READ (would block), connection is alive
  15785. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15786. // If we get a peer close notify or a connection reset, the peer is closed
  15787. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15788. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15789. }
  15790. inline cert_t get_peer_cert(const_session_t session) {
  15791. if (!session) { return nullptr; }
  15792. auto msession =
  15793. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15794. // Mbed TLS returns a pointer to the internal peer cert chain.
  15795. // WARNING: This pointer is only valid while the session is active.
  15796. // Do not use the certificate after calling free_session().
  15797. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15798. return const_cast<mbedtls_x509_crt *>(cert);
  15799. }
  15800. inline void free_cert(cert_t cert) {
  15801. // Mbed TLS: peer certificate is owned by the SSL context.
  15802. // No-op here, but callers should still call this for cross-backend
  15803. // portability.
  15804. (void)cert;
  15805. }
  15806. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15807. if (!cert || !hostname) { return false; }
  15808. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15809. std::string host_str(hostname);
  15810. // Check if hostname is an IP address (IPv4 or IPv6)
  15811. unsigned char ip_bytes[16];
  15812. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15813. auto is_ip = ip_len > 0;
  15814. // Check Subject Alternative Names (SAN)
  15815. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15816. // - DNS names: raw string bytes
  15817. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15818. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15819. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15820. const unsigned char *p = san->buf.p;
  15821. size_t len = san->buf.len;
  15822. if (is_ip) {
  15823. // For an IP host, only a matching iPAddress SAN of the same family
  15824. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15825. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15826. } else {
  15827. // Check if this SAN is a DNS name (printable ASCII string)
  15828. bool is_dns = len > 0;
  15829. for (size_t i = 0; i < len && is_dns; i++) {
  15830. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15831. }
  15832. if (is_dns) {
  15833. std::string san_name(reinterpret_cast<const char *>(p), len);
  15834. if (detail::match_hostname(san_name, host_str)) { return true; }
  15835. }
  15836. }
  15837. san = san->next;
  15838. }
  15839. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15840. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15841. // the OpenSSL backend's X509_check_ip behaves the same way).
  15842. if (!is_ip) {
  15843. char cn[256];
  15844. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15845. if (ret > 0) {
  15846. std::string cn_str(cn);
  15847. // Look for "CN=" in the DN string
  15848. size_t cn_pos = cn_str.find("CN=");
  15849. if (cn_pos != std::string::npos) {
  15850. size_t start = cn_pos + 3;
  15851. size_t end = cn_str.find(',', start);
  15852. std::string cn_value =
  15853. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15854. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15855. }
  15856. }
  15857. }
  15858. return false;
  15859. }
  15860. inline uint64_t hostname_mismatch_code() {
  15861. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15862. }
  15863. inline long get_verify_result(const_session_t session) {
  15864. if (!session) { return -1; }
  15865. auto msession =
  15866. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15867. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15868. // Return 0 (X509_V_OK equivalent) if verification passed
  15869. return flags == 0 ? 0 : static_cast<long>(flags);
  15870. }
  15871. inline std::string get_cert_subject_cn(cert_t cert) {
  15872. if (!cert) return "";
  15873. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15874. // Find the CN in the subject
  15875. const mbedtls_x509_name *name = &x509->subject;
  15876. while (name != nullptr) {
  15877. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15878. return std::string(reinterpret_cast<const char *>(name->val.p),
  15879. name->val.len);
  15880. }
  15881. name = name->next;
  15882. }
  15883. return "";
  15884. }
  15885. inline std::string get_cert_issuer_name(cert_t cert) {
  15886. if (!cert) return "";
  15887. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15888. // Build a human-readable issuer name string
  15889. char buf[512];
  15890. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15891. if (ret < 0) return "";
  15892. return std::string(buf);
  15893. }
  15894. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15895. sans.clear();
  15896. if (!cert) return false;
  15897. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15898. // Parse the Subject Alternative Name extension
  15899. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15900. while (cur != nullptr) {
  15901. if (cur->buf.len > 0) {
  15902. // Mbed TLS stores SAN as ASN.1 sequences
  15903. // The tag byte indicates the type
  15904. const unsigned char *p = cur->buf.p;
  15905. size_t len = cur->buf.len;
  15906. // First byte is the tag
  15907. unsigned char tag = *p;
  15908. p++;
  15909. len--;
  15910. // Parse length (simple single-byte length assumed)
  15911. if (len > 0 && *p < 0x80) {
  15912. size_t value_len = *p;
  15913. p++;
  15914. len--;
  15915. if (value_len <= len) {
  15916. SanEntry entry;
  15917. // ASN.1 context tags for GeneralName
  15918. switch (tag & 0x1F) {
  15919. case 2: // dNSName
  15920. entry.type = SanType::DNS;
  15921. entry.value =
  15922. std::string(reinterpret_cast<const char *>(p), value_len);
  15923. break;
  15924. case 7: // iPAddress
  15925. entry.type = SanType::IP;
  15926. if (value_len == 4) {
  15927. // IPv4
  15928. char buf[16];
  15929. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15930. entry.value = buf;
  15931. } else if (value_len == 16) {
  15932. // IPv6
  15933. char buf[64];
  15934. snprintf(buf, sizeof(buf),
  15935. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15936. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15937. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15938. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15939. entry.value = buf;
  15940. }
  15941. break;
  15942. case 1: // rfc822Name (email)
  15943. entry.type = SanType::EMAIL;
  15944. entry.value =
  15945. std::string(reinterpret_cast<const char *>(p), value_len);
  15946. break;
  15947. case 6: // uniformResourceIdentifier
  15948. entry.type = SanType::URI;
  15949. entry.value =
  15950. std::string(reinterpret_cast<const char *>(p), value_len);
  15951. break;
  15952. default: entry.type = SanType::OTHER; break;
  15953. }
  15954. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15955. }
  15956. }
  15957. }
  15958. cur = cur->next;
  15959. }
  15960. return true;
  15961. }
  15962. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15963. time_t &not_after) {
  15964. if (!cert) return false;
  15965. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15966. // Convert mbedtls_x509_time to time_t
  15967. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15968. struct tm tm_time = {};
  15969. tm_time.tm_year = t.year - 1900;
  15970. tm_time.tm_mon = t.mon - 1;
  15971. tm_time.tm_mday = t.day;
  15972. tm_time.tm_hour = t.hour;
  15973. tm_time.tm_min = t.min;
  15974. tm_time.tm_sec = t.sec;
  15975. #ifdef _WIN32
  15976. return _mkgmtime(&tm_time);
  15977. #else
  15978. return timegm(&tm_time);
  15979. #endif
  15980. };
  15981. not_before = to_time_t(x509->valid_from);
  15982. not_after = to_time_t(x509->valid_to);
  15983. return true;
  15984. }
  15985. inline std::string get_cert_serial(cert_t cert) {
  15986. if (!cert) return "";
  15987. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15988. // Convert serial number to hex string
  15989. std::string result;
  15990. result.reserve(x509->serial.len * 2);
  15991. for (size_t i = 0; i < x509->serial.len; i++) {
  15992. char hex[3];
  15993. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15994. result += hex;
  15995. }
  15996. return result;
  15997. }
  15998. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15999. if (!cert) return false;
  16000. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16001. if (!crt->raw.p || crt->raw.len == 0) return false;
  16002. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16003. return true;
  16004. }
  16005. inline const char *get_sni(const_session_t session) {
  16006. if (!session) return nullptr;
  16007. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16008. // For server: return SNI received from client during handshake
  16009. if (!msession->sni_hostname.empty()) {
  16010. return msession->sni_hostname.c_str();
  16011. }
  16012. // For client: return the hostname set via set_sni
  16013. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16014. return nullptr;
  16015. }
  16016. inline uint64_t peek_error() {
  16017. // Mbed TLS doesn't have an error queue, return the last error
  16018. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16019. }
  16020. inline uint64_t get_error() {
  16021. // Mbed TLS doesn't have an error queue, return and clear the last error
  16022. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16023. impl::mbedtls_last_error() = 0;
  16024. return err;
  16025. }
  16026. inline std::string error_string(uint64_t code) {
  16027. char buf[256];
  16028. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16029. return std::string(buf);
  16030. }
  16031. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16032. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16033. if (!ca_chain) { return nullptr; }
  16034. mbedtls_x509_crt_init(ca_chain);
  16035. // mbedtls_x509_crt_parse expects null-terminated PEM
  16036. int ret = mbedtls_x509_crt_parse(ca_chain,
  16037. reinterpret_cast<const unsigned char *>(pem),
  16038. len + 1); // +1 for null terminator
  16039. if (ret != 0) {
  16040. // Try without +1 in case PEM is already null-terminated
  16041. ret = mbedtls_x509_crt_parse(
  16042. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16043. if (ret != 0) {
  16044. mbedtls_x509_crt_free(ca_chain);
  16045. delete ca_chain;
  16046. return nullptr;
  16047. }
  16048. }
  16049. return static_cast<ca_store_t>(ca_chain);
  16050. }
  16051. inline void free_ca_store(ca_store_t store) {
  16052. if (store) {
  16053. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16054. mbedtls_x509_crt_free(ca_chain);
  16055. delete ca_chain;
  16056. }
  16057. }
  16058. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16059. if (!ctx || !store) { return false; }
  16060. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16061. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16062. // Free existing CA chain
  16063. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16064. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16065. // Copy the CA chain (deep copy)
  16066. // Parse from the raw data of the source cert
  16067. mbedtls_x509_crt *src = ca_chain;
  16068. while (src != nullptr) {
  16069. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16070. src->raw.len);
  16071. if (ret != 0) {
  16072. free_ca_store(store);
  16073. return false;
  16074. }
  16075. src = src->next;
  16076. }
  16077. // This function takes ownership of the store; the chain was deep-copied
  16078. // above, so release the source
  16079. free_ca_store(store);
  16080. // Update the SSL config to use the new CA chain
  16081. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16082. return true;
  16083. }
  16084. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16085. certs.clear();
  16086. if (!ctx) { return 0; }
  16087. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16088. // Iterate through the CA chain
  16089. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16090. while (cert != nullptr && cert->raw.len > 0) {
  16091. // Create a copy of the certificate for the caller
  16092. auto *copy = new mbedtls_x509_crt;
  16093. mbedtls_x509_crt_init(copy);
  16094. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16095. if (ret == 0) {
  16096. certs.push_back(static_cast<cert_t>(copy));
  16097. } else {
  16098. mbedtls_x509_crt_free(copy);
  16099. delete copy;
  16100. }
  16101. cert = cert->next;
  16102. }
  16103. return certs.size();
  16104. }
  16105. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16106. std::vector<std::string> names;
  16107. if (!ctx) { return names; }
  16108. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16109. // Iterate through the CA chain
  16110. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16111. while (cert != nullptr && cert->raw.len > 0) {
  16112. char buf[512];
  16113. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16114. if (ret > 0) { names.push_back(buf); }
  16115. cert = cert->next;
  16116. }
  16117. return names;
  16118. }
  16119. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16120. const char *key_pem, const char *password) {
  16121. if (!ctx || !cert_pem || !key_pem) { return false; }
  16122. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16123. // Free existing certificate and key
  16124. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16125. mbedtls_pk_free(&mbed_ctx->own_key);
  16126. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16127. mbedtls_pk_init(&mbed_ctx->own_key);
  16128. // Parse certificate PEM
  16129. int ret = mbedtls_x509_crt_parse(
  16130. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16131. strlen(cert_pem) + 1);
  16132. if (ret != 0) {
  16133. impl::mbedtls_last_error() = ret;
  16134. return false;
  16135. }
  16136. // Parse private key PEM
  16137. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16138. ret = mbedtls_pk_parse_key(
  16139. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16140. strlen(key_pem) + 1,
  16141. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16142. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16143. &mbed_ctx->ctr_drbg);
  16144. #else
  16145. ret = mbedtls_pk_parse_key(
  16146. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16147. strlen(key_pem) + 1,
  16148. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16149. password ? strlen(password) : 0);
  16150. #endif
  16151. if (ret != 0) {
  16152. impl::mbedtls_last_error() = ret;
  16153. return false;
  16154. }
  16155. // Configure SSL to use the new certificate and key
  16156. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16157. &mbed_ctx->own_key);
  16158. if (ret != 0) {
  16159. impl::mbedtls_last_error() = ret;
  16160. return false;
  16161. }
  16162. return true;
  16163. }
  16164. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16165. if (!ctx || !ca_pem) { return false; }
  16166. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16167. // Free existing CA chain
  16168. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16169. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16170. // Parse CA PEM
  16171. int ret = mbedtls_x509_crt_parse(
  16172. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16173. strlen(ca_pem) + 1);
  16174. if (ret != 0) {
  16175. impl::mbedtls_last_error() = ret;
  16176. return false;
  16177. }
  16178. // Update SSL config to use new CA chain
  16179. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16180. return true;
  16181. }
  16182. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16183. if (!ctx) { return false; }
  16184. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16185. impl::get_verify_callback() = std::move(callback);
  16186. mbed_ctx->has_verify_callback =
  16187. static_cast<bool>(impl::get_verify_callback());
  16188. if (mbed_ctx->has_verify_callback) {
  16189. // Set OPTIONAL mode to ensure callback is called even when verification
  16190. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16191. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16192. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16193. nullptr);
  16194. } else {
  16195. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16196. }
  16197. return true;
  16198. }
  16199. inline long get_verify_error(const_session_t session) {
  16200. if (!session) { return -1; }
  16201. auto *msession =
  16202. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16203. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16204. }
  16205. inline std::string verify_error_string(long error_code) {
  16206. if (error_code == 0) { return ""; }
  16207. char buf[256];
  16208. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16209. static_cast<uint32_t>(error_code));
  16210. // Remove trailing newline if present
  16211. std::string result(buf);
  16212. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16213. result.pop_back();
  16214. }
  16215. return result;
  16216. }
  16217. } // namespace tls
  16218. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16219. /*
  16220. * Group 10: TLS abstraction layer - wolfSSL backend
  16221. */
  16222. /*
  16223. * wolfSSL Backend Implementation
  16224. */
  16225. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16226. namespace tls {
  16227. namespace impl {
  16228. // wolfSSL session wrapper
  16229. struct WolfSSLSession {
  16230. WOLFSSL *ssl = nullptr;
  16231. socket_t sock = INVALID_SOCKET;
  16232. std::string hostname; // For client: set via set_sni
  16233. std::string sni_hostname; // For server: received from client via SNI callback
  16234. WolfSSLSession() = default;
  16235. ~WolfSSLSession() {
  16236. if (ssl) { wolfSSL_free(ssl); }
  16237. }
  16238. WolfSSLSession(const WolfSSLSession &) = delete;
  16239. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16240. };
  16241. // Thread-local error code accessor for wolfSSL
  16242. inline uint64_t &wolfssl_last_error() {
  16243. static thread_local uint64_t err = 0;
  16244. return err;
  16245. }
  16246. // Helper to map wolfSSL error to ErrorCode.
  16247. // ssl_error is the value from wolfSSL_get_error().
  16248. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16249. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16250. int &out_errno) {
  16251. switch (ssl_error) {
  16252. case SSL_ERROR_NONE: return ErrorCode::Success;
  16253. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16254. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16255. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16256. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16257. default:
  16258. if (ssl) {
  16259. // wolfSSL stores the low-level error code as a negative value.
  16260. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16261. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16262. if (low_err == DOMAIN_NAME_MISMATCH) {
  16263. return ErrorCode::HostnameMismatch;
  16264. }
  16265. // Check verify result to distinguish cert verification from generic SSL
  16266. // errors.
  16267. long vr = wolfSSL_get_verify_result(ssl);
  16268. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16269. }
  16270. return ErrorCode::Fatal;
  16271. }
  16272. }
  16273. // WolfSSLContext constructor/destructor implementations
  16274. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16275. inline WolfSSLContext::~WolfSSLContext() {
  16276. if (ctx) { wolfSSL_CTX_free(ctx); }
  16277. }
  16278. // Thread-local storage for SNI captured during handshake
  16279. inline std::string &wolfssl_pending_sni() {
  16280. static thread_local std::string sni;
  16281. return sni;
  16282. }
  16283. // SNI callback for wolfSSL server to capture client's SNI hostname
  16284. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16285. (void)ret;
  16286. (void)exArg;
  16287. void *name_data = nullptr;
  16288. unsigned short name_len =
  16289. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16290. if (name_data && name_len > 0) {
  16291. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16292. name_len);
  16293. } else {
  16294. wolfssl_pending_sni().clear();
  16295. }
  16296. return 0; // Continue regardless
  16297. }
  16298. // wolfSSL verify callback wrapper
  16299. inline int wolfssl_verify_callback(int preverify_ok,
  16300. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16301. auto &callback = get_verify_callback();
  16302. if (!callback) { return preverify_ok; }
  16303. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16304. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16305. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16306. // Get the WOLFSSL object from the X509_STORE_CTX
  16307. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16308. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16309. VerifyContext verify_ctx;
  16310. verify_ctx.session = static_cast<session_t>(ssl);
  16311. verify_ctx.cert = static_cast<cert_t>(cert);
  16312. verify_ctx.depth = depth;
  16313. verify_ctx.preverify_ok = (preverify_ok != 0);
  16314. verify_ctx.error_code = static_cast<long>(err);
  16315. if (err != 0) {
  16316. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16317. } else {
  16318. verify_ctx.error_string = nullptr;
  16319. }
  16320. bool accepted = callback(verify_ctx);
  16321. return accepted ? 1 : 0;
  16322. }
  16323. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16324. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16325. wolfSSL_CTX_set_default_passwd_cb(
  16326. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16327. auto *pwd = static_cast<const char *>(userdata);
  16328. if (!pwd) return 0;
  16329. auto len = static_cast<int>(strlen(pwd));
  16330. if (len > size) len = size;
  16331. memcpy(buf, pwd, static_cast<size_t>(len));
  16332. return len;
  16333. });
  16334. }
  16335. } // namespace impl
  16336. inline ctx_t create_client_context() {
  16337. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16338. if (!ctx) { return nullptr; }
  16339. ctx->is_server = false;
  16340. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16341. if (!method) {
  16342. delete ctx;
  16343. return nullptr;
  16344. }
  16345. ctx->ctx = wolfSSL_CTX_new(method);
  16346. if (!ctx->ctx) {
  16347. delete ctx;
  16348. return nullptr;
  16349. }
  16350. // Default: verify peer certificate
  16351. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16352. return static_cast<ctx_t>(ctx);
  16353. }
  16354. inline ctx_t create_server_context() {
  16355. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16356. if (!ctx) { return nullptr; }
  16357. ctx->is_server = true;
  16358. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16359. if (!method) {
  16360. delete ctx;
  16361. return nullptr;
  16362. }
  16363. ctx->ctx = wolfSSL_CTX_new(method);
  16364. if (!ctx->ctx) {
  16365. delete ctx;
  16366. return nullptr;
  16367. }
  16368. // Default: don't verify client
  16369. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16370. // Enable SNI on server
  16371. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16372. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16373. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16374. return static_cast<ctx_t>(ctx);
  16375. }
  16376. inline void free_context(ctx_t ctx) {
  16377. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16378. }
  16379. inline bool set_min_version(ctx_t ctx, Version version) {
  16380. if (!ctx) { return false; }
  16381. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16382. int min_ver = WOLFSSL_TLSV1_2;
  16383. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16384. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16385. }
  16386. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16387. if (!ctx || !pem) { return false; }
  16388. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16389. int ret = wolfSSL_CTX_load_verify_buffer(
  16390. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16391. static_cast<long>(len), SSL_FILETYPE_PEM);
  16392. if (ret != SSL_SUCCESS) {
  16393. impl::wolfssl_last_error() =
  16394. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16395. return false;
  16396. }
  16397. wctx->ca_pem_data_.append(pem, len);
  16398. return true;
  16399. }
  16400. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16401. if (!ctx || !file_path) { return false; }
  16402. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16403. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16404. if (ret != SSL_SUCCESS) {
  16405. impl::wolfssl_last_error() =
  16406. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16407. return false;
  16408. }
  16409. return true;
  16410. }
  16411. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16412. if (!ctx || !dir_path) { return false; }
  16413. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16414. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16415. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16416. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16417. // immediately. Return true even on failure since the CA file may have
  16418. // already been loaded, matching OpenSSL's lenient behavior.
  16419. (void)ret;
  16420. return true;
  16421. }
  16422. inline bool load_system_certs(ctx_t ctx) {
  16423. if (!ctx) { return false; }
  16424. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16425. bool loaded = false;
  16426. #ifdef _WIN32
  16427. loaded = impl::enumerate_windows_system_certs(
  16428. [&](const unsigned char *data, size_t len) {
  16429. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16430. static_cast<long>(len),
  16431. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16432. });
  16433. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16434. loaded = impl::enumerate_macos_keychain_certs(
  16435. [&](const unsigned char *data, size_t len) {
  16436. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16437. static_cast<long>(len),
  16438. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16439. });
  16440. #else
  16441. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16442. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16443. SSL_SUCCESS) {
  16444. loaded = true;
  16445. break;
  16446. }
  16447. }
  16448. if (!loaded) {
  16449. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16450. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16451. SSL_SUCCESS) {
  16452. loaded = true;
  16453. break;
  16454. }
  16455. }
  16456. }
  16457. #endif
  16458. return loaded;
  16459. }
  16460. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16461. const char *password) {
  16462. if (!ctx || !cert || !key) { return false; }
  16463. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16464. // Load certificate
  16465. int ret = wolfSSL_CTX_use_certificate_buffer(
  16466. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16467. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16468. if (ret != SSL_SUCCESS) {
  16469. impl::wolfssl_last_error() =
  16470. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16471. return false;
  16472. }
  16473. // Set password callback if password is provided
  16474. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16475. // Load private key
  16476. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16477. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16478. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16479. if (ret != SSL_SUCCESS) {
  16480. impl::wolfssl_last_error() =
  16481. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16482. return false;
  16483. }
  16484. // Verify that the certificate and private key match
  16485. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16486. }
  16487. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16488. const char *key_path, const char *password) {
  16489. if (!ctx || !cert_path || !key_path) { return false; }
  16490. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16491. // Load certificate file
  16492. int ret =
  16493. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16494. if (ret != SSL_SUCCESS) {
  16495. impl::wolfssl_last_error() =
  16496. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16497. return false;
  16498. }
  16499. // Set password callback if password is provided
  16500. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16501. // Load private key file
  16502. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16503. if (ret != SSL_SUCCESS) {
  16504. impl::wolfssl_last_error() =
  16505. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16506. return false;
  16507. }
  16508. // Verify that the certificate and private key match
  16509. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16510. }
  16511. inline void set_verify_client(ctx_t ctx, bool require) {
  16512. if (!ctx) { return; }
  16513. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16514. wctx->verify_client = require;
  16515. if (require) {
  16516. wolfSSL_CTX_set_verify(
  16517. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16518. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16519. } else {
  16520. if (wctx->has_verify_callback) {
  16521. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16522. impl::wolfssl_verify_callback);
  16523. } else {
  16524. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16525. }
  16526. }
  16527. }
  16528. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16529. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16530. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16531. auto session = new (std::nothrow) impl::WolfSSLSession();
  16532. if (!session) { return nullptr; }
  16533. session->sock = sock;
  16534. session->ssl = wolfSSL_new(wctx->ctx);
  16535. if (!session->ssl) {
  16536. impl::wolfssl_last_error() =
  16537. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16538. delete session;
  16539. return nullptr;
  16540. }
  16541. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16542. return static_cast<session_t>(session);
  16543. }
  16544. inline void free_session(session_t session) {
  16545. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16546. }
  16547. inline bool set_sni(session_t session, const char *hostname) {
  16548. if (!session || !hostname) { return false; }
  16549. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16550. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16551. static_cast<word16>(strlen(hostname)));
  16552. if (ret != WOLFSSL_SUCCESS) {
  16553. impl::wolfssl_last_error() =
  16554. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16555. return false;
  16556. }
  16557. // Also set hostname for verification
  16558. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16559. wsession->hostname = hostname;
  16560. return true;
  16561. }
  16562. inline bool set_hostname(session_t session, const char *hostname) {
  16563. // In wolfSSL, set_hostname also sets up hostname verification
  16564. return set_sni(session, hostname);
  16565. }
  16566. inline TlsError connect(session_t session) {
  16567. TlsError err;
  16568. if (!session) {
  16569. err.code = ErrorCode::Fatal;
  16570. return err;
  16571. }
  16572. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16573. int ret = wolfSSL_connect(wsession->ssl);
  16574. if (ret == SSL_SUCCESS) {
  16575. err.code = ErrorCode::Success;
  16576. } else {
  16577. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16578. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16579. err.backend_code = static_cast<uint64_t>(ssl_error);
  16580. impl::wolfssl_last_error() = err.backend_code;
  16581. }
  16582. return err;
  16583. }
  16584. inline TlsError accept(session_t session) {
  16585. TlsError err;
  16586. if (!session) {
  16587. err.code = ErrorCode::Fatal;
  16588. return err;
  16589. }
  16590. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16591. int ret = wolfSSL_accept(wsession->ssl);
  16592. if (ret == SSL_SUCCESS) {
  16593. err.code = ErrorCode::Success;
  16594. // Capture SNI from thread-local storage after successful handshake
  16595. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16596. impl::wolfssl_pending_sni().clear();
  16597. } else {
  16598. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16599. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16600. err.backend_code = static_cast<uint64_t>(ssl_error);
  16601. impl::wolfssl_last_error() = err.backend_code;
  16602. }
  16603. return err;
  16604. }
  16605. inline bool connect_nonblocking(session_t session, socket_t sock,
  16606. time_t timeout_sec, time_t timeout_usec,
  16607. TlsError *err) {
  16608. if (!session) {
  16609. if (err) { err->code = ErrorCode::Fatal; }
  16610. return false;
  16611. }
  16612. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16613. // Set socket to non-blocking mode
  16614. detail::set_nonblocking(sock, true);
  16615. auto cleanup =
  16616. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16617. int ret;
  16618. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16619. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16620. if (ssl_error == SSL_ERROR_WANT_READ) {
  16621. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16622. continue;
  16623. }
  16624. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16625. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16626. continue;
  16627. }
  16628. }
  16629. // Error or timeout
  16630. if (err) {
  16631. err->code =
  16632. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16633. err->backend_code = static_cast<uint64_t>(ssl_error);
  16634. }
  16635. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16636. return false;
  16637. }
  16638. if (err) { err->code = ErrorCode::Success; }
  16639. return true;
  16640. }
  16641. inline bool accept_nonblocking(session_t session, socket_t sock,
  16642. time_t timeout_sec, time_t timeout_usec,
  16643. TlsError *err) {
  16644. if (!session) {
  16645. if (err) { err->code = ErrorCode::Fatal; }
  16646. return false;
  16647. }
  16648. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16649. // Set socket to non-blocking mode
  16650. detail::set_nonblocking(sock, true);
  16651. auto cleanup =
  16652. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16653. int ret;
  16654. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16655. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16656. if (ssl_error == SSL_ERROR_WANT_READ) {
  16657. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16658. continue;
  16659. }
  16660. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16661. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16662. continue;
  16663. }
  16664. }
  16665. // Error or timeout
  16666. if (err) {
  16667. err->code =
  16668. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16669. err->backend_code = static_cast<uint64_t>(ssl_error);
  16670. }
  16671. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16672. return false;
  16673. }
  16674. if (err) { err->code = ErrorCode::Success; }
  16675. // Capture SNI from thread-local storage after successful handshake
  16676. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16677. impl::wolfssl_pending_sni().clear();
  16678. return true;
  16679. }
  16680. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16681. if (!session || !buf) {
  16682. err.code = ErrorCode::Fatal;
  16683. return -1;
  16684. }
  16685. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16686. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16687. if (ret > 0) {
  16688. err.code = ErrorCode::Success;
  16689. return static_cast<ssize_t>(ret);
  16690. }
  16691. if (ret == 0) {
  16692. err.code = ErrorCode::PeerClosed;
  16693. return 0;
  16694. }
  16695. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16696. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16697. err.backend_code = static_cast<uint64_t>(ssl_error);
  16698. impl::wolfssl_last_error() = err.backend_code;
  16699. return -1;
  16700. }
  16701. inline ssize_t write(session_t session, const void *buf, size_t len,
  16702. TlsError &err) {
  16703. if (!session || !buf) {
  16704. err.code = ErrorCode::Fatal;
  16705. return -1;
  16706. }
  16707. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16708. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16709. if (ret > 0) {
  16710. err.code = ErrorCode::Success;
  16711. return static_cast<ssize_t>(ret);
  16712. }
  16713. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16714. // Treat this as an error (return -1) so callers don't spin in a
  16715. // write loop adding zero to the offset.
  16716. if (ret == 0) {
  16717. err.code = ErrorCode::PeerClosed;
  16718. return -1;
  16719. }
  16720. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16721. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16722. err.backend_code = static_cast<uint64_t>(ssl_error);
  16723. impl::wolfssl_last_error() = err.backend_code;
  16724. return -1;
  16725. }
  16726. inline int pending(const_session_t session) {
  16727. if (!session) { return 0; }
  16728. auto wsession =
  16729. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16730. return wolfSSL_pending(wsession->ssl);
  16731. }
  16732. inline void shutdown(session_t session, bool graceful) {
  16733. if (!session) { return; }
  16734. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16735. if (graceful) {
  16736. int ret;
  16737. int attempts = 0;
  16738. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16739. attempts < 3) {
  16740. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16741. if (ssl_error != SSL_ERROR_WANT_READ &&
  16742. ssl_error != SSL_ERROR_WANT_WRITE) {
  16743. break;
  16744. }
  16745. attempts++;
  16746. }
  16747. } else {
  16748. wolfSSL_shutdown(wsession->ssl);
  16749. }
  16750. }
  16751. inline bool is_peer_closed(session_t session, socket_t sock) {
  16752. if (!session || sock == INVALID_SOCKET) { return true; }
  16753. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16754. // Check if there's already decrypted data available
  16755. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16756. // Set socket to non-blocking to avoid blocking on read
  16757. detail::set_nonblocking(sock, true);
  16758. auto cleanup =
  16759. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16760. // Peek 1 byte to check connection status without consuming data
  16761. unsigned char buf;
  16762. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16763. // If we got data or WANT_READ (would block), connection is alive
  16764. if (ret > 0) { return false; }
  16765. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16766. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16767. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16768. ret == 0;
  16769. }
  16770. inline cert_t get_peer_cert(const_session_t session) {
  16771. if (!session) { return nullptr; }
  16772. auto wsession =
  16773. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16774. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16775. return static_cast<cert_t>(cert);
  16776. }
  16777. inline void free_cert(cert_t cert) {
  16778. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16779. }
  16780. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16781. if (!cert || !hostname) { return false; }
  16782. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16783. std::string host_str(hostname);
  16784. // Check if hostname is an IP address (IPv4 or IPv6)
  16785. unsigned char ip_bytes[16];
  16786. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16787. auto is_ip = ip_len > 0;
  16788. // Check Subject Alternative Names
  16789. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16790. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16791. if (san_names) {
  16792. int san_count = wolfSSL_sk_num(san_names);
  16793. for (int i = 0; i < san_count; i++) {
  16794. auto *names =
  16795. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16796. if (!names) continue;
  16797. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16798. // DNS name
  16799. unsigned char *dns_name = nullptr;
  16800. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16801. if (dns_name && dns_len > 0) {
  16802. std::string san_name(reinterpret_cast<char *>(dns_name),
  16803. static_cast<size_t>(dns_len));
  16804. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16805. if (detail::match_hostname(san_name, host_str)) {
  16806. wolfSSL_sk_free(san_names);
  16807. return true;
  16808. }
  16809. }
  16810. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16811. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16812. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16813. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16814. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16815. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16816. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16817. wolfSSL_sk_free(san_names);
  16818. return true;
  16819. }
  16820. }
  16821. }
  16822. wolfSSL_sk_free(san_names);
  16823. }
  16824. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16825. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16826. // the OpenSSL backend's X509_check_ip behaves the same way).
  16827. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16828. if (subject) {
  16829. char cn[256] = {};
  16830. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16831. sizeof(cn));
  16832. if (cn_len > 0) {
  16833. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16834. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16835. }
  16836. }
  16837. return false;
  16838. }
  16839. inline uint64_t hostname_mismatch_code() {
  16840. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16841. }
  16842. inline long get_verify_result(const_session_t session) {
  16843. if (!session) { return -1; }
  16844. auto wsession =
  16845. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16846. long result = wolfSSL_get_verify_result(wsession->ssl);
  16847. return result;
  16848. }
  16849. inline std::string get_cert_subject_cn(cert_t cert) {
  16850. if (!cert) return "";
  16851. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16852. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16853. if (!subject) return "";
  16854. char cn[256] = {};
  16855. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16856. sizeof(cn));
  16857. if (cn_len <= 0) return "";
  16858. return std::string(cn, static_cast<size_t>(cn_len));
  16859. }
  16860. inline std::string get_cert_issuer_name(cert_t cert) {
  16861. if (!cert) return "";
  16862. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16863. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16864. if (!issuer) return "";
  16865. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16866. if (!name_str) return "";
  16867. std::string result(name_str);
  16868. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16869. return result;
  16870. }
  16871. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16872. sans.clear();
  16873. if (!cert) return false;
  16874. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16875. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16876. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16877. if (!san_names) return true; // No SANs is not an error
  16878. int count = wolfSSL_sk_num(san_names);
  16879. for (int i = 0; i < count; i++) {
  16880. auto *name =
  16881. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16882. if (!name) continue;
  16883. SanEntry entry;
  16884. switch (name->type) {
  16885. case WOLFSSL_GEN_DNS: {
  16886. entry.type = SanType::DNS;
  16887. unsigned char *dns_name = nullptr;
  16888. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16889. if (dns_name && dns_len > 0) {
  16890. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16891. static_cast<size_t>(dns_len));
  16892. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16893. }
  16894. break;
  16895. }
  16896. case WOLFSSL_GEN_IPADD: {
  16897. entry.type = SanType::IP;
  16898. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16899. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16900. if (ip_data && ip_len == 4) {
  16901. char buf[16];
  16902. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16903. ip_data[2], ip_data[3]);
  16904. entry.value = buf;
  16905. } else if (ip_data && ip_len == 16) {
  16906. char buf[64];
  16907. snprintf(buf, sizeof(buf),
  16908. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16909. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16910. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16911. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16912. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16913. ip_data[14], ip_data[15]);
  16914. entry.value = buf;
  16915. }
  16916. break;
  16917. }
  16918. case WOLFSSL_GEN_EMAIL:
  16919. entry.type = SanType::EMAIL;
  16920. {
  16921. unsigned char *email = nullptr;
  16922. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16923. if (email && email_len > 0) {
  16924. entry.value = std::string(reinterpret_cast<char *>(email),
  16925. static_cast<size_t>(email_len));
  16926. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16927. }
  16928. }
  16929. break;
  16930. case WOLFSSL_GEN_URI:
  16931. entry.type = SanType::URI;
  16932. {
  16933. unsigned char *uri = nullptr;
  16934. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16935. &uri, name->d.uniformResourceIdentifier);
  16936. if (uri && uri_len > 0) {
  16937. entry.value = std::string(reinterpret_cast<char *>(uri),
  16938. static_cast<size_t>(uri_len));
  16939. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16940. }
  16941. }
  16942. break;
  16943. default: entry.type = SanType::OTHER; break;
  16944. }
  16945. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16946. }
  16947. wolfSSL_sk_free(san_names);
  16948. return true;
  16949. }
  16950. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16951. time_t &not_after) {
  16952. if (!cert) return false;
  16953. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16954. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16955. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16956. if (!nb || !na) return false;
  16957. // wolfSSL_ASN1_TIME_to_tm is available
  16958. struct tm tm_nb = {}, tm_na = {};
  16959. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16960. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16961. #ifdef _WIN32
  16962. not_before = _mkgmtime(&tm_nb);
  16963. not_after = _mkgmtime(&tm_na);
  16964. #else
  16965. not_before = timegm(&tm_nb);
  16966. not_after = timegm(&tm_na);
  16967. #endif
  16968. return true;
  16969. }
  16970. inline std::string get_cert_serial(cert_t cert) {
  16971. if (!cert) return "";
  16972. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16973. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16974. if (!serial_asn1) return "";
  16975. // Get the serial number data
  16976. int len = serial_asn1->length;
  16977. unsigned char *data = serial_asn1->data;
  16978. if (!data || len <= 0) return "";
  16979. std::string result;
  16980. result.reserve(static_cast<size_t>(len) * 2);
  16981. for (int i = 0; i < len; i++) {
  16982. char hex[3];
  16983. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16984. result += hex;
  16985. }
  16986. return result;
  16987. }
  16988. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16989. if (!cert) return false;
  16990. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16991. int der_len = 0;
  16992. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16993. if (!der_data || der_len <= 0) return false;
  16994. der.assign(der_data, der_data + der_len);
  16995. return true;
  16996. }
  16997. inline const char *get_sni(const_session_t session) {
  16998. if (!session) return nullptr;
  16999. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17000. // For server: return SNI received from client during handshake
  17001. if (!wsession->sni_hostname.empty()) {
  17002. return wsession->sni_hostname.c_str();
  17003. }
  17004. // For client: return the hostname set via set_sni
  17005. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17006. return nullptr;
  17007. }
  17008. inline uint64_t peek_error() {
  17009. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17010. }
  17011. inline uint64_t get_error() {
  17012. uint64_t err = impl::wolfssl_last_error();
  17013. impl::wolfssl_last_error() = 0;
  17014. return err;
  17015. }
  17016. inline std::string error_string(uint64_t code) {
  17017. char buf[256];
  17018. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17019. return std::string(buf);
  17020. }
  17021. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17022. if (!pem || len == 0) { return nullptr; }
  17023. // Validate by attempting to load into a temporary ctx
  17024. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17025. if (!tmp_ctx) { return nullptr; }
  17026. int ret = wolfSSL_CTX_load_verify_buffer(
  17027. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17028. static_cast<long>(len), SSL_FILETYPE_PEM);
  17029. wolfSSL_CTX_free(tmp_ctx);
  17030. if (ret != SSL_SUCCESS) { return nullptr; }
  17031. return static_cast<ca_store_t>(
  17032. new impl::WolfSSLCAStore{std::string(pem, len)});
  17033. }
  17034. inline void free_ca_store(ca_store_t store) {
  17035. delete static_cast<impl::WolfSSLCAStore *>(store);
  17036. }
  17037. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17038. if (!ctx || !store) { return false; }
  17039. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17040. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17041. int ret = wolfSSL_CTX_load_verify_buffer(
  17042. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17043. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17044. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17045. // This function takes ownership of the store; the PEM data was copied into
  17046. // the context, so release the source
  17047. free_ca_store(store);
  17048. return ret == SSL_SUCCESS;
  17049. }
  17050. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17051. certs.clear();
  17052. if (!ctx) { return 0; }
  17053. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17054. if (wctx->ca_pem_data_.empty()) { return 0; }
  17055. const std::string &pem = wctx->ca_pem_data_;
  17056. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17057. const std::string end_marker = "-----END CERTIFICATE-----";
  17058. size_t pos = 0;
  17059. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17060. size_t end_pos = pem.find(end_marker, pos);
  17061. if (end_pos == std::string::npos) { break; }
  17062. end_pos += end_marker.size();
  17063. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17064. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17065. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17066. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17067. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17068. pos = end_pos;
  17069. }
  17070. return certs.size();
  17071. }
  17072. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17073. std::vector<std::string> names;
  17074. if (!ctx) { return names; }
  17075. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17076. if (wctx->ca_pem_data_.empty()) { return names; }
  17077. const std::string &pem = wctx->ca_pem_data_;
  17078. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17079. const std::string end_marker = "-----END CERTIFICATE-----";
  17080. size_t pos = 0;
  17081. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17082. size_t end_pos = pem.find(end_marker, pos);
  17083. if (end_pos == std::string::npos) { break; }
  17084. end_pos += end_marker.size();
  17085. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17086. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17087. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17088. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17089. if (x509) {
  17090. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17091. if (subject) {
  17092. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17093. if (name_str) {
  17094. names.push_back(name_str);
  17095. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17096. }
  17097. }
  17098. wolfSSL_X509_free(x509);
  17099. }
  17100. pos = end_pos;
  17101. }
  17102. return names;
  17103. }
  17104. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17105. const char *key_pem, const char *password) {
  17106. if (!ctx || !cert_pem || !key_pem) { return false; }
  17107. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17108. // Load new certificate
  17109. int ret = wolfSSL_CTX_use_certificate_buffer(
  17110. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17111. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17112. if (ret != SSL_SUCCESS) {
  17113. impl::wolfssl_last_error() =
  17114. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17115. return false;
  17116. }
  17117. // Set password if provided
  17118. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17119. // Load new private key
  17120. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17121. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17122. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17123. if (ret != SSL_SUCCESS) {
  17124. impl::wolfssl_last_error() =
  17125. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17126. return false;
  17127. }
  17128. return true;
  17129. }
  17130. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17131. if (!ctx || !ca_pem) { return false; }
  17132. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17133. int ret = wolfSSL_CTX_load_verify_buffer(
  17134. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17135. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17136. if (ret != SSL_SUCCESS) {
  17137. impl::wolfssl_last_error() =
  17138. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17139. return false;
  17140. }
  17141. return true;
  17142. }
  17143. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17144. if (!ctx) { return false; }
  17145. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17146. impl::get_verify_callback() = std::move(callback);
  17147. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17148. if (wctx->has_verify_callback) {
  17149. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17150. impl::wolfssl_verify_callback);
  17151. } else {
  17152. wolfSSL_CTX_set_verify(
  17153. wctx->ctx,
  17154. wctx->verify_client
  17155. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17156. : SSL_VERIFY_NONE,
  17157. nullptr);
  17158. }
  17159. return true;
  17160. }
  17161. inline long get_verify_error(const_session_t session) {
  17162. if (!session) { return -1; }
  17163. auto *wsession =
  17164. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17165. return wolfSSL_get_verify_result(wsession->ssl);
  17166. }
  17167. inline std::string verify_error_string(long error_code) {
  17168. if (error_code == 0) { return ""; }
  17169. const char *str =
  17170. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17171. return str ? std::string(str) : std::string();
  17172. }
  17173. } // namespace tls
  17174. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17175. // WebSocket implementation
  17176. namespace ws {
  17177. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17178. bool fin) {
  17179. std::lock_guard<std::mutex> lock(write_mutex_);
  17180. if (closed_) { return false; }
  17181. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17182. }
  17183. inline ReadResult WebSocket::read(std::string &msg) {
  17184. while (!closed_) {
  17185. Opcode opcode;
  17186. std::string payload;
  17187. bool fin;
  17188. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17189. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17190. closed_ = true;
  17191. return Fail;
  17192. }
  17193. switch (opcode) {
  17194. case Opcode::Ping: {
  17195. std::lock_guard<std::mutex> lock(write_mutex_);
  17196. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17197. payload.size(), true, !is_server_);
  17198. continue;
  17199. }
  17200. case Opcode::Pong: {
  17201. std::lock_guard<std::mutex> lock(ping_mutex_);
  17202. unacked_pings_ = 0;
  17203. continue;
  17204. }
  17205. case Opcode::Close: {
  17206. if (!closed_.exchange(true)) {
  17207. // Echo close frame back
  17208. std::lock_guard<std::mutex> lock(write_mutex_);
  17209. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17210. payload.size(), true, !is_server_);
  17211. }
  17212. return Fail;
  17213. }
  17214. case Opcode::Text:
  17215. case Opcode::Binary: {
  17216. auto result = opcode == Opcode::Text ? Text : Binary;
  17217. msg = std::move(payload);
  17218. // Handle fragmentation
  17219. if (!fin) {
  17220. while (true) {
  17221. Opcode cont_opcode;
  17222. std::string cont_payload;
  17223. bool cont_fin;
  17224. if (!impl::read_websocket_frame(
  17225. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17226. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17227. closed_ = true;
  17228. return Fail;
  17229. }
  17230. if (cont_opcode == Opcode::Ping) {
  17231. std::lock_guard<std::mutex> lock(write_mutex_);
  17232. detail::write_websocket_frame(
  17233. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17234. true, !is_server_);
  17235. continue;
  17236. }
  17237. if (cont_opcode == Opcode::Pong) {
  17238. std::lock_guard<std::mutex> lock(ping_mutex_);
  17239. unacked_pings_ = 0;
  17240. continue;
  17241. }
  17242. if (cont_opcode == Opcode::Close) {
  17243. if (!closed_.exchange(true)) {
  17244. std::lock_guard<std::mutex> lock(write_mutex_);
  17245. detail::write_websocket_frame(
  17246. strm_, Opcode::Close, cont_payload.data(),
  17247. cont_payload.size(), true, !is_server_);
  17248. }
  17249. return Fail;
  17250. }
  17251. // RFC 6455: continuation frames must use opcode 0x0
  17252. if (cont_opcode != Opcode::Continuation) {
  17253. closed_ = true;
  17254. return Fail;
  17255. }
  17256. msg += cont_payload;
  17257. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17258. closed_ = true;
  17259. return Fail;
  17260. }
  17261. if (cont_fin) { break; }
  17262. }
  17263. }
  17264. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17265. if (result == Text && !impl::is_valid_utf8(msg)) {
  17266. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17267. return Fail;
  17268. }
  17269. return result;
  17270. }
  17271. default: closed_ = true; return Fail;
  17272. }
  17273. }
  17274. return Fail;
  17275. }
  17276. inline bool WebSocket::send(const std::string &data) {
  17277. return send_frame(Opcode::Text, data.data(), data.size());
  17278. }
  17279. inline bool WebSocket::send(const char *data, size_t len) {
  17280. return send_frame(Opcode::Binary, data, len);
  17281. }
  17282. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17283. if (closed_.exchange(true)) { return; }
  17284. ping_cv_.notify_all();
  17285. std::string payload;
  17286. auto code = static_cast<uint16_t>(status);
  17287. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17288. payload.push_back(static_cast<char>(code & 0xFF));
  17289. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17290. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17291. payload += reason.substr(0, 123);
  17292. {
  17293. std::lock_guard<std::mutex> lock(write_mutex_);
  17294. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17295. payload.size(), true, !is_server_);
  17296. }
  17297. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17298. // Close response before closing the TCP connection. Use a short timeout to
  17299. // avoid hanging if the peer doesn't respond.
  17300. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17301. Opcode op;
  17302. std::string resp;
  17303. bool fin;
  17304. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17305. if (op == Opcode::Close) { break; }
  17306. }
  17307. }
  17308. inline WebSocket::~WebSocket() {
  17309. {
  17310. std::lock_guard<std::mutex> lock(ping_mutex_);
  17311. closed_ = true;
  17312. }
  17313. ping_cv_.notify_all();
  17314. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17315. }
  17316. inline void WebSocket::start_heartbeat() {
  17317. if (ping_interval_sec_ == 0) { return; }
  17318. ping_thread_ = std::thread([this]() {
  17319. std::unique_lock<std::mutex> lock(ping_mutex_);
  17320. while (!closed_) {
  17321. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17322. if (closed_) { break; }
  17323. // If the peer has failed to respond to the previous pings, give up.
  17324. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17325. // opt-in liveness check controlled by max_missed_pongs_.
  17326. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17327. lock.unlock();
  17328. close(CloseStatus::GoingAway, "pong timeout");
  17329. return;
  17330. }
  17331. lock.unlock();
  17332. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17333. lock.lock();
  17334. closed_ = true;
  17335. break;
  17336. }
  17337. lock.lock();
  17338. unacked_pings_++;
  17339. }
  17340. });
  17341. }
  17342. inline const Request &WebSocket::request() const { return req_; }
  17343. inline bool WebSocket::is_open() const { return !closed_; }
  17344. // WebSocketClient implementation
  17345. inline WebSocketClient::WebSocketClient(
  17346. const std::string &scheme_host_port_path, const Headers &headers)
  17347. : headers_(headers) {
  17348. detail::UrlComponents uc;
  17349. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17350. !uc.host.empty() && !uc.path.empty()) {
  17351. auto &scheme = uc.scheme;
  17352. #ifdef CPPHTTPLIB_SSL_ENABLED
  17353. if (scheme != "ws" && scheme != "wss") {
  17354. #else
  17355. if (scheme != "ws") {
  17356. #endif
  17357. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17358. std::string msg = "'" + scheme + "' scheme is not supported.";
  17359. throw std::invalid_argument(msg);
  17360. #endif
  17361. return;
  17362. }
  17363. auto is_ssl = scheme == "wss";
  17364. host_ = std::move(uc.host);
  17365. port_ = is_ssl ? 443 : 80;
  17366. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17367. path_ = std::move(uc.path);
  17368. if (!uc.query.empty()) { path_ += uc.query; }
  17369. #ifdef CPPHTTPLIB_SSL_ENABLED
  17370. is_ssl_ = is_ssl;
  17371. if (is_ssl_) {
  17372. // The context lives as long as the client so that CA configuration
  17373. // survives reconnects; sessions are created per connection.
  17374. tls_ctx_ = tls::create_client_context();
  17375. if (!tls_ctx_) { return; }
  17376. }
  17377. #else
  17378. if (is_ssl) { return; }
  17379. #endif
  17380. is_valid_ = true;
  17381. }
  17382. }
  17383. inline WebSocketClient::~WebSocketClient() {
  17384. shutdown_and_close();
  17385. #ifdef CPPHTTPLIB_SSL_ENABLED
  17386. if (tls_ctx_) {
  17387. tls::free_context(tls_ctx_);
  17388. tls_ctx_ = nullptr;
  17389. }
  17390. #endif
  17391. }
  17392. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17393. inline void WebSocketClient::shutdown_and_close() {
  17394. #ifdef CPPHTTPLIB_SSL_ENABLED
  17395. if (is_ssl_) {
  17396. if (tls_session_) {
  17397. tls::shutdown(tls_session_, true);
  17398. tls::free_session(tls_session_);
  17399. tls_session_ = nullptr;
  17400. }
  17401. }
  17402. #endif
  17403. if (ws_ && ws_->is_open()) { ws_->close(); }
  17404. ws_.reset();
  17405. if (sock_ != INVALID_SOCKET) {
  17406. detail::shutdown_socket(sock_);
  17407. detail::close_socket(sock_);
  17408. sock_ = INVALID_SOCKET;
  17409. }
  17410. }
  17411. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17412. #ifdef CPPHTTPLIB_SSL_ENABLED
  17413. if (is_ssl_) {
  17414. if (server_certificate_verification_ && !certs_loaded_) {
  17415. uint64_t backend_error = 0;
  17416. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17417. custom_ca_loaded_, system_ca_mode_,
  17418. backend_error);
  17419. certs_loaded_ = true;
  17420. }
  17421. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17422. server_certificate_verification_,
  17423. read_timeout_sec_,
  17424. read_timeout_usec_)) {
  17425. return false;
  17426. }
  17427. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17428. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17429. write_timeout_sec_, write_timeout_usec_));
  17430. return true;
  17431. }
  17432. #endif
  17433. strm = std::unique_ptr<Stream>(
  17434. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17435. write_timeout_sec_, write_timeout_usec_));
  17436. return true;
  17437. }
  17438. inline bool WebSocketClient::connect() {
  17439. if (!is_valid_) { return false; }
  17440. shutdown_and_close();
  17441. // Check is custom IP specified for host_
  17442. std::string ip;
  17443. auto it = addr_map_.find(host_);
  17444. if (it != addr_map_.end()) { ip = it->second; }
  17445. Error error;
  17446. sock_ = detail::create_client_socket(
  17447. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17448. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17449. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17450. write_timeout_usec_, interface_, error);
  17451. if (sock_ == INVALID_SOCKET) { return false; }
  17452. std::unique_ptr<Stream> strm;
  17453. if (!create_stream(strm)) {
  17454. shutdown_and_close();
  17455. return false;
  17456. }
  17457. #ifdef CPPHTTPLIB_SSL_ENABLED
  17458. auto is_ssl = is_ssl_;
  17459. #else
  17460. auto is_ssl = false;
  17461. #endif
  17462. std::string selected_subprotocol;
  17463. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17464. headers_, selected_subprotocol)) {
  17465. shutdown_and_close();
  17466. return false;
  17467. }
  17468. subprotocol_ = std::move(selected_subprotocol);
  17469. Request req;
  17470. req.method = "GET";
  17471. req.path = path_;
  17472. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17473. websocket_ping_interval_sec_,
  17474. websocket_max_missed_pongs_));
  17475. return true;
  17476. }
  17477. inline ReadResult WebSocketClient::read(std::string &msg) {
  17478. if (!ws_) { return Fail; }
  17479. return ws_->read(msg);
  17480. }
  17481. inline bool WebSocketClient::send(const std::string &data) {
  17482. if (!ws_) { return false; }
  17483. return ws_->send(data);
  17484. }
  17485. inline bool WebSocketClient::send(const char *data, size_t len) {
  17486. if (!ws_) { return false; }
  17487. return ws_->send(data, len);
  17488. }
  17489. inline void WebSocketClient::close(CloseStatus status,
  17490. const std::string &reason) {
  17491. if (ws_) { ws_->close(status, reason); }
  17492. }
  17493. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17494. inline const std::string &WebSocketClient::subprotocol() const {
  17495. return subprotocol_;
  17496. }
  17497. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17498. read_timeout_sec_ = sec;
  17499. read_timeout_usec_ = usec;
  17500. }
  17501. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17502. write_timeout_sec_ = sec;
  17503. write_timeout_usec_ = usec;
  17504. }
  17505. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17506. websocket_ping_interval_sec_ = sec;
  17507. }
  17508. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17509. websocket_max_missed_pongs_ = count;
  17510. }
  17511. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17512. inline void WebSocketClient::set_address_family(int family) {
  17513. address_family_ = family;
  17514. }
  17515. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17516. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17517. socket_options_ = std::move(socket_options);
  17518. }
  17519. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17520. connection_timeout_sec_ = sec;
  17521. connection_timeout_usec_ = usec;
  17522. }
  17523. inline void WebSocketClient::set_interface(const std::string &intf) {
  17524. interface_ = intf;
  17525. }
  17526. inline void WebSocketClient::set_hostname_addr_map(
  17527. std::map<std::string, std::string> addr_map) {
  17528. addr_map_ = std::move(addr_map);
  17529. }
  17530. #ifdef CPPHTTPLIB_SSL_ENABLED
  17531. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17532. ca_cert_file_path_ = path;
  17533. }
  17534. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17535. if (store && tls_ctx_) {
  17536. // set_ca_store takes ownership of store
  17537. tls::set_ca_store(tls_ctx_, store);
  17538. custom_ca_loaded_ = true;
  17539. } else if (store) {
  17540. tls::free_ca_store(store);
  17541. }
  17542. }
  17543. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17544. std::size_t size) {
  17545. if (tls_ctx_ && ca_cert && size > 0) {
  17546. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17547. custom_ca_loaded_ = true;
  17548. }
  17549. }
  17550. inline void
  17551. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17552. server_certificate_verification_ = enabled;
  17553. }
  17554. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17555. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17556. }
  17557. #endif // CPPHTTPLIB_SSL_ENABLED
  17558. } // namespace ws
  17559. // ----------------------------------------------------------------------------
  17560. } // namespace httplib
  17561. #endif // CPPHTTPLIB_HTTPLIB_H