httplib.h 688 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.50.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003201"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  160. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  161. #endif
  162. /*
  163. * Headers
  164. */
  165. #ifdef _WIN32
  166. #ifndef _CRT_SECURE_NO_WARNINGS
  167. #define _CRT_SECURE_NO_WARNINGS
  168. #endif //_CRT_SECURE_NO_WARNINGS
  169. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  170. #define _CRT_NONSTDC_NO_DEPRECATE
  171. #endif //_CRT_NONSTDC_NO_DEPRECATE
  172. #if defined(_MSC_VER)
  173. #if _MSC_VER < 1900
  174. #error Sorry, Visual Studio versions prior to 2015 are not supported
  175. #endif
  176. #pragma comment(lib, "ws2_32.lib")
  177. #ifndef _SSIZE_T_DEFINED
  178. using ssize_t = __int64;
  179. #define _SSIZE_T_DEFINED
  180. #endif
  181. #endif // _MSC_VER
  182. #ifndef S_ISREG
  183. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  184. #endif // S_ISREG
  185. #ifndef S_ISDIR
  186. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  187. #endif // S_ISDIR
  188. #ifndef NOMINMAX
  189. #define NOMINMAX
  190. #endif // NOMINMAX
  191. #include <io.h>
  192. #include <winsock2.h>
  193. #include <ws2tcpip.h>
  194. #if defined(__has_include)
  195. #if __has_include(<afunix.h>)
  196. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  197. #include <afunix.h>
  198. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  199. #endif
  200. #endif
  201. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  202. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  203. #endif
  204. using nfds_t = unsigned long;
  205. using socket_t = SOCKET;
  206. using socklen_t = int;
  207. #else // not _WIN32
  208. #include <arpa/inet.h>
  209. #if !defined(_AIX) && !defined(__MVS__)
  210. #include <ifaddrs.h>
  211. #endif
  212. #ifdef __MVS__
  213. #include <strings.h>
  214. #ifndef NI_MAXHOST
  215. #define NI_MAXHOST 1025
  216. #endif
  217. #endif
  218. #include <net/if.h>
  219. #include <netdb.h>
  220. #include <netinet/in.h>
  221. #ifdef __linux__
  222. #include <resolv.h>
  223. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  224. #endif
  225. #include <csignal>
  226. #include <netinet/tcp.h>
  227. #include <poll.h>
  228. #include <pthread.h>
  229. #include <sys/mman.h>
  230. #include <sys/socket.h>
  231. #include <sys/un.h>
  232. #include <unistd.h>
  233. using socket_t = int;
  234. #ifndef INVALID_SOCKET
  235. #define INVALID_SOCKET (-1)
  236. #endif
  237. #endif //_WIN32
  238. #if defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #endif
  241. #include <algorithm>
  242. #include <array>
  243. #include <atomic>
  244. #include <cassert>
  245. #include <chrono>
  246. #include <climits>
  247. #include <condition_variable>
  248. #include <cstdlib>
  249. #include <cstring>
  250. #include <errno.h>
  251. #include <exception>
  252. #include <fcntl.h>
  253. #include <fstream>
  254. #include <functional>
  255. #include <iomanip>
  256. #include <iostream>
  257. #include <list>
  258. #include <map>
  259. #include <memory>
  260. #include <mutex>
  261. #include <random>
  262. #include <regex>
  263. #include <set>
  264. #include <sstream>
  265. #include <string>
  266. #include <sys/stat.h>
  267. #include <system_error>
  268. #include <thread>
  269. #include <unordered_map>
  270. #include <unordered_set>
  271. #include <utility>
  272. // On macOS with a TLS backend, enable Keychain root certificates by default
  273. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  274. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  275. // only; on those platforms the user must provide a CA bundle explicitly.
  276. #if defined(__APPLE__) && defined(__clang__) && \
  277. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  278. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  279. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  280. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  281. #if TARGET_OS_OSX
  282. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  283. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #endif
  285. #endif
  286. #endif
  287. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  288. defined(__APPLE__) && !TARGET_OS_OSX
  289. #error \
  290. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  291. #endif
  292. // On Windows, enable Schannel certificate verification by default
  293. // unless the user explicitly opts out.
  294. #if defined(_WIN32) && \
  295. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  296. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  297. #endif
  298. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  299. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  300. #if TARGET_OS_MAC && defined(__clang__)
  301. #include <CFNetwork/CFHost.h>
  302. #include <CoreFoundation/CoreFoundation.h>
  303. #endif
  304. #endif
  305. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  306. #ifdef _WIN32
  307. #include <wincrypt.h>
  308. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  309. // used
  310. #undef X509_NAME
  311. #undef X509_CERT_PAIR
  312. #undef X509_EXTENSIONS
  313. #undef PKCS7_SIGNER_INFO
  314. #ifdef _MSC_VER
  315. #pragma comment(lib, "crypt32.lib")
  316. #endif
  317. #endif // _WIN32
  318. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  319. #if TARGET_OS_OSX
  320. #include <Security/Security.h>
  321. #endif
  322. #endif
  323. #include <openssl/err.h>
  324. #include <openssl/evp.h>
  325. #include <openssl/ssl.h>
  326. #include <openssl/x509v3.h>
  327. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  328. #include <openssl/applink.c>
  329. #endif
  330. #include <iostream>
  331. #include <sstream>
  332. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  333. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  334. #error Please use OpenSSL or a current version of BoringSSL
  335. #endif
  336. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  337. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  338. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  339. #endif
  340. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  341. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  342. #include <mbedtls/ctr_drbg.h>
  343. #include <mbedtls/entropy.h>
  344. #include <mbedtls/error.h>
  345. #include <mbedtls/md5.h>
  346. #include <mbedtls/net_sockets.h>
  347. #include <mbedtls/oid.h>
  348. #include <mbedtls/pk.h>
  349. #include <mbedtls/sha1.h>
  350. #include <mbedtls/sha256.h>
  351. #include <mbedtls/sha512.h>
  352. #include <mbedtls/ssl.h>
  353. #include <mbedtls/x509_crt.h>
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. #ifdef _MSC_VER
  357. #pragma comment(lib, "crypt32.lib")
  358. #endif
  359. #endif // _WIN32
  360. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  361. #if TARGET_OS_OSX
  362. #include <Security/Security.h>
  363. #endif
  364. #endif
  365. // Mbed TLS 3.x API compatibility
  366. #if MBEDTLS_VERSION_MAJOR >= 3
  367. #define CPPHTTPLIB_MBEDTLS_V3
  368. #endif
  369. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  370. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  371. #include <wolfssl/options.h>
  372. #include <wolfssl/openssl/x509v3.h>
  373. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  374. #ifndef WOLFSSL_GEN_EMAIL
  375. #define WOLFSSL_GEN_EMAIL 1
  376. #endif
  377. #ifndef WOLFSSL_GEN_DNS
  378. #define WOLFSSL_GEN_DNS 2
  379. #endif
  380. #ifndef WOLFSSL_GEN_URI
  381. #define WOLFSSL_GEN_URI 6
  382. #endif
  383. #ifndef WOLFSSL_GEN_IPADD
  384. #define WOLFSSL_GEN_IPADD 7
  385. #endif
  386. #include <wolfssl/ssl.h>
  387. #include <wolfssl/wolfcrypt/hash.h>
  388. #include <wolfssl/wolfcrypt/md5.h>
  389. #include <wolfssl/wolfcrypt/sha256.h>
  390. #include <wolfssl/wolfcrypt/sha512.h>
  391. #ifdef _WIN32
  392. #include <wincrypt.h>
  393. #ifdef _MSC_VER
  394. #pragma comment(lib, "crypt32.lib")
  395. #endif
  396. #endif // _WIN32
  397. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  398. #if TARGET_OS_OSX
  399. #include <Security/Security.h>
  400. #endif
  401. #endif
  402. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  403. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  404. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  405. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  406. #define CPPHTTPLIB_SSL_ENABLED
  407. #endif
  408. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  409. #include <zlib.h>
  410. #endif
  411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  412. #include <brotli/decode.h>
  413. #include <brotli/encode.h>
  414. #endif
  415. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  416. #include <zstd.h>
  417. #endif
  418. /*
  419. * Declaration
  420. */
  421. namespace httplib {
  422. namespace ws {
  423. class WebSocket;
  424. } // namespace ws
  425. namespace detail {
  426. /*
  427. * Backport std::make_unique from C++14.
  428. *
  429. * NOTE: This code came up with the following stackoverflow post:
  430. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  431. *
  432. */
  433. template <class T, class... Args>
  434. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  435. make_unique(Args &&...args) {
  436. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  437. }
  438. template <class T>
  439. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  440. make_unique(std::size_t n) {
  441. typedef typename std::remove_extent<T>::type RT;
  442. return std::unique_ptr<T>(new RT[n]);
  443. }
  444. // Locale-independent ASCII character classification. The <cctype>
  445. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  446. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  447. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  448. // classified without regard to the locale.
  449. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  450. inline bool is_ascii_alpha(char c) {
  451. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  452. }
  453. inline bool is_ascii_alnum(char c) {
  454. return is_ascii_digit(c) || is_ascii_alpha(c);
  455. }
  456. namespace case_ignore {
  457. inline unsigned char to_lower(int c) {
  458. const static unsigned char table[256] = {
  459. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  460. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  461. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  462. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  463. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  464. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  465. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  466. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  467. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  468. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  469. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  470. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  471. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  472. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  473. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  474. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  475. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  476. 255,
  477. };
  478. return table[(unsigned char)(char)c];
  479. }
  480. inline std::string to_lower(const std::string &s) {
  481. std::string result = s;
  482. std::transform(
  483. result.begin(), result.end(), result.begin(),
  484. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  485. return result;
  486. }
  487. inline bool equal(const std::string &a, const std::string &b) {
  488. return a.size() == b.size() &&
  489. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  490. return to_lower(ca) == to_lower(cb);
  491. });
  492. }
  493. struct equal_to {
  494. bool operator()(const std::string &a, const std::string &b) const {
  495. return equal(a, b);
  496. }
  497. };
  498. struct hash {
  499. size_t operator()(const std::string &key) const {
  500. return hash_core(key.data(), key.size(), 0);
  501. }
  502. size_t hash_core(const char *s, size_t l, size_t h) const {
  503. return (l == 0) ? h
  504. : hash_core(s + 1, l - 1,
  505. // Unsets the 6 high bits of h, therefore no
  506. // overflow happens
  507. (((std::numeric_limits<size_t>::max)() >> 6) &
  508. h * 33) ^
  509. static_cast<unsigned char>(to_lower(*s)));
  510. }
  511. };
  512. template <typename T>
  513. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  514. detail::case_ignore::equal_to>;
  515. } // namespace case_ignore
  516. // This is based on
  517. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  518. struct scope_exit {
  519. explicit scope_exit(std::function<void(void)> &&f)
  520. : exit_function(std::move(f)), execute_on_destruction{true} {}
  521. scope_exit(scope_exit &&rhs) noexcept
  522. : exit_function(std::move(rhs.exit_function)),
  523. execute_on_destruction{rhs.execute_on_destruction} {
  524. rhs.release();
  525. }
  526. ~scope_exit() {
  527. if (execute_on_destruction) { this->exit_function(); }
  528. }
  529. void release() { this->execute_on_destruction = false; }
  530. private:
  531. scope_exit(const scope_exit &) = delete;
  532. void operator=(const scope_exit &) = delete;
  533. scope_exit &operator=(scope_exit &&) = delete;
  534. std::function<void(void)> exit_function;
  535. bool execute_on_destruction;
  536. };
  537. // Simple from_chars implementation for integer and double types (C++17
  538. // substitute)
  539. template <typename T> struct from_chars_result {
  540. const char *ptr;
  541. std::errc ec;
  542. };
  543. template <typename T>
  544. inline from_chars_result<T> from_chars(const char *first, const char *last,
  545. T &value, int base = 10) {
  546. value = 0;
  547. const char *p = first;
  548. bool negative = false;
  549. if (p != last && *p == '-') {
  550. negative = true;
  551. ++p;
  552. }
  553. if (p == last) { return {first, std::errc::invalid_argument}; }
  554. T result = 0;
  555. for (; p != last; ++p) {
  556. char c = *p;
  557. int digit = -1;
  558. if (is_ascii_digit(c)) {
  559. digit = c - '0';
  560. } else if ('a' <= c && c <= 'z') {
  561. digit = c - 'a' + 10;
  562. } else if ('A' <= c && c <= 'Z') {
  563. digit = c - 'A' + 10;
  564. } else {
  565. break;
  566. }
  567. if (digit < 0 || digit >= base) { break; }
  568. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  569. return {p, std::errc::result_out_of_range};
  570. }
  571. result = result * base + digit;
  572. }
  573. if (p == first || (negative && p == first + 1)) {
  574. return {first, std::errc::invalid_argument};
  575. }
  576. value = negative ? -result : result;
  577. return {p, std::errc{}};
  578. }
  579. // from_chars for double (hand-written, locale-independent)
  580. //
  581. // The only double consumed by this library is the HTTP quality value, whose
  582. // grammar is (RFC 9110 12.4.2):
  583. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  584. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  585. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  586. // '.' always the decimal separator (std::strtod would instead read it from the
  587. // global C locale, mis-parsing q-values once an embedder calls
  588. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  589. // the result to [0, 1], so inputs outside that range need not be distinguished
  590. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  591. // cases that exponent and wide-range handling would introduce.
  592. inline from_chars_result<double> from_chars(const char *first, const char *last,
  593. double &value) {
  594. value = 0.0;
  595. const char *p = first;
  596. // Each 1eN is exactly representable, so a single final division by the
  597. // matching entry yields a correctly-rounded result.
  598. static const double powers_of_ten[] = {
  599. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  600. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  601. const int max_frac_digits =
  602. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  603. // Accumulate digits into a 64-bit integer and remember how many were
  604. // fractional. Two independent caps keep this bounded and safe:
  605. // * accumulation saturates before mantissa could overflow uint64_t, and
  606. // * frac_digits is capped at max_frac_digits so it is always a valid index
  607. // into powers_of_ten (without this an input like "0.000...0" would never
  608. // grow mantissa, so the saturation cap alone would not bound it).
  609. // Both caps only drop digits far beyond the precision a q-value needs; any
  610. // value they would change is well outside [0, 1] and rejected by the caller.
  611. uint64_t mantissa = 0;
  612. int frac_digits = 0;
  613. bool seen_digit = false;
  614. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  615. auto accumulate = [&](char c) {
  616. if (mantissa <= limit) {
  617. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  618. return true;
  619. }
  620. return false;
  621. };
  622. for (; p != last && is_ascii_digit(*p); ++p) {
  623. seen_digit = true;
  624. accumulate(*p);
  625. }
  626. if (p != last && *p == '.') {
  627. ++p;
  628. for (; p != last && is_ascii_digit(*p); ++p) {
  629. seen_digit = true;
  630. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  631. }
  632. }
  633. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  634. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  635. return {p, std::errc{}};
  636. }
  637. inline bool parse_port(const char *s, size_t len, int &port) {
  638. int val = 0;
  639. auto r = from_chars(s, s + len, val);
  640. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  641. port = val;
  642. return true;
  643. }
  644. inline bool parse_port(const std::string &s, int &port) {
  645. return parse_port(s.data(), s.size(), port);
  646. }
  647. struct UrlComponents {
  648. std::string scheme;
  649. std::string host;
  650. std::string port;
  651. std::string path;
  652. std::string query;
  653. };
  654. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  655. uc = {};
  656. size_t pos = 0;
  657. auto sep = url.find("://");
  658. if (sep != std::string::npos) {
  659. uc.scheme = url.substr(0, sep);
  660. // Scheme must be [a-z]+ only
  661. if (uc.scheme.empty()) { return false; }
  662. for (auto c : uc.scheme) {
  663. if (c < 'a' || c > 'z') { return false; }
  664. }
  665. pos = sep + 3;
  666. } else if (url.compare(0, 2, "//") == 0) {
  667. pos = 2;
  668. }
  669. auto has_authority_prefix = pos > 0;
  670. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  671. url[0] != '?' && url[0] != '#');
  672. if (has_authority) {
  673. if (pos < url.size() && url[pos] == '[') {
  674. auto close = url.find(']', pos);
  675. if (close == std::string::npos) { return false; }
  676. uc.host = url.substr(pos + 1, close - pos - 1);
  677. // IPv6 host must be [a-fA-F0-9:]+ only
  678. if (uc.host.empty()) { return false; }
  679. for (auto c : uc.host) {
  680. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  681. (c >= 'A' && c <= 'F') || c == ':')) {
  682. return false;
  683. }
  684. }
  685. pos = close + 1;
  686. } else {
  687. auto end = url.find_first_of(":/?#", pos);
  688. if (end == std::string::npos) { end = url.size(); }
  689. uc.host = url.substr(pos, end - pos);
  690. pos = end;
  691. }
  692. if (pos < url.size() && url[pos] == ':') {
  693. ++pos;
  694. auto end = url.find_first_of("/?#", pos);
  695. if (end == std::string::npos) { end = url.size(); }
  696. uc.port = url.substr(pos, end - pos);
  697. pos = end;
  698. }
  699. // Without :// or //, the entire input must be consumed as host[:port].
  700. // If there is leftover (path, query, etc.), this is not a valid
  701. // host[:port] string — clear and reparse as a plain path.
  702. if (!has_authority_prefix && pos < url.size()) {
  703. uc.host.clear();
  704. uc.port.clear();
  705. pos = 0;
  706. }
  707. }
  708. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  709. auto end = url.find_first_of("?#", pos);
  710. if (end == std::string::npos) { end = url.size(); }
  711. uc.path = url.substr(pos, end - pos);
  712. pos = end;
  713. }
  714. if (pos < url.size() && url[pos] == '?') {
  715. auto end = url.find('#', pos);
  716. if (end == std::string::npos) { end = url.size(); }
  717. uc.query = url.substr(pos, end - pos);
  718. }
  719. return true;
  720. }
  721. } // namespace detail
  722. enum class SSLVerifierResponse {
  723. // no decision has been made, use the built-in certificate verifier
  724. NoDecisionMade,
  725. // connection certificate is verified and accepted
  726. CertificateAccepted,
  727. // connection certificate was processed but is rejected
  728. CertificateRejected
  729. };
  730. // System CA loading policy for SSL clients. Auto (the default) loads system
  731. // CA certs only when no custom CA is configured; enable_system_ca() switches
  732. // to an explicit policy.
  733. enum class SystemCAMode { Auto, Enabled, Disabled };
  734. enum StatusCode {
  735. // Information responses
  736. Continue_100 = 100,
  737. SwitchingProtocol_101 = 101,
  738. Processing_102 = 102,
  739. EarlyHints_103 = 103,
  740. // Successful responses
  741. OK_200 = 200,
  742. Created_201 = 201,
  743. Accepted_202 = 202,
  744. NonAuthoritativeInformation_203 = 203,
  745. NoContent_204 = 204,
  746. ResetContent_205 = 205,
  747. PartialContent_206 = 206,
  748. MultiStatus_207 = 207,
  749. AlreadyReported_208 = 208,
  750. IMUsed_226 = 226,
  751. // Redirection messages
  752. MultipleChoices_300 = 300,
  753. MovedPermanently_301 = 301,
  754. Found_302 = 302,
  755. SeeOther_303 = 303,
  756. NotModified_304 = 304,
  757. UseProxy_305 = 305,
  758. unused_306 = 306,
  759. TemporaryRedirect_307 = 307,
  760. PermanentRedirect_308 = 308,
  761. // Client error responses
  762. BadRequest_400 = 400,
  763. Unauthorized_401 = 401,
  764. PaymentRequired_402 = 402,
  765. Forbidden_403 = 403,
  766. NotFound_404 = 404,
  767. MethodNotAllowed_405 = 405,
  768. NotAcceptable_406 = 406,
  769. ProxyAuthenticationRequired_407 = 407,
  770. RequestTimeout_408 = 408,
  771. Conflict_409 = 409,
  772. Gone_410 = 410,
  773. LengthRequired_411 = 411,
  774. PreconditionFailed_412 = 412,
  775. PayloadTooLarge_413 = 413,
  776. UriTooLong_414 = 414,
  777. UnsupportedMediaType_415 = 415,
  778. RangeNotSatisfiable_416 = 416,
  779. ExpectationFailed_417 = 417,
  780. ImATeapot_418 = 418,
  781. MisdirectedRequest_421 = 421,
  782. UnprocessableContent_422 = 422,
  783. Locked_423 = 423,
  784. FailedDependency_424 = 424,
  785. TooEarly_425 = 425,
  786. UpgradeRequired_426 = 426,
  787. PreconditionRequired_428 = 428,
  788. TooManyRequests_429 = 429,
  789. RequestHeaderFieldsTooLarge_431 = 431,
  790. UnavailableForLegalReasons_451 = 451,
  791. // Server error responses
  792. InternalServerError_500 = 500,
  793. NotImplemented_501 = 501,
  794. BadGateway_502 = 502,
  795. ServiceUnavailable_503 = 503,
  796. GatewayTimeout_504 = 504,
  797. HttpVersionNotSupported_505 = 505,
  798. VariantAlsoNegotiates_506 = 506,
  799. InsufficientStorage_507 = 507,
  800. LoopDetected_508 = 508,
  801. NotExtended_510 = 510,
  802. NetworkAuthenticationRequired_511 = 511,
  803. };
  804. using Headers =
  805. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  806. detail::case_ignore::equal_to>;
  807. using Params = std::multimap<std::string, std::string>;
  808. using Match = std::smatch;
  809. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  810. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  811. /*
  812. * detail: type-erased storage used by UserData.
  813. * ABI-stable regardless of C++ standard — always uses this custom
  814. * implementation instead of std::any.
  815. */
  816. namespace detail {
  817. using any_type_id = const void *;
  818. template <typename T> any_type_id any_typeid() noexcept {
  819. static const char id = 0;
  820. return &id;
  821. }
  822. struct any_storage {
  823. virtual ~any_storage() = default;
  824. virtual std::unique_ptr<any_storage> clone() const = 0;
  825. virtual any_type_id type_id() const noexcept = 0;
  826. };
  827. template <typename T> struct any_value final : any_storage {
  828. T value;
  829. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  830. std::unique_ptr<any_storage> clone() const override {
  831. return std::unique_ptr<any_storage>(new any_value<T>(value));
  832. }
  833. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  834. };
  835. } // namespace detail
  836. class UserData {
  837. public:
  838. UserData() = default;
  839. UserData(UserData &&) noexcept = default;
  840. UserData &operator=(UserData &&) noexcept = default;
  841. UserData(const UserData &o) {
  842. for (const auto &e : o.entries_) {
  843. if (e.second) { entries_[e.first] = e.second->clone(); }
  844. }
  845. }
  846. UserData &operator=(const UserData &o) {
  847. if (this != &o) {
  848. entries_.clear();
  849. for (const auto &e : o.entries_) {
  850. if (e.second) { entries_[e.first] = e.second->clone(); }
  851. }
  852. }
  853. return *this;
  854. }
  855. template <typename T> void set(const std::string &key, T &&value) {
  856. using D = typename std::decay<T>::type;
  857. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  858. }
  859. template <typename T> T *get(const std::string &key) noexcept {
  860. auto it = entries_.find(key);
  861. if (it == entries_.end() || !it->second) { return nullptr; }
  862. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  863. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  864. }
  865. template <typename T> const T *get(const std::string &key) const noexcept {
  866. auto it = entries_.find(key);
  867. if (it == entries_.end() || !it->second) { return nullptr; }
  868. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  869. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  870. }
  871. bool has(const std::string &key) const noexcept {
  872. return entries_.find(key) != entries_.end();
  873. }
  874. void erase(const std::string &key) { entries_.erase(key); }
  875. void clear() noexcept { entries_.clear(); }
  876. private:
  877. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  878. entries_;
  879. };
  880. struct Response;
  881. using ResponseHandler = std::function<bool(const Response &response)>;
  882. struct FormData {
  883. std::string name;
  884. std::string content;
  885. std::string filename;
  886. std::string content_type;
  887. Headers headers;
  888. };
  889. struct FormField {
  890. std::string name;
  891. std::string content;
  892. Headers headers;
  893. };
  894. using FormFields = std::multimap<std::string, FormField>;
  895. using FormFiles = std::multimap<std::string, FormData>;
  896. struct MultipartFormData {
  897. FormFields fields; // Text fields from multipart
  898. FormFiles files; // Files from multipart
  899. // Text field access
  900. std::string get_field(const std::string &key, size_t id = 0) const;
  901. std::vector<std::string> get_fields(const std::string &key) const;
  902. bool has_field(const std::string &key) const;
  903. size_t get_field_count(const std::string &key) const;
  904. // File access
  905. FormData get_file(const std::string &key, size_t id = 0) const;
  906. std::vector<FormData> get_files(const std::string &key) const;
  907. bool has_file(const std::string &key) const;
  908. size_t get_file_count(const std::string &key) const;
  909. };
  910. struct UploadFormData {
  911. std::string name;
  912. std::string content;
  913. std::string filename;
  914. std::string content_type;
  915. };
  916. using UploadFormDataItems = std::vector<UploadFormData>;
  917. class DataSink {
  918. public:
  919. DataSink() : os(&sb_), sb_(*this) {}
  920. DataSink(const DataSink &) = delete;
  921. DataSink &operator=(const DataSink &) = delete;
  922. DataSink(DataSink &&) = delete;
  923. DataSink &operator=(DataSink &&) = delete;
  924. std::function<bool(const char *data, size_t data_len)> write;
  925. std::function<bool()> is_writable;
  926. std::function<void()> done;
  927. std::function<void(const Headers &trailer)> done_with_trailer;
  928. std::ostream os;
  929. private:
  930. class data_sink_streambuf final : public std::streambuf {
  931. public:
  932. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  933. protected:
  934. std::streamsize xsputn(const char *s, std::streamsize n) override {
  935. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  936. return 0;
  937. }
  938. private:
  939. DataSink &sink_;
  940. };
  941. data_sink_streambuf sb_;
  942. };
  943. using ContentProvider =
  944. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  945. using ContentProviderWithoutLength =
  946. std::function<bool(size_t offset, DataSink &sink)>;
  947. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  948. struct FormDataProvider {
  949. std::string name;
  950. ContentProviderWithoutLength provider;
  951. std::string filename;
  952. std::string content_type;
  953. };
  954. using FormDataProviderItems = std::vector<FormDataProvider>;
  955. inline FormDataProvider
  956. make_file_provider(const std::string &name, const std::string &filepath,
  957. const std::string &filename = std::string(),
  958. const std::string &content_type = std::string()) {
  959. FormDataProvider fdp;
  960. fdp.name = name;
  961. fdp.filename = filename.empty() ? filepath : filename;
  962. fdp.content_type = content_type;
  963. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  964. std::ifstream f(filepath, std::ios::binary);
  965. if (!f) { return false; }
  966. if (offset > 0) {
  967. f.seekg(static_cast<std::streamoff>(offset));
  968. if (!f.good()) {
  969. sink.done();
  970. return true;
  971. }
  972. }
  973. char buf[8192];
  974. f.read(buf, sizeof(buf));
  975. auto n = static_cast<size_t>(f.gcount());
  976. if (n > 0) { return sink.write(buf, n); }
  977. sink.done(); // EOF
  978. return true;
  979. };
  980. return fdp;
  981. }
  982. inline std::pair<size_t, ContentProvider>
  983. make_file_body(const std::string &filepath) {
  984. size_t size = 0;
  985. {
  986. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  987. if (!f) { return {0, ContentProvider{}}; }
  988. size = static_cast<size_t>(f.tellg());
  989. }
  990. ContentProvider provider = [filepath](size_t offset, size_t length,
  991. DataSink &sink) -> bool {
  992. std::ifstream f(filepath, std::ios::binary);
  993. if (!f) { return false; }
  994. f.seekg(static_cast<std::streamoff>(offset));
  995. if (!f.good()) { return false; }
  996. char buf[8192];
  997. while (length > 0) {
  998. auto to_read = (std::min)(sizeof(buf), length);
  999. f.read(buf, static_cast<std::streamsize>(to_read));
  1000. auto n = static_cast<size_t>(f.gcount());
  1001. if (n == 0) { break; }
  1002. if (!sink.write(buf, n)) { return false; }
  1003. length -= n;
  1004. }
  1005. return true;
  1006. };
  1007. return {size, std::move(provider)};
  1008. }
  1009. using ContentReceiverWithProgress = std::function<bool(
  1010. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1011. using ContentReceiver =
  1012. std::function<bool(const char *data, size_t data_length)>;
  1013. using FormDataHeader = std::function<bool(const FormData &file)>;
  1014. class ContentReader {
  1015. public:
  1016. using Reader = std::function<bool(ContentReceiver receiver)>;
  1017. using FormDataReader =
  1018. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1019. ContentReader(Reader reader, FormDataReader multipart_reader)
  1020. : reader_(std::move(reader)),
  1021. formdata_reader_(std::move(multipart_reader)) {}
  1022. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1023. return formdata_reader_(std::move(header), std::move(receiver));
  1024. }
  1025. bool operator()(ContentReceiver receiver) const {
  1026. return reader_(std::move(receiver));
  1027. }
  1028. Reader reader_;
  1029. FormDataReader formdata_reader_;
  1030. };
  1031. using Range = std::pair<ssize_t, ssize_t>;
  1032. using Ranges = std::vector<Range>;
  1033. #ifdef CPPHTTPLIB_SSL_ENABLED
  1034. // TLS abstraction layer - public type definitions and API
  1035. namespace tls {
  1036. // Opaque handles (defined as void* for abstraction)
  1037. using ctx_t = void *;
  1038. using session_t = void *;
  1039. using const_session_t = const void *; // For read-only session access
  1040. using cert_t = void *;
  1041. using ca_store_t = void *;
  1042. // TLS versions
  1043. enum class Version {
  1044. TLS1_2 = 0x0303,
  1045. TLS1_3 = 0x0304,
  1046. };
  1047. // Subject Alternative Names (SAN) entry types
  1048. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1049. // SAN entry structure
  1050. struct SanEntry {
  1051. SanType type;
  1052. std::string value;
  1053. };
  1054. // Verification context for certificate verification callback
  1055. struct VerifyContext {
  1056. session_t session; // TLS session handle
  1057. cert_t cert; // Current certificate being verified
  1058. int depth; // Certificate chain depth (0 = leaf)
  1059. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1060. long error_code; // Backend-specific error code (0 = no error)
  1061. const char *error_string; // Human-readable error description
  1062. // Certificate introspection methods
  1063. std::string subject_cn() const;
  1064. std::string issuer_name() const;
  1065. bool check_hostname(const char *hostname) const;
  1066. std::vector<SanEntry> sans() const;
  1067. bool validity(time_t &not_before, time_t &not_after) const;
  1068. std::string serial() const;
  1069. };
  1070. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1071. // TlsError codes for TLS operations (backend-independent)
  1072. enum class ErrorCode : int {
  1073. Success = 0,
  1074. WantRead, // Non-blocking: need to wait for read
  1075. WantWrite, // Non-blocking: need to wait for write
  1076. PeerClosed, // Peer closed the connection
  1077. Fatal, // Unrecoverable error
  1078. SyscallError, // System call error (check sys_errno)
  1079. CertVerifyFailed, // Certificate verification failed
  1080. HostnameMismatch, // Hostname verification failed
  1081. };
  1082. // TLS error information
  1083. struct TlsError {
  1084. ErrorCode code = ErrorCode::Fatal;
  1085. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1086. int sys_errno = 0; // errno when SyscallError
  1087. // Convert verification error code to human-readable string
  1088. static std::string verify_error_to_string(long error_code);
  1089. };
  1090. // RAII wrapper for peer certificate
  1091. class PeerCert {
  1092. public:
  1093. PeerCert();
  1094. PeerCert(PeerCert &&other) noexcept;
  1095. PeerCert &operator=(PeerCert &&other) noexcept;
  1096. ~PeerCert();
  1097. PeerCert(const PeerCert &) = delete;
  1098. PeerCert &operator=(const PeerCert &) = delete;
  1099. explicit operator bool() const;
  1100. std::string subject_cn() const;
  1101. std::string issuer_name() const;
  1102. bool check_hostname(const char *hostname) const;
  1103. std::vector<SanEntry> sans() const;
  1104. bool validity(time_t &not_before, time_t &not_after) const;
  1105. std::string serial() const;
  1106. private:
  1107. explicit PeerCert(cert_t cert);
  1108. cert_t cert_ = nullptr;
  1109. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1110. };
  1111. // Callback for TLS context setup (used by SSLServer constructor)
  1112. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1113. } // namespace tls
  1114. #endif
  1115. struct Request {
  1116. std::string method;
  1117. std::string path;
  1118. std::string matched_route;
  1119. Params params;
  1120. Headers headers;
  1121. Headers trailers;
  1122. std::string body;
  1123. std::string remote_addr;
  1124. int remote_port = -1;
  1125. std::string local_addr;
  1126. int local_port = -1;
  1127. // for server
  1128. std::string version;
  1129. std::string target;
  1130. MultipartFormData form;
  1131. Ranges ranges;
  1132. Match matches;
  1133. std::unordered_map<std::string, std::string> path_params;
  1134. std::function<bool()> is_connection_closed = []() { return true; };
  1135. // for client
  1136. std::vector<std::string> accept_content_types;
  1137. ResponseHandler response_handler;
  1138. ContentReceiverWithProgress content_receiver;
  1139. DownloadProgress download_progress;
  1140. UploadProgress upload_progress;
  1141. bool has_header(const std::string &key) const;
  1142. std::string get_header_value(const std::string &key, const char *def = "",
  1143. size_t id = 0) const;
  1144. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1145. size_t id = 0) const;
  1146. size_t get_header_value_count(const std::string &key) const;
  1147. void set_header(const std::string &key, const std::string &val);
  1148. bool has_trailer(const std::string &key) const;
  1149. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1150. size_t get_trailer_value_count(const std::string &key) const;
  1151. bool has_param(const std::string &key) const;
  1152. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1153. std::vector<std::string> get_param_values(const std::string &key) const;
  1154. size_t get_param_value_count(const std::string &key) const;
  1155. bool is_multipart_form_data() const;
  1156. // private members...
  1157. bool body_consumed_ = false;
  1158. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1159. size_t content_length_ = 0;
  1160. ContentProvider content_provider_;
  1161. bool is_chunked_content_provider_ = false;
  1162. size_t authorization_count_ = 0;
  1163. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1164. (std::chrono::steady_clock::time_point::min)();
  1165. #ifdef CPPHTTPLIB_SSL_ENABLED
  1166. tls::const_session_t ssl = nullptr;
  1167. tls::PeerCert peer_cert() const;
  1168. std::string sni() const;
  1169. #endif
  1170. };
  1171. struct Response {
  1172. std::string version;
  1173. int status = -1;
  1174. std::string reason;
  1175. Headers headers;
  1176. Headers trailers;
  1177. std::string body;
  1178. std::string location; // Redirect location
  1179. // User-defined context — set by pre-routing/pre-request handlers and read
  1180. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1181. UserData user_data;
  1182. bool has_header(const std::string &key) const;
  1183. std::string get_header_value(const std::string &key, const char *def = "",
  1184. size_t id = 0) const;
  1185. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1186. size_t id = 0) const;
  1187. size_t get_header_value_count(const std::string &key) const;
  1188. void set_header(const std::string &key, const std::string &val);
  1189. bool has_trailer(const std::string &key) const;
  1190. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1191. size_t get_trailer_value_count(const std::string &key) const;
  1192. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1193. void set_content(const char *s, size_t n, const std::string &content_type);
  1194. void set_content(const std::string &s, const std::string &content_type);
  1195. void set_content(std::string &&s, const std::string &content_type);
  1196. void set_content_provider(
  1197. size_t length, const std::string &content_type, ContentProvider provider,
  1198. ContentProviderResourceReleaser resource_releaser = nullptr);
  1199. void set_content_provider(
  1200. const std::string &content_type, ContentProviderWithoutLength provider,
  1201. ContentProviderResourceReleaser resource_releaser = nullptr);
  1202. void set_chunked_content_provider(
  1203. const std::string &content_type, ContentProviderWithoutLength provider,
  1204. ContentProviderResourceReleaser resource_releaser = nullptr);
  1205. void set_file_content(const std::string &path,
  1206. const std::string &content_type);
  1207. void set_file_content(const std::string &path);
  1208. Response() = default;
  1209. Response(const Response &) = default;
  1210. Response &operator=(const Response &) = default;
  1211. Response(Response &&) = default;
  1212. Response &operator=(Response &&) = default;
  1213. ~Response() {
  1214. if (content_provider_resource_releaser_) {
  1215. content_provider_resource_releaser_(content_provider_success_);
  1216. }
  1217. }
  1218. // private members...
  1219. size_t content_length_ = 0;
  1220. ContentProvider content_provider_;
  1221. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1222. bool is_chunked_content_provider_ = false;
  1223. bool content_provider_success_ = false;
  1224. std::string file_content_path_;
  1225. std::string file_content_content_type_;
  1226. };
  1227. enum class Error {
  1228. Success = 0,
  1229. Unknown,
  1230. Connection,
  1231. BindIPAddress,
  1232. Read,
  1233. Write,
  1234. ExceedRedirectCount,
  1235. Canceled,
  1236. SSLConnection,
  1237. SSLLoadingCerts,
  1238. SSLServerVerification,
  1239. SSLServerHostnameVerification,
  1240. UnsupportedMultipartBoundaryChars,
  1241. Compression,
  1242. ConnectionTimeout,
  1243. ProxyConnection,
  1244. ConnectionClosed,
  1245. Timeout,
  1246. ResourceExhaustion,
  1247. TooManyFormDataFiles,
  1248. ExceedMaxPayloadSize,
  1249. ExceedUriMaxLength,
  1250. ExceedMaxSocketDescriptorCount,
  1251. InvalidRequestLine,
  1252. InvalidHTTPMethod,
  1253. InvalidHTTPVersion,
  1254. InvalidHeaders,
  1255. MultipartParsing,
  1256. OpenFile,
  1257. Listen,
  1258. GetSockName,
  1259. UnsupportedAddressFamily,
  1260. HTTPParsing,
  1261. InvalidRangeHeader,
  1262. // For internal use only
  1263. SSLPeerCouldBeClosed_,
  1264. };
  1265. std::string to_string(Error error);
  1266. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1267. class Stream {
  1268. public:
  1269. virtual ~Stream() = default;
  1270. virtual bool is_readable() const = 0;
  1271. virtual bool wait_readable() const = 0;
  1272. virtual bool wait_writable() const = 0;
  1273. virtual bool is_peer_alive() const { return wait_writable(); }
  1274. virtual ssize_t read(char *ptr, size_t size) = 0;
  1275. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1276. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1277. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1278. virtual socket_t socket() const = 0;
  1279. virtual time_t duration() const = 0;
  1280. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1281. (void)sec;
  1282. (void)usec;
  1283. }
  1284. ssize_t write(const char *ptr);
  1285. ssize_t write(const std::string &s);
  1286. Error get_error() const { return error_; }
  1287. protected:
  1288. Error error_ = Error::Success;
  1289. };
  1290. class TaskQueue {
  1291. public:
  1292. TaskQueue() = default;
  1293. virtual ~TaskQueue() = default;
  1294. virtual bool enqueue(std::function<void()> fn) = 0;
  1295. virtual void shutdown() = 0;
  1296. virtual void on_idle() {}
  1297. };
  1298. class ThreadPool final : public TaskQueue {
  1299. public:
  1300. explicit ThreadPool(
  1301. size_t n, size_t max_n = 0, size_t mqr = 0,
  1302. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1303. ThreadPool(const ThreadPool &) = delete;
  1304. ~ThreadPool() override = default;
  1305. bool enqueue(std::function<void()> fn) override;
  1306. void shutdown() override;
  1307. private:
  1308. void worker(bool is_dynamic);
  1309. void move_to_finished(std::thread::id id);
  1310. void cleanup_finished_threads();
  1311. size_t base_thread_count_;
  1312. size_t max_thread_count_;
  1313. size_t max_queued_requests_;
  1314. time_t idle_timeout_sec_;
  1315. size_t idle_thread_count_;
  1316. bool shutdown_;
  1317. std::list<std::function<void()>> jobs_;
  1318. std::vector<std::thread> threads_; // base threads
  1319. std::list<std::thread> dynamic_threads_; // dynamic threads
  1320. std::vector<std::thread>
  1321. finished_threads_; // exited dynamic threads awaiting join
  1322. std::condition_variable cond_;
  1323. std::mutex mutex_;
  1324. };
  1325. using Logger = std::function<void(const Request &, const Response &)>;
  1326. // Forward declaration for Error type
  1327. enum class Error;
  1328. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1329. using SocketOptions = std::function<void(socket_t sock)>;
  1330. void default_socket_options(socket_t sock);
  1331. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1332. const char *status_message(int status);
  1333. std::string to_string(Error error);
  1334. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1335. std::string get_bearer_token_auth(const Request &req);
  1336. namespace detail {
  1337. class MatcherBase {
  1338. public:
  1339. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1340. virtual ~MatcherBase() = default;
  1341. const std::string &pattern() const { return pattern_; }
  1342. // Match request path and populate its matches and
  1343. virtual bool match(Request &request) const = 0;
  1344. private:
  1345. std::string pattern_;
  1346. };
  1347. /**
  1348. * Captures parameters in request path and stores them in Request::path_params
  1349. *
  1350. * Capture name is a substring of a pattern from : to /.
  1351. * The rest of the pattern is matched against the request path directly
  1352. * Parameters are captured starting from the next character after
  1353. * the end of the last matched static pattern fragment until the next /.
  1354. *
  1355. * Example pattern:
  1356. * "/path/fragments/:capture/more/fragments/:second_capture"
  1357. * Static fragments:
  1358. * "/path/fragments/", "more/fragments/"
  1359. *
  1360. * Given the following request path:
  1361. * "/path/fragments/:1/more/fragments/:2"
  1362. * the resulting capture will be
  1363. * {{"capture", "1"}, {"second_capture", "2"}}
  1364. */
  1365. class PathParamsMatcher final : public MatcherBase {
  1366. public:
  1367. PathParamsMatcher(const std::string &pattern);
  1368. bool match(Request &request) const override;
  1369. private:
  1370. // Treat segment separators as the end of path parameter capture
  1371. // Does not need to handle query parameters as they are parsed before path
  1372. // matching
  1373. static constexpr char separator = '/';
  1374. // Contains static path fragments to match against, excluding the '/' after
  1375. // path params
  1376. // Fragments are separated by path params
  1377. std::vector<std::string> static_fragments_;
  1378. // Stores the names of the path parameters to be used as keys in the
  1379. // Request::path_params map
  1380. std::vector<std::string> param_names_;
  1381. };
  1382. /**
  1383. * Performs std::regex_match on request path
  1384. * and stores the result in Request::matches
  1385. *
  1386. * Note that regex match is performed directly on the whole request.
  1387. * This means that wildcard patterns may match multiple path segments with /:
  1388. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1389. */
  1390. class RegexMatcher final : public MatcherBase {
  1391. public:
  1392. RegexMatcher(const std::string &pattern)
  1393. : MatcherBase(pattern), regex_(pattern) {}
  1394. bool match(Request &request) const override;
  1395. private:
  1396. std::regex regex_;
  1397. };
  1398. int close_socket(socket_t sock) noexcept;
  1399. ssize_t write_headers(Stream &strm, const Headers &headers);
  1400. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1401. time_t usec);
  1402. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1403. const std::string &boundary);
  1404. ContentProvider
  1405. make_multipart_content_provider(const UploadFormDataItems &items,
  1406. const std::string &boundary);
  1407. } // namespace detail
  1408. bool is_valid_multipart_boundary(const std::string &boundary);
  1409. // Serializer for multipart/form-data request bodies. The boundary is owned
  1410. // by the writer so that per-part framing and the final terminator always
  1411. // agree. Field names and filenames are escaped following the WHATWG HTML
  1412. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1413. // in content types.
  1414. class MultipartFormDataWriter {
  1415. public:
  1416. MultipartFormDataWriter();
  1417. // precondition: is_valid_multipart_boundary(boundary)
  1418. explicit MultipartFormDataWriter(std::string boundary);
  1419. const std::string &boundary() const;
  1420. std::string content_type() const;
  1421. // In-memory items -> whole body (known length)
  1422. std::string serialize(const UploadFormDataItems &items) const;
  1423. size_t content_length(const UploadFormDataItems &items) const;
  1424. // Per-part framing for streaming via a content provider
  1425. std::string item_begin(const UploadFormData &item) const;
  1426. static std::string item_end();
  1427. std::string finish() const;
  1428. private:
  1429. std::string boundary_;
  1430. };
  1431. class Server {
  1432. public:
  1433. using Handler = std::function<void(const Request &, Response &)>;
  1434. using ExceptionHandler =
  1435. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1436. enum class HandlerResponse {
  1437. Handled,
  1438. Unhandled,
  1439. };
  1440. using HandlerWithResponse =
  1441. std::function<HandlerResponse(const Request &, Response &)>;
  1442. using HandlerWithContentReader = std::function<void(
  1443. const Request &, Response &, const ContentReader &content_reader)>;
  1444. using Expect100ContinueHandler =
  1445. std::function<int(const Request &, Response &)>;
  1446. using StartHandler = std::function<void()>;
  1447. using WebSocketHandler =
  1448. std::function<void(const Request &, ws::WebSocket &)>;
  1449. using SubProtocolSelector =
  1450. std::function<std::string(const std::vector<std::string> &protocols)>;
  1451. Server();
  1452. virtual ~Server();
  1453. virtual bool is_valid() const;
  1454. Server &Get(const std::string &pattern, Handler handler);
  1455. Server &Post(const std::string &pattern, Handler handler);
  1456. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1457. Server &Put(const std::string &pattern, Handler handler);
  1458. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1459. Server &Patch(const std::string &pattern, Handler handler);
  1460. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1461. Server &Delete(const std::string &pattern, Handler handler);
  1462. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1463. Server &Options(const std::string &pattern, Handler handler);
  1464. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1465. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1466. SubProtocolSelector sub_protocol_selector);
  1467. bool set_base_dir(const std::string &dir,
  1468. const std::string &mount_point = std::string());
  1469. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1470. Headers headers = Headers());
  1471. bool remove_mount_point(const std::string &mount_point);
  1472. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1473. const std::string &mime);
  1474. Server &set_default_file_mimetype(const std::string &mime);
  1475. Server &set_file_request_handler(Handler handler);
  1476. template <class ErrorHandlerFunc>
  1477. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1478. return set_error_handler_core(
  1479. std::forward<ErrorHandlerFunc>(handler),
  1480. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1481. }
  1482. Server &set_exception_handler(ExceptionHandler handler);
  1483. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1484. Server &set_post_routing_handler(Handler handler);
  1485. Server &set_pre_request_handler(HandlerWithResponse handler);
  1486. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1487. Server &set_start_handler(StartHandler handler);
  1488. Server &set_logger(Logger logger);
  1489. Server &set_pre_compression_logger(Logger logger);
  1490. Server &set_error_logger(ErrorLogger error_logger);
  1491. Server &set_address_family(int family);
  1492. Server &set_tcp_nodelay(bool on);
  1493. Server &set_ipv6_v6only(bool on);
  1494. Server &set_socket_options(SocketOptions socket_options);
  1495. Server &set_default_headers(Headers headers);
  1496. Server &
  1497. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1498. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1499. Server &set_keep_alive_max_count(size_t count);
  1500. Server &set_keep_alive_timeout(time_t sec);
  1501. template <class Rep, class Period>
  1502. Server &
  1503. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1505. template <class Rep, class Period>
  1506. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1508. template <class Rep, class Period>
  1509. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1510. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1511. template <class Rep, class Period>
  1512. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1513. Server &set_payload_max_length(size_t length);
  1514. Server &set_websocket_ping_interval(time_t sec);
  1515. template <class Rep, class Period>
  1516. Server &set_websocket_ping_interval(
  1517. const std::chrono::duration<Rep, Period> &duration);
  1518. Server &set_websocket_max_missed_pongs(int count);
  1519. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1520. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1521. bool listen_after_bind();
  1522. bool listen(const std::string &host, int port, int socket_flags = 0);
  1523. bool is_running() const;
  1524. void wait_until_ready() const;
  1525. void stop() noexcept;
  1526. void decommission();
  1527. std::function<TaskQueue *(void)> new_task_queue;
  1528. protected:
  1529. bool process_request(Stream &strm, const std::string &remote_addr,
  1530. int remote_port, const std::string &local_addr,
  1531. int local_port, bool close_connection,
  1532. bool &connection_closed,
  1533. const std::function<void(Request &)> &setup_request,
  1534. bool *websocket_upgraded = nullptr);
  1535. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1536. std::vector<std::string> trusted_proxies_;
  1537. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1538. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1539. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1540. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1541. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1542. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1543. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1544. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1545. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1546. time_t websocket_ping_interval_sec_ =
  1547. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1548. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1549. private:
  1550. using Handlers =
  1551. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1552. using HandlersForContentReader =
  1553. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1554. HandlerWithContentReader>>;
  1555. static std::unique_ptr<detail::MatcherBase>
  1556. make_matcher(const std::string &pattern);
  1557. template <typename H>
  1558. Server &add_handler(
  1559. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1560. const std::string &pattern, H handler) {
  1561. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1562. return *this;
  1563. }
  1564. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1565. Server &set_error_handler_core(Handler handler, std::false_type);
  1566. socket_t create_server_socket(const std::string &host, int port,
  1567. int socket_flags,
  1568. SocketOptions socket_options) const;
  1569. int bind_internal(const std::string &host, int port, int socket_flags);
  1570. bool listen_internal();
  1571. bool routing(Request &req, Response &res, Stream &strm);
  1572. bool handle_file_request(Request &req, Response &res);
  1573. bool check_if_not_modified(const Request &req, Response &res,
  1574. const std::string &etag, time_t mtime) const;
  1575. bool check_if_range(Request &req, const std::string &etag,
  1576. time_t mtime) const;
  1577. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1578. Stream &strm);
  1579. bool dispatch_request_for_content_reader(
  1580. Request &req, Response &res, ContentReader content_reader,
  1581. const HandlersForContentReader &handlers) const;
  1582. bool parse_request_line(const char *s, Request &req) const;
  1583. void apply_ranges(const Request &req, Response &res,
  1584. std::string &content_type, std::string &boundary) const;
  1585. bool write_response(Stream &strm, bool close_connection, Request &req,
  1586. Response &res);
  1587. bool write_response_with_content(Stream &strm, bool close_connection,
  1588. const Request &req, Response &res);
  1589. bool write_response_core(Stream &strm, bool close_connection,
  1590. const Request &req, Response &res,
  1591. bool need_apply_ranges);
  1592. bool write_content_with_provider(Stream &strm, const Request &req,
  1593. Response &res, const std::string &boundary,
  1594. const std::string &content_type);
  1595. bool read_content(Stream &strm, Request &req, Response &res);
  1596. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1597. Response &res,
  1598. ContentReceiver receiver,
  1599. FormDataHeader multipart_header,
  1600. ContentReceiver multipart_receiver);
  1601. bool read_content_core(Stream &strm, Request &req, Response &res,
  1602. ContentReceiver receiver,
  1603. FormDataHeader multipart_header,
  1604. ContentReceiver multipart_receiver) const;
  1605. virtual bool process_and_close_socket(socket_t sock);
  1606. void output_log(const Request &req, const Response &res) const;
  1607. void output_pre_compression_log(const Request &req,
  1608. const Response &res) const;
  1609. void output_error_log(const Error &err, const Request *req) const;
  1610. std::atomic<bool> is_running_{false};
  1611. std::atomic<bool> is_decommissioned{false};
  1612. struct MountPointEntry {
  1613. std::string mount_point;
  1614. std::string base_dir;
  1615. std::string resolved_base_dir;
  1616. Headers headers;
  1617. };
  1618. std::vector<MountPointEntry> base_dirs_;
  1619. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1620. std::string default_file_mimetype_ = "application/octet-stream";
  1621. Handler file_request_handler_;
  1622. Handlers get_handlers_;
  1623. Handlers post_handlers_;
  1624. HandlersForContentReader post_handlers_for_content_reader_;
  1625. Handlers put_handlers_;
  1626. HandlersForContentReader put_handlers_for_content_reader_;
  1627. Handlers patch_handlers_;
  1628. HandlersForContentReader patch_handlers_for_content_reader_;
  1629. Handlers delete_handlers_;
  1630. HandlersForContentReader delete_handlers_for_content_reader_;
  1631. Handlers options_handlers_;
  1632. struct WebSocketHandlerEntry {
  1633. std::unique_ptr<detail::MatcherBase> matcher;
  1634. WebSocketHandler handler;
  1635. SubProtocolSelector sub_protocol_selector;
  1636. };
  1637. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1638. WebSocketHandlers websocket_handlers_;
  1639. HandlerWithResponse error_handler_;
  1640. ExceptionHandler exception_handler_;
  1641. HandlerWithResponse pre_routing_handler_;
  1642. Handler post_routing_handler_;
  1643. HandlerWithResponse pre_request_handler_;
  1644. Expect100ContinueHandler expect_100_continue_handler_;
  1645. StartHandler start_handler_;
  1646. mutable std::mutex logger_mutex_;
  1647. Logger logger_;
  1648. Logger pre_compression_logger_;
  1649. ErrorLogger error_logger_;
  1650. int address_family_ = AF_UNSPEC;
  1651. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1652. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1653. SocketOptions socket_options_ = default_socket_options;
  1654. Headers default_headers_;
  1655. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1656. detail::write_headers;
  1657. };
  1658. class Result {
  1659. public:
  1660. Result() = default;
  1661. Result(std::unique_ptr<Response> &&res, Error err,
  1662. Headers &&request_headers = Headers{})
  1663. : res_(std::move(res)), err_(err),
  1664. request_headers_(std::move(request_headers)) {}
  1665. // Response
  1666. operator bool() const { return res_ != nullptr; }
  1667. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1668. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1669. const Response &value() const { return *res_; }
  1670. Response &value() { return *res_; }
  1671. const Response &operator*() const { return *res_; }
  1672. Response &operator*() { return *res_; }
  1673. const Response *operator->() const { return res_.get(); }
  1674. Response *operator->() { return res_.get(); }
  1675. // Error
  1676. Error error() const { return err_; }
  1677. // Request Headers
  1678. bool has_request_header(const std::string &key) const;
  1679. std::string get_request_header_value(const std::string &key,
  1680. const char *def = "",
  1681. size_t id = 0) const;
  1682. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1683. size_t id = 0) const;
  1684. size_t get_request_header_value_count(const std::string &key) const;
  1685. private:
  1686. std::unique_ptr<Response> res_;
  1687. Error err_ = Error::Unknown;
  1688. Headers request_headers_;
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. public:
  1691. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1692. int ssl_error)
  1693. : res_(std::move(res)), err_(err),
  1694. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1695. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1696. int ssl_error, uint64_t ssl_backend_error)
  1697. : res_(std::move(res)), err_(err),
  1698. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1699. ssl_backend_error_(ssl_backend_error) {}
  1700. int ssl_error() const { return ssl_error_; }
  1701. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1702. private:
  1703. int ssl_error_ = 0;
  1704. uint64_t ssl_backend_error_ = 0;
  1705. #endif
  1706. };
  1707. struct ClientConnection {
  1708. socket_t sock = INVALID_SOCKET;
  1709. bool is_open() const { return sock != INVALID_SOCKET; }
  1710. ClientConnection() = default;
  1711. ~ClientConnection();
  1712. ClientConnection(const ClientConnection &) = delete;
  1713. ClientConnection &operator=(const ClientConnection &) = delete;
  1714. ClientConnection(ClientConnection &&other) noexcept
  1715. : sock(other.sock)
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. ,
  1718. session(other.session)
  1719. #endif
  1720. {
  1721. other.sock = INVALID_SOCKET;
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. other.session = nullptr;
  1724. #endif
  1725. }
  1726. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1727. if (this != &other) {
  1728. sock = other.sock;
  1729. other.sock = INVALID_SOCKET;
  1730. #ifdef CPPHTTPLIB_SSL_ENABLED
  1731. session = other.session;
  1732. other.session = nullptr;
  1733. #endif
  1734. }
  1735. return *this;
  1736. }
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. tls::session_t session = nullptr;
  1739. #endif
  1740. };
  1741. namespace detail {
  1742. struct ChunkedDecoder;
  1743. struct BodyReader {
  1744. Stream *stream = nullptr;
  1745. bool has_content_length = false;
  1746. size_t content_length = 0;
  1747. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1748. size_t bytes_read = 0;
  1749. bool chunked = false;
  1750. bool eof = false;
  1751. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1752. Error last_error = Error::Success;
  1753. ssize_t read(char *buf, size_t len);
  1754. bool has_error() const { return last_error != Error::Success; }
  1755. };
  1756. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1757. size_t len) {
  1758. (void)stream;
  1759. return br.read(buf, len);
  1760. }
  1761. class decompressor;
  1762. enum class NoProxyKind {
  1763. Wildcard, // "*"
  1764. HostnameSuffix, // "example.com" or ".example.com"
  1765. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1766. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1767. };
  1768. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1769. // Lets one CIDR matcher cover both families.
  1770. using IPBytes = std::array<uint8_t, 16>;
  1771. struct NoProxyEntry {
  1772. NoProxyKind kind = NoProxyKind::Wildcard;
  1773. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1774. IPBytes net{};
  1775. int prefix_bits = 0;
  1776. };
  1777. struct NormalizedTarget {
  1778. std::string hostname; // lowercase; brackets and trailing dot removed
  1779. bool is_ipv4 = false;
  1780. bool is_ipv6 = false;
  1781. IPBytes ip{};
  1782. };
  1783. } // namespace detail
  1784. class ClientImpl {
  1785. public:
  1786. explicit ClientImpl(const std::string &host);
  1787. explicit ClientImpl(const std::string &host, int port);
  1788. explicit ClientImpl(const std::string &host, int port,
  1789. const std::string &client_cert_path,
  1790. const std::string &client_key_path);
  1791. virtual ~ClientImpl();
  1792. virtual bool is_valid() const;
  1793. struct StreamHandle {
  1794. std::unique_ptr<Response> response;
  1795. Error error = Error::Success;
  1796. StreamHandle() = default;
  1797. StreamHandle(const StreamHandle &) = delete;
  1798. StreamHandle &operator=(const StreamHandle &) = delete;
  1799. StreamHandle(StreamHandle &&) = default;
  1800. StreamHandle &operator=(StreamHandle &&) = default;
  1801. ~StreamHandle() = default;
  1802. bool is_valid() const {
  1803. return response != nullptr && error == Error::Success;
  1804. }
  1805. ssize_t read(char *buf, size_t len);
  1806. void parse_trailers_if_needed();
  1807. Error get_read_error() const { return body_reader_.last_error; }
  1808. bool has_read_error() const { return body_reader_.has_error(); }
  1809. bool trailers_parsed_ = false;
  1810. private:
  1811. friend class ClientImpl;
  1812. ssize_t read_with_decompression(char *buf, size_t len);
  1813. std::unique_ptr<ClientConnection> connection_;
  1814. std::unique_ptr<Stream> socket_stream_;
  1815. Stream *stream_ = nullptr;
  1816. detail::BodyReader body_reader_;
  1817. std::unique_ptr<detail::decompressor> decompressor_;
  1818. std::string decompress_buffer_;
  1819. size_t decompress_offset_ = 0;
  1820. size_t decompressed_bytes_read_ = 0;
  1821. };
  1822. // clang-format off
  1823. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1824. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1825. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1826. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1827. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1828. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1829. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1830. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1831. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1832. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1833. Result Head(const std::string &path);
  1834. Result Head(const std::string &path, const Headers &headers);
  1835. Result Post(const std::string &path);
  1836. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1840. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1842. Result Post(const std::string &path, const Params &params);
  1843. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1844. Result Post(const std::string &path, const Headers &headers);
  1845. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1847. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1848. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1849. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1851. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1852. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1855. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1856. Result Put(const std::string &path);
  1857. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1861. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1863. Result Put(const std::string &path, const Params &params);
  1864. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1865. Result Put(const std::string &path, const Headers &headers);
  1866. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1868. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1869. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1870. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1872. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1873. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1876. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1877. Result Patch(const std::string &path);
  1878. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1882. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1884. Result Patch(const std::string &path, const Params &params);
  1885. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1886. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1887. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1888. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1889. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1890. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1891. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1893. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1894. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1897. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1898. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1899. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1900. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1901. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1902. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1903. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1904. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1905. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1906. Result Options(const std::string &path);
  1907. Result Options(const std::string &path, const Headers &headers);
  1908. // clang-format on
  1909. // Streaming API: Open a stream for reading response body incrementally
  1910. // Socket ownership is transferred to StreamHandle for true streaming
  1911. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1912. StreamHandle open_stream(const std::string &method, const std::string &path,
  1913. const Params &params = {},
  1914. const Headers &headers = {},
  1915. const std::string &body = {},
  1916. const std::string &content_type = {});
  1917. bool send(Request &req, Response &res, Error &error);
  1918. Result send(const Request &req);
  1919. void stop();
  1920. std::string host() const;
  1921. int port() const;
  1922. size_t is_socket_open() const;
  1923. socket_t socket() const;
  1924. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1925. void set_default_headers(Headers headers);
  1926. void
  1927. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1928. void set_address_family(int family);
  1929. void set_tcp_nodelay(bool on);
  1930. void set_ipv6_v6only(bool on);
  1931. void set_socket_options(SocketOptions socket_options);
  1932. void set_connection_timeout(time_t sec, time_t usec = 0);
  1933. template <class Rep, class Period>
  1934. void
  1935. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1936. void set_read_timeout(time_t sec, time_t usec = 0);
  1937. template <class Rep, class Period>
  1938. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1939. void set_write_timeout(time_t sec, time_t usec = 0);
  1940. template <class Rep, class Period>
  1941. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1942. void set_max_timeout(time_t msec);
  1943. template <class Rep, class Period>
  1944. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1945. void set_basic_auth(const std::string &username, const std::string &password);
  1946. void set_bearer_token_auth(const std::string &token);
  1947. void set_keep_alive(bool on);
  1948. void set_follow_location(bool on);
  1949. void set_path_encode(bool on);
  1950. void set_compress(bool on);
  1951. void set_decompress(bool on);
  1952. void set_payload_max_length(size_t length);
  1953. void set_interface(const std::string &intf);
  1954. void set_proxy(const std::string &host, int port);
  1955. void set_proxy_basic_auth(const std::string &username,
  1956. const std::string &password);
  1957. void set_proxy_bearer_token_auth(const std::string &token);
  1958. void set_no_proxy(const std::vector<std::string> &patterns);
  1959. void set_logger(Logger logger);
  1960. void set_error_logger(ErrorLogger error_logger);
  1961. protected:
  1962. struct Socket {
  1963. socket_t sock = INVALID_SOCKET;
  1964. // For Mbed TLS compatibility: start_time for request timeout tracking
  1965. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1966. bool is_open() const { return sock != INVALID_SOCKET; }
  1967. #ifdef CPPHTTPLIB_SSL_ENABLED
  1968. tls::session_t ssl = nullptr;
  1969. #endif
  1970. };
  1971. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1972. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1973. virtual bool setup_proxy_connection(
  1974. Socket &socket,
  1975. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1976. Response &res, bool &success, Error &error);
  1977. bool is_proxy_enabled_for_host(const std::string &host) const;
  1978. // All of:
  1979. // shutdown_ssl
  1980. // shutdown_socket
  1981. // close_socket
  1982. // disconnect
  1983. // should ONLY be called when socket_mutex_ is locked, and only when
  1984. // no other thread is using the socket.
  1985. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1986. void shutdown_socket(Socket &socket) const;
  1987. void close_socket(Socket &socket);
  1988. void disconnect(bool gracefully);
  1989. bool process_request(Stream &strm, Request &req, Response &res,
  1990. bool close_connection, Error &error);
  1991. bool write_content_with_provider(Stream &strm, const Request &req,
  1992. Error &error) const;
  1993. void copy_settings(const ClientImpl &rhs);
  1994. void output_log(const Request &req, const Response &res) const;
  1995. void output_error_log(const Error &err, const Request *req) const;
  1996. // Socket endpoint information
  1997. const std::string host_;
  1998. const int port_;
  1999. // Current open socket
  2000. Socket socket_;
  2001. mutable std::mutex socket_mutex_;
  2002. std::recursive_mutex request_mutex_;
  2003. // These are all protected under socket_mutex
  2004. size_t socket_requests_in_flight_ = 0;
  2005. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2006. bool socket_should_be_closed_when_request_is_done_ = false;
  2007. // Hostname-IP map
  2008. std::map<std::string, std::string> addr_map_;
  2009. // Default headers
  2010. Headers default_headers_;
  2011. // Header writer
  2012. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2013. detail::write_headers;
  2014. // Settings
  2015. std::string client_cert_path_;
  2016. std::string client_key_path_;
  2017. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2018. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2019. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2020. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2021. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2022. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2023. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2024. std::string basic_auth_username_;
  2025. std::string basic_auth_password_;
  2026. std::string bearer_token_auth_token_;
  2027. bool keep_alive_ = false;
  2028. bool follow_location_ = false;
  2029. bool path_encode_ = true;
  2030. int address_family_ = AF_UNSPEC;
  2031. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2032. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2033. SocketOptions socket_options_ = nullptr;
  2034. bool compress_ = false;
  2035. bool decompress_ = true;
  2036. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2037. bool has_payload_max_length_ = false;
  2038. std::string interface_;
  2039. std::string proxy_host_;
  2040. int proxy_port_ = -1;
  2041. std::string proxy_basic_auth_username_;
  2042. std::string proxy_basic_auth_password_;
  2043. std::string proxy_bearer_token_auth_token_;
  2044. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2045. mutable detail::NormalizedTarget host_normalized_;
  2046. mutable bool host_normalized_valid_ = false;
  2047. mutable std::mutex logger_mutex_;
  2048. Logger logger_;
  2049. ErrorLogger error_logger_;
  2050. private:
  2051. bool send_(Request &req, Response &res, Error &error);
  2052. Result send_(Request &&req);
  2053. socket_t create_client_socket(Error &error) const;
  2054. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2055. bool skip_100_continue = true) const;
  2056. bool write_request(Stream &strm, Request &req, bool close_connection,
  2057. Error &error, bool skip_body = false);
  2058. bool write_request_body(Stream &strm, Request &req, Error &error);
  2059. void prepare_default_headers(Request &r, bool for_stream,
  2060. const std::string &ct);
  2061. bool redirect(Request &req, Response &res, Error &error);
  2062. bool create_redirect_client(const std::string &scheme,
  2063. const std::string &host, int port, Request &req,
  2064. Response &res, const std::string &path,
  2065. const std::string &location, Error &error);
  2066. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2067. bool handle_request(Stream &strm, Request &req, Response &res,
  2068. bool close_connection, Error &error);
  2069. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2070. Request &req, const char *body, size_t content_length,
  2071. ContentProvider content_provider,
  2072. ContentProviderWithoutLength content_provider_without_length,
  2073. const std::string &content_type, ContentReceiver content_receiver,
  2074. Error &error);
  2075. Result send_with_content_provider_and_receiver(
  2076. const std::string &method, const std::string &path,
  2077. const Headers &headers, const char *body, size_t content_length,
  2078. ContentProvider content_provider,
  2079. ContentProviderWithoutLength content_provider_without_length,
  2080. const std::string &content_type, ContentReceiver content_receiver,
  2081. UploadProgress progress);
  2082. ContentProviderWithoutLength get_multipart_content_provider(
  2083. const std::string &boundary, const UploadFormDataItems &items,
  2084. const FormDataProviderItems &provider_items) const;
  2085. virtual bool
  2086. process_socket(const Socket &socket,
  2087. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2088. std::function<bool(Stream &strm)> callback);
  2089. virtual bool is_ssl() const;
  2090. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2091. #ifdef CPPHTTPLIB_SSL_ENABLED
  2092. public:
  2093. void set_digest_auth(const std::string &username,
  2094. const std::string &password);
  2095. void set_proxy_digest_auth(const std::string &username,
  2096. const std::string &password);
  2097. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2098. const std::string &ca_cert_dir_path = std::string());
  2099. void enable_server_certificate_verification(bool enabled);
  2100. void enable_server_hostname_verification(bool enabled);
  2101. void enable_system_ca(bool enabled);
  2102. protected:
  2103. std::string digest_auth_username_;
  2104. std::string digest_auth_password_;
  2105. std::string proxy_digest_auth_username_;
  2106. std::string proxy_digest_auth_password_;
  2107. std::string ca_cert_file_path_;
  2108. std::string ca_cert_dir_path_;
  2109. bool server_certificate_verification_ = true;
  2110. bool server_hostname_verification_ = true;
  2111. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2112. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2113. int last_ssl_error_ = 0;
  2114. uint64_t last_backend_error_ = 0;
  2115. #endif
  2116. };
  2117. class Client {
  2118. public:
  2119. // Universal interface
  2120. explicit Client(const std::string &scheme_host_port);
  2121. explicit Client(const std::string &scheme_host_port,
  2122. const std::string &client_cert_path,
  2123. const std::string &client_key_path);
  2124. // HTTP only interface
  2125. explicit Client(const std::string &host, int port);
  2126. explicit Client(const std::string &host, int port,
  2127. const std::string &client_cert_path,
  2128. const std::string &client_key_path);
  2129. Client(Client &&) = default;
  2130. Client &operator=(Client &&) = default;
  2131. ~Client();
  2132. bool is_valid() const;
  2133. // clang-format off
  2134. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2135. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2136. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2137. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2138. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2139. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2142. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2143. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2144. Result Head(const std::string &path);
  2145. Result Head(const std::string &path, const Headers &headers);
  2146. Result Post(const std::string &path);
  2147. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2150. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2152. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Params &params);
  2154. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, const Headers &headers);
  2156. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2158. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2159. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2160. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2163. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2165. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2167. Result Put(const std::string &path);
  2168. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2173. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Params &params);
  2175. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, const Headers &headers);
  2177. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2179. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2180. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2181. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2184. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2186. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2188. Result Patch(const std::string &path);
  2189. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2194. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Params &params);
  2196. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, const Headers &headers);
  2198. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2199. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2200. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2201. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2202. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2205. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2207. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2209. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2210. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2211. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2212. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2213. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2215. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2216. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2217. Result Options(const std::string &path);
  2218. Result Options(const std::string &path, const Headers &headers);
  2219. // clang-format on
  2220. // Streaming API: Open a stream for reading response body incrementally
  2221. // Socket ownership is transferred to StreamHandle for true streaming
  2222. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2223. ClientImpl::StreamHandle open_stream(const std::string &method,
  2224. const std::string &path,
  2225. const Params &params = {},
  2226. const Headers &headers = {},
  2227. const std::string &body = {},
  2228. const std::string &content_type = {});
  2229. bool send(Request &req, Response &res, Error &error);
  2230. Result send(const Request &req);
  2231. void stop();
  2232. std::string host() const;
  2233. int port() const;
  2234. size_t is_socket_open() const;
  2235. socket_t socket() const;
  2236. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2237. void set_default_headers(Headers headers);
  2238. void
  2239. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2240. void set_address_family(int family);
  2241. void set_tcp_nodelay(bool on);
  2242. void set_socket_options(SocketOptions socket_options);
  2243. void set_connection_timeout(time_t sec, time_t usec = 0);
  2244. template <class Rep, class Period>
  2245. void
  2246. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2247. void set_read_timeout(time_t sec, time_t usec = 0);
  2248. template <class Rep, class Period>
  2249. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2250. void set_write_timeout(time_t sec, time_t usec = 0);
  2251. template <class Rep, class Period>
  2252. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2253. void set_max_timeout(time_t msec);
  2254. template <class Rep, class Period>
  2255. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2256. void set_basic_auth(const std::string &username, const std::string &password);
  2257. void set_bearer_token_auth(const std::string &token);
  2258. void set_keep_alive(bool on);
  2259. void set_follow_location(bool on);
  2260. void set_path_encode(bool on);
  2261. void set_compress(bool on);
  2262. void set_decompress(bool on);
  2263. void set_payload_max_length(size_t length);
  2264. void set_interface(const std::string &intf);
  2265. void set_proxy(const std::string &host, int port);
  2266. void set_proxy_basic_auth(const std::string &username,
  2267. const std::string &password);
  2268. void set_proxy_bearer_token_auth(const std::string &token);
  2269. void set_no_proxy(const std::vector<std::string> &patterns);
  2270. void set_logger(Logger logger);
  2271. void set_error_logger(ErrorLogger error_logger);
  2272. private:
  2273. std::unique_ptr<ClientImpl> cli_;
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. public:
  2276. void set_digest_auth(const std::string &username,
  2277. const std::string &password);
  2278. void set_proxy_digest_auth(const std::string &username,
  2279. const std::string &password);
  2280. void enable_server_certificate_verification(bool enabled);
  2281. void enable_server_hostname_verification(bool enabled);
  2282. void enable_system_ca(bool enabled);
  2283. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2284. const std::string &ca_cert_dir_path = std::string());
  2285. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2286. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2287. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2288. void set_session_verifier(
  2289. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2290. tls::ctx_t tls_context() const;
  2291. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2292. void enable_windows_certificate_verification(bool enabled);
  2293. #endif
  2294. private:
  2295. bool is_ssl_ = false;
  2296. #endif
  2297. };
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. class SSLServer : public Server {
  2300. public:
  2301. SSLServer(const char *cert_path, const char *private_key_path,
  2302. const char *client_ca_cert_file_path = nullptr,
  2303. const char *client_ca_cert_dir_path = nullptr,
  2304. const char *private_key_password = nullptr);
  2305. struct PemMemory {
  2306. const char *cert_pem;
  2307. size_t cert_pem_len;
  2308. const char *key_pem;
  2309. size_t key_pem_len;
  2310. const char *client_ca_pem;
  2311. size_t client_ca_pem_len;
  2312. const char *private_key_password;
  2313. };
  2314. explicit SSLServer(const PemMemory &pem);
  2315. // The callback receives the ctx_t handle which can be cast to the
  2316. // appropriate backend type (SSL_CTX* for OpenSSL,
  2317. // tls::impl::MbedTlsContext* for Mbed TLS)
  2318. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2319. ~SSLServer() override;
  2320. bool is_valid() const override;
  2321. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2322. const char *client_ca_pem = nullptr,
  2323. const char *password = nullptr);
  2324. tls::ctx_t tls_context() const { return ctx_; }
  2325. int ssl_last_error() const { return last_ssl_error_; }
  2326. private:
  2327. bool process_and_close_socket(socket_t sock) override;
  2328. tls::ctx_t ctx_ = nullptr;
  2329. std::mutex ctx_mutex_;
  2330. int last_ssl_error_ = 0;
  2331. };
  2332. class SSLClient final : public ClientImpl {
  2333. public:
  2334. explicit SSLClient(const std::string &host);
  2335. explicit SSLClient(const std::string &host, int port);
  2336. explicit SSLClient(const std::string &host, int port,
  2337. const std::string &client_cert_path,
  2338. const std::string &client_key_path,
  2339. const std::string &private_key_password = std::string());
  2340. struct PemMemory {
  2341. const char *cert_pem;
  2342. size_t cert_pem_len;
  2343. const char *key_pem;
  2344. size_t key_pem_len;
  2345. const char *private_key_password;
  2346. };
  2347. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2348. ~SSLClient() override;
  2349. bool is_valid() const override;
  2350. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2351. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2352. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2353. // Post-handshake session verifier (backend-independent)
  2354. void set_session_verifier(
  2355. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2356. tls::ctx_t tls_context() const { return ctx_; }
  2357. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2358. void enable_windows_certificate_verification(bool enabled);
  2359. #endif
  2360. private:
  2361. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2362. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2363. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2364. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2365. bool
  2366. process_socket(const Socket &socket,
  2367. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2368. std::function<bool(Stream &strm)> callback) override;
  2369. bool is_ssl() const override;
  2370. bool setup_proxy_connection(
  2371. Socket &socket,
  2372. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2373. Response &res, bool &success, Error &error) override;
  2374. bool connect_with_proxy(
  2375. Socket &sock,
  2376. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2377. Response &res, bool &success, Error &error);
  2378. bool initialize_ssl(Socket &socket, Error &error);
  2379. void init_ctx();
  2380. void reset_ctx_on_error();
  2381. bool load_certs();
  2382. tls::ctx_t ctx_ = nullptr;
  2383. std::mutex ctx_mutex_;
  2384. std::once_flag initialize_cert_;
  2385. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2386. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2387. // Used to keep custom CA configuration exclusive with system CA loading.
  2388. bool ca_cert_store_set_ = false;
  2389. long verify_result_ = 0;
  2390. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2391. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2392. bool enable_windows_cert_verification_ = true;
  2393. #endif
  2394. friend class ClientImpl;
  2395. };
  2396. #endif // CPPHTTPLIB_SSL_ENABLED
  2397. namespace detail {
  2398. template <typename T, typename U>
  2399. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2400. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2401. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2402. duration - std::chrono::seconds(sec))
  2403. .count();
  2404. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2405. }
  2406. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2407. return N - 1;
  2408. }
  2409. inline bool is_numeric(const std::string &str) {
  2410. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2411. }
  2412. inline size_t get_header_value_u64(const Headers &headers,
  2413. const std::string &key, size_t def,
  2414. size_t id, bool &is_invalid_value) {
  2415. is_invalid_value = false;
  2416. auto rng = headers.equal_range(key);
  2417. auto it = rng.first;
  2418. std::advance(it, static_cast<ssize_t>(id));
  2419. if (it != rng.second) {
  2420. if (is_numeric(it->second)) {
  2421. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2422. } else {
  2423. is_invalid_value = true;
  2424. }
  2425. }
  2426. return def;
  2427. }
  2428. inline size_t get_header_value_u64(const Headers &headers,
  2429. const std::string &key, size_t def,
  2430. size_t id) {
  2431. auto dummy = false;
  2432. return get_header_value_u64(headers, key, def, id, dummy);
  2433. }
  2434. } // namespace detail
  2435. template <class Rep, class Period>
  2436. inline Server &
  2437. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2438. detail::duration_to_sec_and_usec(
  2439. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2440. return *this;
  2441. }
  2442. template <class Rep, class Period>
  2443. inline Server &
  2444. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2445. detail::duration_to_sec_and_usec(
  2446. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2447. return *this;
  2448. }
  2449. template <class Rep, class Period>
  2450. inline Server &
  2451. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2452. detail::duration_to_sec_and_usec(
  2453. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2454. return *this;
  2455. }
  2456. template <class Rep, class Period>
  2457. inline void ClientImpl::set_connection_timeout(
  2458. const std::chrono::duration<Rep, Period> &duration) {
  2459. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2460. set_connection_timeout(sec, usec);
  2461. });
  2462. }
  2463. template <class Rep, class Period>
  2464. inline void ClientImpl::set_read_timeout(
  2465. const std::chrono::duration<Rep, Period> &duration) {
  2466. detail::duration_to_sec_and_usec(
  2467. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2468. }
  2469. template <class Rep, class Period>
  2470. inline void ClientImpl::set_write_timeout(
  2471. const std::chrono::duration<Rep, Period> &duration) {
  2472. detail::duration_to_sec_and_usec(
  2473. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2474. }
  2475. template <class Rep, class Period>
  2476. inline void ClientImpl::set_max_timeout(
  2477. const std::chrono::duration<Rep, Period> &duration) {
  2478. auto msec =
  2479. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2480. set_max_timeout(msec);
  2481. }
  2482. template <class Rep, class Period>
  2483. inline void Client::set_connection_timeout(
  2484. const std::chrono::duration<Rep, Period> &duration) {
  2485. cli_->set_connection_timeout(duration);
  2486. }
  2487. template <class Rep, class Period>
  2488. inline void
  2489. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2490. cli_->set_read_timeout(duration);
  2491. }
  2492. template <class Rep, class Period>
  2493. inline void
  2494. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2495. cli_->set_write_timeout(duration);
  2496. }
  2497. inline void Client::set_max_timeout(time_t msec) {
  2498. cli_->set_max_timeout(msec);
  2499. }
  2500. template <class Rep, class Period>
  2501. inline void
  2502. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2503. cli_->set_max_timeout(duration);
  2504. }
  2505. /*
  2506. * Forward declarations and types that will be part of the .h file if split into
  2507. * .h + .cc.
  2508. */
  2509. std::string hosted_at(const std::string &hostname);
  2510. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2511. // JavaScript-style URL encoding/decoding functions
  2512. std::string encode_uri_component(const std::string &value);
  2513. std::string encode_uri(const std::string &value);
  2514. std::string decode_uri_component(const std::string &value);
  2515. std::string decode_uri(const std::string &value);
  2516. // RFC 3986 compliant URL component encoding/decoding functions
  2517. std::string encode_path_component(const std::string &component);
  2518. std::string decode_path_component(const std::string &component);
  2519. std::string encode_query_component(const std::string &component,
  2520. bool space_as_plus = true);
  2521. std::string decode_query_component(const std::string &component,
  2522. bool plus_as_space = true);
  2523. std::string sanitize_filename(const std::string &filename);
  2524. std::string append_query_params(const std::string &path, const Params &params);
  2525. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2526. std::pair<std::string, std::string>
  2527. make_basic_authentication_header(const std::string &username,
  2528. const std::string &password,
  2529. bool is_proxy = false);
  2530. namespace detail {
  2531. #if defined(_WIN32)
  2532. inline std::wstring u8string_to_wstring(const char *s) {
  2533. if (!s) { return std::wstring(); }
  2534. auto len = static_cast<int>(strlen(s));
  2535. if (!len) { return std::wstring(); }
  2536. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2537. if (!wlen) { return std::wstring(); }
  2538. std::wstring ws;
  2539. ws.resize(wlen);
  2540. wlen = ::MultiByteToWideChar(
  2541. CP_UTF8, 0, s, len,
  2542. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2543. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2544. return ws;
  2545. }
  2546. #endif
  2547. struct FileStat {
  2548. FileStat(const std::string &path);
  2549. bool is_file() const;
  2550. bool is_dir() const;
  2551. time_t mtime() const;
  2552. size_t size() const;
  2553. private:
  2554. #if defined(_WIN32)
  2555. struct _stat st_;
  2556. #else
  2557. struct stat st_;
  2558. #endif
  2559. int ret_ = -1;
  2560. };
  2561. std::string make_host_and_port_string(const std::string &host, int port,
  2562. bool is_ssl);
  2563. std::string trim_copy(const std::string &s);
  2564. void divide(
  2565. const char *data, std::size_t size, char d,
  2566. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2567. fn);
  2568. void divide(
  2569. const std::string &str, char d,
  2570. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2571. fn);
  2572. void split(const char *b, const char *e, char d,
  2573. std::function<void(const char *, const char *)> fn);
  2574. void split(const char *b, const char *e, char d, size_t m,
  2575. std::function<void(const char *, const char *)> fn);
  2576. bool process_client_socket(
  2577. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2578. time_t write_timeout_sec, time_t write_timeout_usec,
  2579. time_t max_timeout_msec,
  2580. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2581. std::function<bool(Stream &)> callback);
  2582. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2583. int port, int address_family, bool tcp_nodelay,
  2584. bool ipv6_v6only, SocketOptions socket_options,
  2585. time_t connection_timeout_sec,
  2586. time_t connection_timeout_usec,
  2587. time_t read_timeout_sec, time_t read_timeout_usec,
  2588. time_t write_timeout_sec,
  2589. time_t write_timeout_usec,
  2590. const std::string &intf, Error &error);
  2591. const char *get_header_value(const Headers &headers, const std::string &key,
  2592. const char *def, size_t id);
  2593. std::string params_to_query_str(const Params &params);
  2594. void parse_query_text(const char *data, std::size_t size, Params &params);
  2595. void parse_query_text(const std::string &s, Params &params);
  2596. bool parse_multipart_boundary(const std::string &content_type,
  2597. std::string &boundary);
  2598. bool parse_range_header(const std::string &s, Ranges &ranges);
  2599. bool parse_accept_header(const std::string &s,
  2600. std::vector<std::string> &content_types);
  2601. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2602. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2603. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2604. EncodingType encoding_type(const Request &req, const Response &res);
  2605. class BufferStream final : public Stream {
  2606. public:
  2607. BufferStream() = default;
  2608. ~BufferStream() override = default;
  2609. bool is_readable() const override;
  2610. bool wait_readable() const override;
  2611. bool wait_writable() const override;
  2612. ssize_t read(char *ptr, size_t size) override;
  2613. ssize_t write(const char *ptr, size_t size) override;
  2614. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2615. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2616. socket_t socket() const override;
  2617. time_t duration() const override;
  2618. const std::string &get_buffer() const;
  2619. private:
  2620. std::string buffer;
  2621. size_t position = 0;
  2622. };
  2623. class compressor {
  2624. public:
  2625. virtual ~compressor() = default;
  2626. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2627. virtual bool compress(const char *data, size_t data_length, bool last,
  2628. Callback callback) = 0;
  2629. };
  2630. class decompressor {
  2631. public:
  2632. virtual ~decompressor() = default;
  2633. virtual bool is_valid() const = 0;
  2634. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2635. virtual bool decompress(const char *data, size_t data_length,
  2636. Callback callback) = 0;
  2637. };
  2638. class nocompressor final : public compressor {
  2639. public:
  2640. ~nocompressor() override = default;
  2641. bool compress(const char *data, size_t data_length, bool /*last*/,
  2642. Callback callback) override;
  2643. };
  2644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2645. class gzip_compressor final : public compressor {
  2646. public:
  2647. gzip_compressor();
  2648. ~gzip_compressor() override;
  2649. bool compress(const char *data, size_t data_length, bool last,
  2650. Callback callback) override;
  2651. private:
  2652. bool is_valid_ = false;
  2653. z_stream strm_;
  2654. };
  2655. class gzip_decompressor final : public decompressor {
  2656. public:
  2657. gzip_decompressor();
  2658. ~gzip_decompressor() override;
  2659. bool is_valid() const override;
  2660. bool decompress(const char *data, size_t data_length,
  2661. Callback callback) override;
  2662. private:
  2663. bool is_valid_ = false;
  2664. z_stream strm_;
  2665. };
  2666. #endif
  2667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2668. class brotli_compressor final : public compressor {
  2669. public:
  2670. brotli_compressor();
  2671. ~brotli_compressor();
  2672. bool compress(const char *data, size_t data_length, bool last,
  2673. Callback callback) override;
  2674. private:
  2675. BrotliEncoderState *state_ = nullptr;
  2676. };
  2677. class brotli_decompressor final : public decompressor {
  2678. public:
  2679. brotli_decompressor();
  2680. ~brotli_decompressor();
  2681. bool is_valid() const override;
  2682. bool decompress(const char *data, size_t data_length,
  2683. Callback callback) override;
  2684. private:
  2685. BrotliDecoderResult decoder_r;
  2686. BrotliDecoderState *decoder_s = nullptr;
  2687. };
  2688. #endif
  2689. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2690. class zstd_compressor : public compressor {
  2691. public:
  2692. zstd_compressor();
  2693. ~zstd_compressor();
  2694. bool compress(const char *data, size_t data_length, bool last,
  2695. Callback callback) override;
  2696. private:
  2697. ZSTD_CCtx *ctx_ = nullptr;
  2698. };
  2699. class zstd_decompressor : public decompressor {
  2700. public:
  2701. zstd_decompressor();
  2702. ~zstd_decompressor();
  2703. bool is_valid() const override;
  2704. bool decompress(const char *data, size_t data_length,
  2705. Callback callback) override;
  2706. private:
  2707. ZSTD_DCtx *ctx_ = nullptr;
  2708. };
  2709. #endif
  2710. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2711. // to store data. The call can set memory on stack for performance.
  2712. class stream_line_reader {
  2713. public:
  2714. stream_line_reader(Stream &strm, char *fixed_buffer,
  2715. size_t fixed_buffer_size);
  2716. const char *ptr() const;
  2717. size_t size() const;
  2718. bool end_with_crlf() const;
  2719. bool getline();
  2720. private:
  2721. void append(char c);
  2722. Stream &strm_;
  2723. char *fixed_buffer_;
  2724. const size_t fixed_buffer_size_;
  2725. size_t fixed_buffer_used_size_ = 0;
  2726. std::string growable_buffer_;
  2727. };
  2728. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2729. const Headers &src_headers);
  2730. struct ChunkedDecoder {
  2731. Stream &strm;
  2732. size_t chunk_remaining = 0;
  2733. bool finished = false;
  2734. char line_buf[64];
  2735. size_t last_chunk_total = 0;
  2736. size_t last_chunk_offset = 0;
  2737. explicit ChunkedDecoder(Stream &s);
  2738. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2739. size_t &out_chunk_total);
  2740. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2741. };
  2742. class mmap {
  2743. public:
  2744. mmap(const char *path);
  2745. ~mmap();
  2746. bool open(const char *path);
  2747. void close();
  2748. bool is_open() const;
  2749. size_t size() const;
  2750. const char *data() const;
  2751. private:
  2752. #if defined(_WIN32)
  2753. HANDLE hFile_ = NULL;
  2754. HANDLE hMapping_ = NULL;
  2755. #else
  2756. int fd_ = -1;
  2757. #endif
  2758. size_t size_ = 0;
  2759. void *addr_ = nullptr;
  2760. bool is_open_empty_file = false;
  2761. };
  2762. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2763. namespace fields {
  2764. bool is_token_char(char c);
  2765. bool is_token(const std::string &s);
  2766. bool is_field_name(const std::string &s);
  2767. bool is_vchar(char c);
  2768. bool is_obs_text(char c);
  2769. bool is_field_vchar(char c);
  2770. bool is_field_content(const std::string &s);
  2771. bool is_field_value(const std::string &s);
  2772. } // namespace fields
  2773. } // namespace detail
  2774. /*
  2775. * TLS Abstraction Layer Declarations
  2776. */
  2777. #ifdef CPPHTTPLIB_SSL_ENABLED
  2778. // TLS abstraction layer - backend-specific type declarations
  2779. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2780. namespace tls {
  2781. namespace impl {
  2782. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2783. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2784. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2785. struct MbedTlsContext {
  2786. mbedtls_ssl_config conf;
  2787. mbedtls_entropy_context entropy;
  2788. mbedtls_ctr_drbg_context ctr_drbg;
  2789. mbedtls_x509_crt ca_chain;
  2790. mbedtls_x509_crt own_cert;
  2791. mbedtls_pk_context own_key;
  2792. bool is_server = false;
  2793. bool verify_client = false;
  2794. bool has_verify_callback = false;
  2795. MbedTlsContext();
  2796. ~MbedTlsContext();
  2797. MbedTlsContext(const MbedTlsContext &) = delete;
  2798. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2799. };
  2800. } // namespace impl
  2801. } // namespace tls
  2802. #endif
  2803. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2804. namespace tls {
  2805. namespace impl {
  2806. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2807. // This struct is accessible via tls::impl for use in SSL context
  2808. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2809. struct WolfSSLContext {
  2810. WOLFSSL_CTX *ctx = nullptr;
  2811. bool is_server = false;
  2812. bool verify_client = false;
  2813. bool has_verify_callback = false;
  2814. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2815. WolfSSLContext();
  2816. ~WolfSSLContext();
  2817. WolfSSLContext(const WolfSSLContext &) = delete;
  2818. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2819. };
  2820. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2821. struct WolfSSLCAStore {
  2822. std::string pem_data;
  2823. };
  2824. } // namespace impl
  2825. } // namespace tls
  2826. #endif
  2827. #endif // CPPHTTPLIB_SSL_ENABLED
  2828. namespace stream {
  2829. class Result {
  2830. public:
  2831. Result();
  2832. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2833. Result(Result &&other) noexcept;
  2834. Result &operator=(Result &&other) noexcept;
  2835. Result(const Result &) = delete;
  2836. Result &operator=(const Result &) = delete;
  2837. // Response info
  2838. bool is_valid() const;
  2839. explicit operator bool() const;
  2840. int status() const;
  2841. const Headers &headers() const;
  2842. std::string get_header_value(const std::string &key,
  2843. const char *def = "") const;
  2844. bool has_header(const std::string &key) const;
  2845. Error error() const;
  2846. Error read_error() const;
  2847. bool has_read_error() const;
  2848. // Stream reading
  2849. bool next();
  2850. const char *data() const;
  2851. size_t size() const;
  2852. std::string read_all();
  2853. private:
  2854. ClientImpl::StreamHandle handle_;
  2855. std::string buffer_;
  2856. size_t current_size_ = 0;
  2857. size_t chunk_size_;
  2858. bool finished_ = false;
  2859. };
  2860. // GET
  2861. template <typename ClientType>
  2862. inline Result Get(ClientType &cli, const std::string &path,
  2863. size_t chunk_size = 8192) {
  2864. return Result{cli.open_stream("GET", path), chunk_size};
  2865. }
  2866. template <typename ClientType>
  2867. inline Result Get(ClientType &cli, const std::string &path,
  2868. const Headers &headers, size_t chunk_size = 8192) {
  2869. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2870. }
  2871. template <typename ClientType>
  2872. inline Result Get(ClientType &cli, const std::string &path,
  2873. const Params &params, size_t chunk_size = 8192) {
  2874. return Result{cli.open_stream("GET", path, params), chunk_size};
  2875. }
  2876. template <typename ClientType>
  2877. inline Result Get(ClientType &cli, const std::string &path,
  2878. const Params &params, const Headers &headers,
  2879. size_t chunk_size = 8192) {
  2880. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2881. }
  2882. // POST
  2883. template <typename ClientType>
  2884. inline Result Post(ClientType &cli, const std::string &path,
  2885. const std::string &body, const std::string &content_type,
  2886. size_t chunk_size = 8192) {
  2887. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2888. chunk_size};
  2889. }
  2890. template <typename ClientType>
  2891. inline Result Post(ClientType &cli, const std::string &path,
  2892. const Headers &headers, const std::string &body,
  2893. const std::string &content_type, size_t chunk_size = 8192) {
  2894. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2895. chunk_size};
  2896. }
  2897. template <typename ClientType>
  2898. inline Result Post(ClientType &cli, const std::string &path,
  2899. const Params &params, const std::string &body,
  2900. const std::string &content_type, size_t chunk_size = 8192) {
  2901. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2902. chunk_size};
  2903. }
  2904. template <typename ClientType>
  2905. inline Result Post(ClientType &cli, const std::string &path,
  2906. const Params &params, const Headers &headers,
  2907. const std::string &body, const std::string &content_type,
  2908. size_t chunk_size = 8192) {
  2909. return Result{
  2910. cli.open_stream("POST", path, params, headers, body, content_type),
  2911. chunk_size};
  2912. }
  2913. // PUT
  2914. template <typename ClientType>
  2915. inline Result Put(ClientType &cli, const std::string &path,
  2916. const std::string &body, const std::string &content_type,
  2917. size_t chunk_size = 8192) {
  2918. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2919. chunk_size};
  2920. }
  2921. template <typename ClientType>
  2922. inline Result Put(ClientType &cli, const std::string &path,
  2923. const Headers &headers, const std::string &body,
  2924. const std::string &content_type, size_t chunk_size = 8192) {
  2925. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2926. chunk_size};
  2927. }
  2928. template <typename ClientType>
  2929. inline Result Put(ClientType &cli, const std::string &path,
  2930. const Params &params, const std::string &body,
  2931. const std::string &content_type, size_t chunk_size = 8192) {
  2932. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2933. chunk_size};
  2934. }
  2935. template <typename ClientType>
  2936. inline Result Put(ClientType &cli, const std::string &path,
  2937. const Params &params, const Headers &headers,
  2938. const std::string &body, const std::string &content_type,
  2939. size_t chunk_size = 8192) {
  2940. return Result{
  2941. cli.open_stream("PUT", path, params, headers, body, content_type),
  2942. chunk_size};
  2943. }
  2944. // PATCH
  2945. template <typename ClientType>
  2946. inline Result Patch(ClientType &cli, const std::string &path,
  2947. const std::string &body, const std::string &content_type,
  2948. size_t chunk_size = 8192) {
  2949. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2950. chunk_size};
  2951. }
  2952. template <typename ClientType>
  2953. inline Result Patch(ClientType &cli, const std::string &path,
  2954. const Headers &headers, const std::string &body,
  2955. const std::string &content_type, size_t chunk_size = 8192) {
  2956. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2957. chunk_size};
  2958. }
  2959. template <typename ClientType>
  2960. inline Result Patch(ClientType &cli, const std::string &path,
  2961. const Params &params, const std::string &body,
  2962. const std::string &content_type, size_t chunk_size = 8192) {
  2963. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2964. chunk_size};
  2965. }
  2966. template <typename ClientType>
  2967. inline Result Patch(ClientType &cli, const std::string &path,
  2968. const Params &params, const Headers &headers,
  2969. const std::string &body, const std::string &content_type,
  2970. size_t chunk_size = 8192) {
  2971. return Result{
  2972. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2973. chunk_size};
  2974. }
  2975. // DELETE
  2976. template <typename ClientType>
  2977. inline Result Delete(ClientType &cli, const std::string &path,
  2978. size_t chunk_size = 8192) {
  2979. return Result{cli.open_stream("DELETE", path), chunk_size};
  2980. }
  2981. template <typename ClientType>
  2982. inline Result Delete(ClientType &cli, const std::string &path,
  2983. const Headers &headers, size_t chunk_size = 8192) {
  2984. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2985. }
  2986. template <typename ClientType>
  2987. inline Result Delete(ClientType &cli, const std::string &path,
  2988. const std::string &body, const std::string &content_type,
  2989. size_t chunk_size = 8192) {
  2990. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2991. chunk_size};
  2992. }
  2993. template <typename ClientType>
  2994. inline Result Delete(ClientType &cli, const std::string &path,
  2995. const Headers &headers, const std::string &body,
  2996. const std::string &content_type,
  2997. size_t chunk_size = 8192) {
  2998. return Result{
  2999. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3000. chunk_size};
  3001. }
  3002. template <typename ClientType>
  3003. inline Result Delete(ClientType &cli, const std::string &path,
  3004. const Params &params, size_t chunk_size = 8192) {
  3005. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3006. }
  3007. template <typename ClientType>
  3008. inline Result Delete(ClientType &cli, const std::string &path,
  3009. const Params &params, const Headers &headers,
  3010. size_t chunk_size = 8192) {
  3011. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3012. }
  3013. template <typename ClientType>
  3014. inline Result Delete(ClientType &cli, const std::string &path,
  3015. const Params &params, const std::string &body,
  3016. const std::string &content_type,
  3017. size_t chunk_size = 8192) {
  3018. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3019. chunk_size};
  3020. }
  3021. template <typename ClientType>
  3022. inline Result Delete(ClientType &cli, const std::string &path,
  3023. const Params &params, const Headers &headers,
  3024. const std::string &body, const std::string &content_type,
  3025. size_t chunk_size = 8192) {
  3026. return Result{
  3027. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3028. chunk_size};
  3029. }
  3030. // HEAD
  3031. template <typename ClientType>
  3032. inline Result Head(ClientType &cli, const std::string &path,
  3033. size_t chunk_size = 8192) {
  3034. return Result{cli.open_stream("HEAD", path), chunk_size};
  3035. }
  3036. template <typename ClientType>
  3037. inline Result Head(ClientType &cli, const std::string &path,
  3038. const Headers &headers, size_t chunk_size = 8192) {
  3039. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3040. }
  3041. template <typename ClientType>
  3042. inline Result Head(ClientType &cli, const std::string &path,
  3043. const Params &params, size_t chunk_size = 8192) {
  3044. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3045. }
  3046. template <typename ClientType>
  3047. inline Result Head(ClientType &cli, const std::string &path,
  3048. const Params &params, const Headers &headers,
  3049. size_t chunk_size = 8192) {
  3050. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3051. }
  3052. // OPTIONS
  3053. template <typename ClientType>
  3054. inline Result Options(ClientType &cli, const std::string &path,
  3055. size_t chunk_size = 8192) {
  3056. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3057. }
  3058. template <typename ClientType>
  3059. inline Result Options(ClientType &cli, const std::string &path,
  3060. const Headers &headers, size_t chunk_size = 8192) {
  3061. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3062. }
  3063. template <typename ClientType>
  3064. inline Result Options(ClientType &cli, const std::string &path,
  3065. const Params &params, size_t chunk_size = 8192) {
  3066. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3067. }
  3068. template <typename ClientType>
  3069. inline Result Options(ClientType &cli, const std::string &path,
  3070. const Params &params, const Headers &headers,
  3071. size_t chunk_size = 8192) {
  3072. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3073. }
  3074. } // namespace stream
  3075. namespace sse {
  3076. struct SSEMessage {
  3077. std::string event; // Event type (default: "message")
  3078. std::string data; // Event payload
  3079. std::string id; // Event ID for Last-Event-ID header
  3080. SSEMessage();
  3081. void clear();
  3082. };
  3083. class SSEClient {
  3084. public:
  3085. using MessageHandler = std::function<void(const SSEMessage &)>;
  3086. using ErrorHandler = std::function<void(Error)>;
  3087. using OpenHandler = std::function<void()>;
  3088. SSEClient(Client &client, const std::string &path);
  3089. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3090. ~SSEClient();
  3091. SSEClient(const SSEClient &) = delete;
  3092. SSEClient &operator=(const SSEClient &) = delete;
  3093. // Event handlers
  3094. SSEClient &on_message(MessageHandler handler);
  3095. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3096. SSEClient &on_open(OpenHandler handler);
  3097. SSEClient &on_error(ErrorHandler handler);
  3098. SSEClient &set_reconnect_interval(int ms);
  3099. SSEClient &set_max_reconnect_attempts(int n);
  3100. // Update headers (thread-safe)
  3101. SSEClient &set_headers(const Headers &headers);
  3102. // State accessors
  3103. bool is_connected() const;
  3104. const std::string &last_event_id() const;
  3105. // Blocking start - runs event loop with auto-reconnect
  3106. void start();
  3107. // Non-blocking start - runs in background thread
  3108. void start_async();
  3109. // Stop the client (thread-safe)
  3110. void stop();
  3111. private:
  3112. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3113. void run_event_loop();
  3114. void dispatch_event(const SSEMessage &msg);
  3115. bool should_reconnect(int count) const;
  3116. void wait_for_reconnect();
  3117. // Client and path
  3118. Client &client_;
  3119. std::string path_;
  3120. Headers headers_;
  3121. mutable std::mutex headers_mutex_;
  3122. // Callbacks
  3123. MessageHandler on_message_;
  3124. std::map<std::string, MessageHandler> event_handlers_;
  3125. OpenHandler on_open_;
  3126. ErrorHandler on_error_;
  3127. // Configuration
  3128. int reconnect_interval_ms_ = 3000;
  3129. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3130. // State
  3131. std::atomic<bool> running_{false};
  3132. std::atomic<bool> connected_{false};
  3133. std::string last_event_id_;
  3134. // Async support
  3135. std::thread async_thread_;
  3136. };
  3137. } // namespace sse
  3138. namespace ws {
  3139. enum class Opcode : uint8_t {
  3140. Continuation = 0x0,
  3141. Text = 0x1,
  3142. Binary = 0x2,
  3143. Close = 0x8,
  3144. Ping = 0x9,
  3145. Pong = 0xA,
  3146. };
  3147. enum class CloseStatus : uint16_t {
  3148. Normal = 1000,
  3149. GoingAway = 1001,
  3150. ProtocolError = 1002,
  3151. UnsupportedData = 1003,
  3152. NoStatus = 1005,
  3153. Abnormal = 1006,
  3154. InvalidPayload = 1007,
  3155. PolicyViolation = 1008,
  3156. MessageTooBig = 1009,
  3157. MandatoryExtension = 1010,
  3158. InternalError = 1011,
  3159. };
  3160. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3161. class WebSocket {
  3162. public:
  3163. WebSocket(const WebSocket &) = delete;
  3164. WebSocket &operator=(const WebSocket &) = delete;
  3165. ~WebSocket();
  3166. ReadResult read(std::string &msg);
  3167. bool send(const std::string &data);
  3168. bool send(const char *data, size_t len);
  3169. void close(CloseStatus status = CloseStatus::Normal,
  3170. const std::string &reason = "");
  3171. const Request &request() const;
  3172. bool is_open() const;
  3173. private:
  3174. friend class httplib::Server;
  3175. friend class WebSocketClient;
  3176. WebSocket(
  3177. Stream &strm, const Request &req, bool is_server,
  3178. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3179. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3180. : strm_(strm), req_(req), is_server_(is_server),
  3181. ping_interval_sec_(ping_interval_sec),
  3182. max_missed_pongs_(max_missed_pongs) {
  3183. start_heartbeat();
  3184. }
  3185. WebSocket(
  3186. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3187. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3188. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3189. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3190. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3191. max_missed_pongs_(max_missed_pongs) {
  3192. start_heartbeat();
  3193. }
  3194. void start_heartbeat();
  3195. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3196. Stream &strm_;
  3197. std::unique_ptr<Stream> owned_strm_;
  3198. Request req_;
  3199. bool is_server_;
  3200. time_t ping_interval_sec_;
  3201. int max_missed_pongs_;
  3202. int unacked_pings_ = 0;
  3203. std::atomic<bool> closed_{false};
  3204. std::mutex write_mutex_;
  3205. std::thread ping_thread_;
  3206. std::mutex ping_mutex_;
  3207. std::condition_variable ping_cv_;
  3208. };
  3209. class WebSocketClient {
  3210. public:
  3211. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3212. const Headers &headers = {});
  3213. ~WebSocketClient();
  3214. WebSocketClient(const WebSocketClient &) = delete;
  3215. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3216. bool is_valid() const;
  3217. bool connect();
  3218. ReadResult read(std::string &msg);
  3219. bool send(const std::string &data);
  3220. bool send(const char *data, size_t len);
  3221. void close(CloseStatus status = CloseStatus::Normal,
  3222. const std::string &reason = "");
  3223. bool is_open() const;
  3224. const std::string &subprotocol() const;
  3225. void set_read_timeout(time_t sec, time_t usec = 0);
  3226. void set_write_timeout(time_t sec, time_t usec = 0);
  3227. void set_websocket_ping_interval(time_t sec);
  3228. void set_websocket_max_missed_pongs(int count);
  3229. void set_tcp_nodelay(bool on);
  3230. void set_address_family(int family);
  3231. void set_ipv6_v6only(bool on);
  3232. void set_socket_options(SocketOptions socket_options);
  3233. void set_connection_timeout(time_t sec, time_t usec = 0);
  3234. void set_interface(const std::string &intf);
  3235. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. void set_ca_cert_path(const std::string &path);
  3238. void set_ca_cert_store(tls::ca_store_t store);
  3239. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3240. void enable_server_certificate_verification(bool enabled);
  3241. void enable_system_ca(bool enabled);
  3242. #endif
  3243. private:
  3244. void shutdown_and_close();
  3245. bool create_stream(std::unique_ptr<Stream> &strm);
  3246. std::string host_;
  3247. int port_;
  3248. std::string path_;
  3249. Headers headers_;
  3250. std::string subprotocol_;
  3251. bool is_valid_ = false;
  3252. socket_t sock_ = INVALID_SOCKET;
  3253. std::unique_ptr<WebSocket> ws_;
  3254. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3255. time_t read_timeout_usec_ = 0;
  3256. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3257. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3258. time_t websocket_ping_interval_sec_ =
  3259. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3260. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3261. int address_family_ = AF_UNSPEC;
  3262. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3263. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3264. SocketOptions socket_options_ = nullptr;
  3265. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3266. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3267. std::string interface_;
  3268. // Hostname-IP map
  3269. std::map<std::string, std::string> addr_map_;
  3270. #ifdef CPPHTTPLIB_SSL_ENABLED
  3271. bool is_ssl_ = false;
  3272. tls::ctx_t tls_ctx_ = nullptr;
  3273. tls::session_t tls_session_ = nullptr;
  3274. std::string ca_cert_file_path_;
  3275. bool custom_ca_loaded_ = false;
  3276. bool certs_loaded_ = false;
  3277. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3278. bool server_certificate_verification_ = true;
  3279. #endif
  3280. };
  3281. namespace impl {
  3282. bool is_valid_utf8(const std::string &s);
  3283. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3284. bool &fin, bool expect_masked, size_t max_len);
  3285. } // namespace impl
  3286. } // namespace ws
  3287. // ----------------------------------------------------------------------------
  3288. /*
  3289. * Implementation that will be part of the .cc file if split into .h + .cc.
  3290. */
  3291. namespace stream {
  3292. // stream::Result implementations
  3293. inline Result::Result() : chunk_size_(8192) {}
  3294. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3295. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3296. inline Result::Result(Result &&other) noexcept
  3297. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3298. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3299. finished_(other.finished_) {
  3300. other.current_size_ = 0;
  3301. other.finished_ = true;
  3302. }
  3303. inline Result &Result::operator=(Result &&other) noexcept {
  3304. if (this != &other) {
  3305. handle_ = std::move(other.handle_);
  3306. buffer_ = std::move(other.buffer_);
  3307. current_size_ = other.current_size_;
  3308. chunk_size_ = other.chunk_size_;
  3309. finished_ = other.finished_;
  3310. other.current_size_ = 0;
  3311. other.finished_ = true;
  3312. }
  3313. return *this;
  3314. }
  3315. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3316. inline Result::operator bool() const { return is_valid(); }
  3317. inline int Result::status() const {
  3318. return handle_.response ? handle_.response->status : -1;
  3319. }
  3320. inline const Headers &Result::headers() const {
  3321. static const Headers empty_headers;
  3322. return handle_.response ? handle_.response->headers : empty_headers;
  3323. }
  3324. inline std::string Result::get_header_value(const std::string &key,
  3325. const char *def) const {
  3326. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3327. }
  3328. inline bool Result::has_header(const std::string &key) const {
  3329. return handle_.response ? handle_.response->has_header(key) : false;
  3330. }
  3331. inline Error Result::error() const { return handle_.error; }
  3332. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3333. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3334. inline bool Result::next() {
  3335. if (!handle_.is_valid() || finished_) { return false; }
  3336. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3337. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3338. if (n > 0) {
  3339. current_size_ = static_cast<size_t>(n);
  3340. return true;
  3341. }
  3342. current_size_ = 0;
  3343. finished_ = true;
  3344. return false;
  3345. }
  3346. inline const char *Result::data() const { return buffer_.data(); }
  3347. inline size_t Result::size() const { return current_size_; }
  3348. inline std::string Result::read_all() {
  3349. std::string result;
  3350. while (next()) {
  3351. result.append(data(), size());
  3352. }
  3353. return result;
  3354. }
  3355. } // namespace stream
  3356. namespace sse {
  3357. // SSEMessage implementations
  3358. inline SSEMessage::SSEMessage() : event("message") {}
  3359. inline void SSEMessage::clear() {
  3360. event = "message";
  3361. data.clear();
  3362. id.clear();
  3363. }
  3364. // SSEClient implementations
  3365. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3366. : client_(client), path_(path) {}
  3367. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3368. const Headers &headers)
  3369. : client_(client), path_(path), headers_(headers) {}
  3370. inline SSEClient::~SSEClient() { stop(); }
  3371. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3372. on_message_ = std::move(handler);
  3373. return *this;
  3374. }
  3375. inline SSEClient &SSEClient::on_event(const std::string &type,
  3376. MessageHandler handler) {
  3377. event_handlers_[type] = std::move(handler);
  3378. return *this;
  3379. }
  3380. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3381. on_open_ = std::move(handler);
  3382. return *this;
  3383. }
  3384. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3385. on_error_ = std::move(handler);
  3386. return *this;
  3387. }
  3388. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3389. reconnect_interval_ms_ = ms;
  3390. return *this;
  3391. }
  3392. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3393. max_reconnect_attempts_ = n;
  3394. return *this;
  3395. }
  3396. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3397. std::lock_guard<std::mutex> lock(headers_mutex_);
  3398. headers_ = headers;
  3399. return *this;
  3400. }
  3401. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3402. inline const std::string &SSEClient::last_event_id() const {
  3403. return last_event_id_;
  3404. }
  3405. inline void SSEClient::start() {
  3406. running_.store(true);
  3407. run_event_loop();
  3408. }
  3409. inline void SSEClient::start_async() {
  3410. running_.store(true);
  3411. async_thread_ = std::thread([this]() { run_event_loop(); });
  3412. }
  3413. inline void SSEClient::stop() {
  3414. running_.store(false);
  3415. client_.stop(); // Cancel any pending operations
  3416. if (async_thread_.joinable()) { async_thread_.join(); }
  3417. }
  3418. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3419. int &retry_ms) {
  3420. // Blank line signals end of event
  3421. if (line.empty() || line == "\r") { return true; }
  3422. // Lines starting with ':' are comments (ignored)
  3423. if (!line.empty() && line[0] == ':') { return false; }
  3424. // Find the colon separator
  3425. auto colon_pos = line.find(':');
  3426. if (colon_pos == std::string::npos) {
  3427. // Line with no colon is treated as field name with empty value
  3428. return false;
  3429. }
  3430. auto field = line.substr(0, colon_pos);
  3431. std::string value;
  3432. // Value starts after colon, skip optional single space
  3433. if (colon_pos + 1 < line.size()) {
  3434. auto value_start = colon_pos + 1;
  3435. if (line[value_start] == ' ') { value_start++; }
  3436. value = line.substr(value_start);
  3437. // Remove trailing \r if present
  3438. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3439. }
  3440. // Handle known fields
  3441. if (field == "event") {
  3442. msg.event = value;
  3443. } else if (field == "data") {
  3444. // Multiple data lines are concatenated with newlines
  3445. if (!msg.data.empty()) { msg.data += "\n"; }
  3446. msg.data += value;
  3447. } else if (field == "id") {
  3448. // Empty id is valid (clears the last event ID)
  3449. msg.id = value;
  3450. } else if (field == "retry") {
  3451. // Parse retry interval in milliseconds
  3452. {
  3453. int v = 0;
  3454. auto res =
  3455. detail::from_chars(value.data(), value.data() + value.size(), v);
  3456. if (res.ec == std::errc{}) { retry_ms = v; }
  3457. }
  3458. }
  3459. // Unknown fields are ignored per SSE spec
  3460. return false;
  3461. }
  3462. inline void SSEClient::run_event_loop() {
  3463. auto reconnect_count = 0;
  3464. while (running_.load()) {
  3465. // Build headers, including Last-Event-ID if we have one
  3466. Headers request_headers;
  3467. {
  3468. std::lock_guard<std::mutex> lock(headers_mutex_);
  3469. request_headers = headers_;
  3470. }
  3471. if (!last_event_id_.empty()) {
  3472. request_headers.emplace("Last-Event-ID", last_event_id_);
  3473. }
  3474. // Open streaming connection
  3475. auto result = stream::Get(client_, path_, request_headers);
  3476. // Connection error handling
  3477. if (!result) {
  3478. connected_.store(false);
  3479. if (on_error_) { on_error_(result.error()); }
  3480. if (!should_reconnect(reconnect_count)) { break; }
  3481. wait_for_reconnect();
  3482. reconnect_count++;
  3483. continue;
  3484. }
  3485. if (result.status() != StatusCode::OK_200) {
  3486. connected_.store(false);
  3487. if (on_error_) { on_error_(Error::Connection); }
  3488. // For certain errors, don't reconnect.
  3489. // Note: 401 is intentionally absent so that handlers can refresh
  3490. // credentials via set_headers() and let the client reconnect.
  3491. if (result.status() == StatusCode::NoContent_204 ||
  3492. result.status() == StatusCode::NotFound_404 ||
  3493. result.status() == StatusCode::Forbidden_403) {
  3494. break;
  3495. }
  3496. if (!should_reconnect(reconnect_count)) { break; }
  3497. wait_for_reconnect();
  3498. reconnect_count++;
  3499. continue;
  3500. }
  3501. // Connection successful
  3502. connected_.store(true);
  3503. reconnect_count = 0;
  3504. if (on_open_) { on_open_(); }
  3505. // Event receiving loop
  3506. std::string buffer;
  3507. SSEMessage current_msg;
  3508. while (running_.load() && result.next()) {
  3509. buffer.append(result.data(), result.size());
  3510. // Process complete lines in the buffer
  3511. size_t line_start = 0;
  3512. size_t newline_pos;
  3513. while ((newline_pos = buffer.find('\n', line_start)) !=
  3514. std::string::npos) {
  3515. auto line = buffer.substr(line_start, newline_pos - line_start);
  3516. line_start = newline_pos + 1;
  3517. // Parse the line and check if event is complete
  3518. auto event_complete =
  3519. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3520. if (event_complete && !current_msg.data.empty()) {
  3521. // Update last_event_id for reconnection
  3522. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3523. // Dispatch event to appropriate handler
  3524. dispatch_event(current_msg);
  3525. current_msg.clear();
  3526. }
  3527. }
  3528. // Keep unprocessed data in buffer
  3529. buffer.erase(0, line_start);
  3530. }
  3531. // Connection ended
  3532. connected_.store(false);
  3533. if (!running_.load()) { break; }
  3534. // Check for read errors
  3535. if (result.has_read_error()) {
  3536. if (on_error_) { on_error_(result.read_error()); }
  3537. }
  3538. if (!should_reconnect(reconnect_count)) { break; }
  3539. wait_for_reconnect();
  3540. reconnect_count++;
  3541. }
  3542. connected_.store(false);
  3543. }
  3544. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3545. // Check for specific event type handler first
  3546. auto it = event_handlers_.find(msg.event);
  3547. if (it != event_handlers_.end()) {
  3548. it->second(msg);
  3549. return;
  3550. }
  3551. // Fall back to generic message handler
  3552. if (on_message_) { on_message_(msg); }
  3553. }
  3554. inline bool SSEClient::should_reconnect(int count) const {
  3555. if (!running_.load()) { return false; }
  3556. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3557. return count < max_reconnect_attempts_;
  3558. }
  3559. inline void SSEClient::wait_for_reconnect() {
  3560. // Use small increments to check running_ flag frequently
  3561. auto waited = 0;
  3562. while (running_.load() && waited < reconnect_interval_ms_) {
  3563. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3564. waited += 100;
  3565. }
  3566. }
  3567. } // namespace sse
  3568. #ifdef CPPHTTPLIB_SSL_ENABLED
  3569. /*
  3570. * TLS abstraction layer - internal function declarations
  3571. * These are implementation details and not part of the public API.
  3572. */
  3573. namespace tls {
  3574. // Client context
  3575. ctx_t create_client_context();
  3576. void free_context(ctx_t ctx);
  3577. bool set_min_version(ctx_t ctx, Version version);
  3578. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3579. bool load_ca_file(ctx_t ctx, const char *file_path);
  3580. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3581. bool load_system_certs(ctx_t ctx);
  3582. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3583. const char *password);
  3584. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3585. const char *key_path, const char *password);
  3586. // Server context
  3587. ctx_t create_server_context();
  3588. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3589. const char *password);
  3590. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3591. const char *key_path, const char *password);
  3592. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3593. void set_verify_client(ctx_t ctx, bool require);
  3594. // Session management
  3595. session_t create_session(ctx_t ctx, socket_t sock);
  3596. void free_session(session_t session);
  3597. bool set_sni(session_t session, const char *hostname);
  3598. bool set_hostname(session_t session, const char *hostname);
  3599. // Handshake (non-blocking capable)
  3600. TlsError connect(session_t session);
  3601. TlsError accept(session_t session);
  3602. // Handshake with timeout (blocking until timeout)
  3603. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3604. time_t timeout_usec, TlsError *err);
  3605. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3606. time_t timeout_usec, TlsError *err);
  3607. // I/O (non-blocking capable)
  3608. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3609. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3610. int pending(const_session_t session);
  3611. void shutdown(session_t session, bool graceful);
  3612. // Connection state
  3613. bool is_peer_closed(session_t session, socket_t sock);
  3614. // Certificate verification
  3615. cert_t get_peer_cert(const_session_t session);
  3616. void free_cert(cert_t cert);
  3617. bool verify_hostname(cert_t cert, const char *hostname);
  3618. uint64_t hostname_mismatch_code();
  3619. long get_verify_result(const_session_t session);
  3620. // Certificate introspection
  3621. std::string get_cert_subject_cn(cert_t cert);
  3622. std::string get_cert_issuer_name(cert_t cert);
  3623. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3624. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3625. std::string get_cert_serial(cert_t cert);
  3626. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3627. const char *get_sni(const_session_t session);
  3628. // CA store management
  3629. ca_store_t create_ca_store(const char *pem, size_t len);
  3630. void free_ca_store(ca_store_t store);
  3631. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3632. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3633. std::vector<std::string> get_ca_names(ctx_t ctx);
  3634. // Dynamic certificate update (for servers)
  3635. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3636. const char *password);
  3637. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3638. // Certificate verification callback
  3639. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3640. long get_verify_error(const_session_t session);
  3641. std::string verify_error_string(long error_code);
  3642. // TlsError information
  3643. uint64_t peek_error();
  3644. uint64_t get_error();
  3645. std::string error_string(uint64_t code);
  3646. } // namespace tls
  3647. #endif // CPPHTTPLIB_SSL_ENABLED
  3648. /*
  3649. * Group 1: detail namespace - Non-SSL utilities
  3650. */
  3651. namespace detail {
  3652. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3653. const void *optval, socklen_t optlen) {
  3654. return setsockopt(sock, level, optname,
  3655. #ifdef _WIN32
  3656. reinterpret_cast<const char *>(optval),
  3657. #else
  3658. optval,
  3659. #endif
  3660. optlen) == 0;
  3661. }
  3662. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3663. time_t sec, time_t usec) {
  3664. #ifdef _WIN32
  3665. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3666. #else
  3667. timeval timeout;
  3668. timeout.tv_sec = static_cast<long>(sec);
  3669. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3670. #endif
  3671. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3672. }
  3673. inline bool is_hex(char c, int &v) {
  3674. if (is_ascii_digit(c)) {
  3675. v = c - '0';
  3676. return true;
  3677. } else if ('A' <= c && c <= 'F') {
  3678. v = c - 'A' + 10;
  3679. return true;
  3680. } else if ('a' <= c && c <= 'f') {
  3681. v = c - 'a' + 10;
  3682. return true;
  3683. }
  3684. return false;
  3685. }
  3686. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3687. int &val) {
  3688. if (i >= s.size()) { return false; }
  3689. val = 0;
  3690. for (; cnt; i++, cnt--) {
  3691. if (!s[i]) { return false; }
  3692. auto v = 0;
  3693. if (is_hex(s[i], v)) {
  3694. val = val * 16 + v;
  3695. } else {
  3696. return false;
  3697. }
  3698. }
  3699. return true;
  3700. }
  3701. inline std::string from_i_to_hex(size_t n) {
  3702. static const auto charset = "0123456789abcdef";
  3703. std::string ret;
  3704. do {
  3705. ret = charset[n & 15] + ret;
  3706. n >>= 4;
  3707. } while (n > 0);
  3708. return ret;
  3709. }
  3710. inline std::string compute_etag(const FileStat &fs) {
  3711. if (!fs.is_file()) { return std::string(); }
  3712. // If mtime cannot be determined (negative value indicates an error
  3713. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3714. // value like 0 could collide with a real file that legitimately has
  3715. // mtime == 0 (epoch) and lead to misleading validators.
  3716. auto mtime_raw = fs.mtime();
  3717. if (mtime_raw < 0) { return std::string(); }
  3718. auto mtime = static_cast<size_t>(mtime_raw);
  3719. auto size = fs.size();
  3720. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3721. from_i_to_hex(size) + "\"";
  3722. }
  3723. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3724. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3725. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3726. inline std::string file_mtime_to_http_date(time_t mtime) {
  3727. if (mtime < 0) { return std::string(); }
  3728. struct tm tm_buf;
  3729. #ifdef _WIN32
  3730. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3731. #else
  3732. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3733. #endif
  3734. char buf[64];
  3735. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3736. return std::string();
  3737. }
  3738. return std::string(buf);
  3739. }
  3740. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3741. inline time_t parse_http_date(const std::string &date_str) {
  3742. struct tm tm_buf;
  3743. // Create a classic locale object once for all parsing attempts
  3744. const std::locale classic_locale = std::locale::classic();
  3745. // Try to parse using std::get_time (C++11, cross-platform)
  3746. auto try_parse = [&](const char *fmt) -> bool {
  3747. std::istringstream ss(date_str);
  3748. ss.imbue(classic_locale);
  3749. memset(&tm_buf, 0, sizeof(tm_buf));
  3750. ss >> std::get_time(&tm_buf, fmt);
  3751. return !ss.fail();
  3752. };
  3753. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3754. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3755. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3756. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3757. // asctime format: "Sun Nov 6 08:49:37 1994"
  3758. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3759. return static_cast<time_t>(-1);
  3760. }
  3761. }
  3762. }
  3763. #ifdef _WIN32
  3764. return _mkgmtime(&tm_buf);
  3765. #elif defined _AIX
  3766. return mktime(&tm_buf);
  3767. #else
  3768. return timegm(&tm_buf);
  3769. #endif
  3770. }
  3771. inline bool is_weak_etag(const std::string &s) {
  3772. // Check if the string is a weak ETag (starts with 'W/"')
  3773. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3774. }
  3775. inline bool is_strong_etag(const std::string &s) {
  3776. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3777. // chars)
  3778. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3779. }
  3780. inline size_t to_utf8(int code, char *buff) {
  3781. if (code < 0x0080) {
  3782. buff[0] = static_cast<char>(code & 0x7F);
  3783. return 1;
  3784. } else if (code < 0x0800) {
  3785. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3786. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3787. return 2;
  3788. } else if (code < 0xD800) {
  3789. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3790. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3791. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3792. return 3;
  3793. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3794. return 0;
  3795. } else if (code < 0x10000) {
  3796. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3797. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3798. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3799. return 3;
  3800. } else if (code < 0x110000) {
  3801. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3802. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3803. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3804. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3805. return 4;
  3806. }
  3807. // NOTREACHED
  3808. return 0;
  3809. }
  3810. } // namespace detail
  3811. namespace ws {
  3812. namespace impl {
  3813. inline bool is_valid_utf8(const std::string &s) {
  3814. size_t i = 0;
  3815. auto n = s.size();
  3816. while (i < n) {
  3817. auto c = static_cast<unsigned char>(s[i]);
  3818. size_t len;
  3819. uint32_t cp;
  3820. if (c < 0x80) {
  3821. i++;
  3822. continue;
  3823. } else if ((c & 0xE0) == 0xC0) {
  3824. len = 2;
  3825. cp = c & 0x1F;
  3826. } else if ((c & 0xF0) == 0xE0) {
  3827. len = 3;
  3828. cp = c & 0x0F;
  3829. } else if ((c & 0xF8) == 0xF0) {
  3830. len = 4;
  3831. cp = c & 0x07;
  3832. } else {
  3833. return false;
  3834. }
  3835. if (i + len > n) { return false; }
  3836. for (size_t j = 1; j < len; j++) {
  3837. auto b = static_cast<unsigned char>(s[i + j]);
  3838. if ((b & 0xC0) != 0x80) { return false; }
  3839. cp = (cp << 6) | (b & 0x3F);
  3840. }
  3841. // Overlong encoding check
  3842. if (len == 2 && cp < 0x80) { return false; }
  3843. if (len == 3 && cp < 0x800) { return false; }
  3844. if (len == 4 && cp < 0x10000) { return false; }
  3845. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3846. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3847. if (cp > 0x10FFFF) { return false; }
  3848. i += len;
  3849. }
  3850. return true;
  3851. }
  3852. } // namespace impl
  3853. } // namespace ws
  3854. namespace detail {
  3855. // NOTE: This code came up with the following stackoverflow post:
  3856. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3857. inline std::string base64_encode(const std::string &in) {
  3858. static const auto lookup =
  3859. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3860. std::string out;
  3861. out.reserve(in.size());
  3862. // Unsigned: the accumulator is never masked, so with a signed int the
  3863. // `val << 8` below overflows once enough bytes are folded in (undefined
  3864. // behaviour before C++20). Only the low bits are ever emitted, so the
  3865. // wrap-around of an unsigned accumulator does not affect the output.
  3866. uint32_t val = 0;
  3867. auto valb = -6;
  3868. for (auto c : in) {
  3869. val = (val << 8) + static_cast<uint8_t>(c);
  3870. valb += 8;
  3871. while (valb >= 0) {
  3872. out.push_back(lookup[(val >> valb) & 0x3F]);
  3873. valb -= 6;
  3874. }
  3875. }
  3876. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3877. while (out.size() % 4) {
  3878. out.push_back('=');
  3879. }
  3880. return out;
  3881. }
  3882. inline std::string sha1(const std::string &input) {
  3883. // RFC 3174 SHA-1 implementation
  3884. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3885. return (x << n) | (x >> (32 - n));
  3886. };
  3887. uint32_t h0 = 0x67452301;
  3888. uint32_t h1 = 0xEFCDAB89;
  3889. uint32_t h2 = 0x98BADCFE;
  3890. uint32_t h3 = 0x10325476;
  3891. uint32_t h4 = 0xC3D2E1F0;
  3892. // Pre-processing: adding padding bits
  3893. std::string msg = input;
  3894. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3895. msg.push_back(static_cast<char>(0x80u));
  3896. while (msg.size() % 64 != 56) {
  3897. msg.push_back(0);
  3898. }
  3899. // Append original length in bits as 64-bit big-endian
  3900. for (int i = 56; i >= 0; i -= 8) {
  3901. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3902. }
  3903. // Process each 512-bit chunk
  3904. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3905. uint32_t w[80];
  3906. for (size_t i = 0; i < 16; i++) {
  3907. w[i] =
  3908. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3909. << 24) |
  3910. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3911. << 16) |
  3912. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3913. << 8) |
  3914. (static_cast<uint32_t>(
  3915. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3916. }
  3917. for (int i = 16; i < 80; i++) {
  3918. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3919. }
  3920. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3921. for (int i = 0; i < 80; i++) {
  3922. uint32_t f, k;
  3923. if (i < 20) {
  3924. f = (b & c) | ((~b) & d);
  3925. k = 0x5A827999;
  3926. } else if (i < 40) {
  3927. f = b ^ c ^ d;
  3928. k = 0x6ED9EBA1;
  3929. } else if (i < 60) {
  3930. f = (b & c) | (b & d) | (c & d);
  3931. k = 0x8F1BBCDC;
  3932. } else {
  3933. f = b ^ c ^ d;
  3934. k = 0xCA62C1D6;
  3935. }
  3936. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3937. e = d;
  3938. d = c;
  3939. c = left_rotate(b, 30);
  3940. b = a;
  3941. a = temp;
  3942. }
  3943. h0 += a;
  3944. h1 += b;
  3945. h2 += c;
  3946. h3 += d;
  3947. h4 += e;
  3948. }
  3949. // Produce the final hash as a 20-byte binary string
  3950. std::string hash(20, '\0');
  3951. for (size_t i = 0; i < 4; i++) {
  3952. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3953. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3954. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3955. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3956. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3957. }
  3958. return hash;
  3959. }
  3960. inline std::string websocket_accept_key(const std::string &client_key) {
  3961. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3962. return base64_encode(sha1(client_key + magic));
  3963. }
  3964. inline bool is_websocket_upgrade(const Request &req) {
  3965. if (req.method != "GET") { return false; }
  3966. // Check Upgrade: websocket (case-insensitive)
  3967. auto upgrade_it = req.headers.find("Upgrade");
  3968. if (upgrade_it == req.headers.end()) { return false; }
  3969. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3970. if (upgrade_val != "websocket") { return false; }
  3971. // Check Connection header contains "Upgrade"
  3972. auto connection_it = req.headers.find("Connection");
  3973. if (connection_it == req.headers.end()) { return false; }
  3974. auto connection_val = case_ignore::to_lower(connection_it->second);
  3975. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3976. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3977. // RFC 6455 Section 4.2.1
  3978. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3979. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3980. return false;
  3981. }
  3982. static const std::string b64chars =
  3983. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3984. for (size_t i = 0; i < 22; i++) {
  3985. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3986. }
  3987. // Check Sec-WebSocket-Version: 13
  3988. auto version = req.get_header_value("Sec-WebSocket-Version");
  3989. if (version != "13") { return false; }
  3990. return true;
  3991. }
  3992. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3993. const char *data, size_t len, bool fin,
  3994. bool mask) {
  3995. // First byte: FIN + opcode
  3996. uint8_t header[2];
  3997. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3998. (static_cast<uint8_t>(opcode) & 0x0F));
  3999. // Second byte: MASK + payload length
  4000. if (len < 126) {
  4001. header[1] = static_cast<uint8_t>(len);
  4002. if (mask) { header[1] |= 0x80; }
  4003. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4004. } else if (len <= 0xFFFF) {
  4005. header[1] = 126;
  4006. if (mask) { header[1] |= 0x80; }
  4007. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4008. uint8_t ext[2];
  4009. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4010. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4011. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4012. } else {
  4013. header[1] = 127;
  4014. if (mask) { header[1] |= 0x80; }
  4015. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4016. uint8_t ext[8];
  4017. for (int i = 7; i >= 0; i--) {
  4018. ext[7 - i] =
  4019. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4020. }
  4021. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4022. }
  4023. if (mask) {
  4024. // Generate random mask key
  4025. thread_local std::mt19937 rng(std::random_device{}());
  4026. uint8_t mask_key[4];
  4027. auto r = rng();
  4028. std::memcpy(mask_key, &r, 4);
  4029. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4030. // Write masked payload in chunks
  4031. const size_t chunk_size = 4096;
  4032. std::vector<char> buf((std::min)(len, chunk_size));
  4033. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4034. size_t n = (std::min)(chunk_size, len - offset);
  4035. for (size_t i = 0; i < n; i++) {
  4036. buf[i] =
  4037. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4038. }
  4039. if (strm.write(buf.data(), n) < 0) { return false; }
  4040. }
  4041. } else {
  4042. if (len > 0) {
  4043. if (strm.write(data, len) < 0) { return false; }
  4044. }
  4045. }
  4046. return true;
  4047. }
  4048. } // namespace detail
  4049. namespace ws {
  4050. namespace impl {
  4051. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4052. std::string &payload, bool &fin,
  4053. bool expect_masked, size_t max_len) {
  4054. // Read first 2 bytes
  4055. uint8_t header[2];
  4056. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4057. fin = (header[0] & 0x80) != 0;
  4058. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4059. if (header[0] & 0x70) { return false; }
  4060. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4061. bool masked = (header[1] & 0x80) != 0;
  4062. uint64_t payload_len = header[1] & 0x7F;
  4063. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4064. // MUST have a payload length of 125 bytes or less
  4065. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4066. if (is_control) {
  4067. if (!fin) { return false; }
  4068. if (payload_len > 125) { return false; }
  4069. }
  4070. if (masked != expect_masked) { return false; }
  4071. // Extended payload length
  4072. if (payload_len == 126) {
  4073. uint8_t ext[2];
  4074. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4075. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4076. } else if (payload_len == 127) {
  4077. uint8_t ext[8];
  4078. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4079. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4080. if (ext[0] & 0x80) { return false; }
  4081. payload_len = 0;
  4082. for (int i = 0; i < 8; i++) {
  4083. payload_len = (payload_len << 8) | ext[i];
  4084. }
  4085. }
  4086. if (payload_len > max_len) { return false; }
  4087. // Read mask key if present
  4088. uint8_t mask_key[4] = {0};
  4089. if (masked) {
  4090. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4091. }
  4092. // Read payload
  4093. payload.resize(static_cast<size_t>(payload_len));
  4094. if (payload_len > 0) {
  4095. size_t total_read = 0;
  4096. while (total_read < payload_len) {
  4097. auto n = strm.read(&payload[total_read],
  4098. static_cast<size_t>(payload_len - total_read));
  4099. if (n <= 0) { return false; }
  4100. total_read += static_cast<size_t>(n);
  4101. }
  4102. }
  4103. // Unmask if needed
  4104. if (masked) {
  4105. for (size_t i = 0; i < payload.size(); i++) {
  4106. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4107. }
  4108. }
  4109. return true;
  4110. }
  4111. } // namespace impl
  4112. } // namespace ws
  4113. namespace detail {
  4114. inline bool is_valid_path(const std::string &path) {
  4115. size_t level = 0;
  4116. size_t i = 0;
  4117. // Skip slash
  4118. while (i < path.size() && path[i] == '/') {
  4119. i++;
  4120. }
  4121. while (i < path.size()) {
  4122. // Read component
  4123. auto beg = i;
  4124. while (i < path.size() && path[i] != '/') {
  4125. if (path[i] == '\0') {
  4126. return false;
  4127. } else if (path[i] == '\\') {
  4128. return false;
  4129. }
  4130. i++;
  4131. }
  4132. auto len = i - beg;
  4133. assert(len > 0);
  4134. if (!path.compare(beg, len, ".")) {
  4135. ;
  4136. } else if (!path.compare(beg, len, "..")) {
  4137. if (level == 0) { return false; }
  4138. level--;
  4139. } else {
  4140. level++;
  4141. }
  4142. // Skip slash
  4143. while (i < path.size() && path[i] == '/') {
  4144. i++;
  4145. }
  4146. }
  4147. return true;
  4148. }
  4149. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4150. #if defined(_WIN32)
  4151. char buf[_MAX_PATH];
  4152. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4153. resolved = buf;
  4154. #elif defined(PATH_MAX)
  4155. char buf[PATH_MAX];
  4156. if (realpath(path, buf) == nullptr) { return false; }
  4157. resolved = buf;
  4158. #else
  4159. auto buf = realpath(path, nullptr);
  4160. auto guard = scope_exit([&]() { std::free(buf); });
  4161. if (buf == nullptr) { return false; }
  4162. resolved = buf;
  4163. #endif
  4164. return true;
  4165. }
  4166. inline bool is_path_within_base(const std::string &resolved_path,
  4167. const std::string &resolved_base) {
  4168. #if defined(_WIN32)
  4169. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4170. resolved_base.size()) == 0;
  4171. #else
  4172. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4173. resolved_base.size()) == 0;
  4174. #endif
  4175. }
  4176. inline FileStat::FileStat(const std::string &path) {
  4177. #if defined(_WIN32)
  4178. auto wpath = u8string_to_wstring(path.c_str());
  4179. ret_ = _wstat(wpath.c_str(), &st_);
  4180. #else
  4181. ret_ = stat(path.c_str(), &st_);
  4182. #endif
  4183. }
  4184. inline bool FileStat::is_file() const {
  4185. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4186. }
  4187. inline bool FileStat::is_dir() const {
  4188. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4189. }
  4190. inline time_t FileStat::mtime() const {
  4191. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4192. : static_cast<time_t>(-1);
  4193. }
  4194. inline size_t FileStat::size() const {
  4195. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4196. }
  4197. inline std::string encode_path(const std::string &s) {
  4198. std::string result;
  4199. result.reserve(s.size());
  4200. for (size_t i = 0; s[i]; i++) {
  4201. switch (s[i]) {
  4202. case ' ': result += "%20"; break;
  4203. case '+': result += "%2B"; break;
  4204. case '\r': result += "%0D"; break;
  4205. case '\n': result += "%0A"; break;
  4206. case '\'': result += "%27"; break;
  4207. case ',': result += "%2C"; break;
  4208. // case ':': result += "%3A"; break; // ok? probably...
  4209. case ';': result += "%3B"; break;
  4210. default:
  4211. auto c = static_cast<uint8_t>(s[i]);
  4212. if (c >= 0x80) {
  4213. result += '%';
  4214. char hex[4];
  4215. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4216. assert(len == 2);
  4217. result.append(hex, static_cast<size_t>(len));
  4218. } else {
  4219. result += s[i];
  4220. }
  4221. break;
  4222. }
  4223. }
  4224. return result;
  4225. }
  4226. inline std::string file_extension(const std::string &path) {
  4227. std::smatch m;
  4228. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4229. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4230. return std::string();
  4231. }
  4232. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4233. template <typename T>
  4234. inline bool parse_header(const char *beg, const char *end, T fn);
  4235. template <typename T>
  4236. inline bool parse_header(const char *beg, const char *end, T fn) {
  4237. // Skip trailing spaces and tabs.
  4238. while (beg < end && is_space_or_tab(end[-1])) {
  4239. end--;
  4240. }
  4241. auto p = beg;
  4242. while (p < end && *p != ':') {
  4243. p++;
  4244. }
  4245. auto name = std::string(beg, p);
  4246. if (!detail::fields::is_field_name(name)) { return false; }
  4247. if (p == end) { return false; }
  4248. auto key_end = p;
  4249. if (*p++ != ':') { return false; }
  4250. while (p < end && is_space_or_tab(*p)) {
  4251. p++;
  4252. }
  4253. if (p <= end) {
  4254. auto key_len = key_end - beg;
  4255. if (!key_len) { return false; }
  4256. auto key = std::string(beg, key_end);
  4257. auto val = std::string(p, end);
  4258. if (!detail::fields::is_field_value(val)) { return false; }
  4259. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4260. // percent-decoded by the recipient. Applications that need to interpret a
  4261. // value as a URI component should call httplib::decode_uri_component()
  4262. // (or decode_path_component()) explicitly.
  4263. fn(key, val);
  4264. return true;
  4265. }
  4266. return false;
  4267. }
  4268. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4269. const Headers &src_headers) {
  4270. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4271. // transfer coding is complete when a chunk with a chunk-size of zero is
  4272. // received, possibly followed by a trailer section, and finally terminated by
  4273. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4274. //
  4275. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4276. // doesn't care for the existence of the final CRLF. In other words, it seems
  4277. // to be ok whether the final CRLF exists or not in the chunked data.
  4278. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4279. //
  4280. // According to the reference code in RFC 9112, cpp-httplib now allows
  4281. // chunked transfer coding data without the final CRLF.
  4282. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4283. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4284. "transfer-encoding",
  4285. "content-length",
  4286. "host",
  4287. "authorization",
  4288. "www-authenticate",
  4289. "proxy-authenticate",
  4290. "proxy-authorization",
  4291. "cookie",
  4292. "set-cookie",
  4293. "cache-control",
  4294. "expect",
  4295. "max-forwards",
  4296. "pragma",
  4297. "range",
  4298. "te",
  4299. "age",
  4300. "expires",
  4301. "date",
  4302. "location",
  4303. "retry-after",
  4304. "vary",
  4305. "warning",
  4306. "content-encoding",
  4307. "content-type",
  4308. "content-range",
  4309. "trailer"};
  4310. case_ignore::unordered_set<std::string> declared_trailers;
  4311. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4312. if (trailer_header && std::strlen(trailer_header)) {
  4313. auto len = std::strlen(trailer_header);
  4314. split(trailer_header, trailer_header + len, ',',
  4315. [&](const char *b, const char *e) {
  4316. const char *kbeg = b;
  4317. const char *kend = e;
  4318. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4319. ++kbeg;
  4320. }
  4321. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4322. --kend;
  4323. }
  4324. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4325. if (!key.empty() &&
  4326. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4327. declared_trailers.insert(key);
  4328. }
  4329. });
  4330. }
  4331. size_t trailer_header_count = 0;
  4332. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4333. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4334. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4335. constexpr auto line_terminator_len = 2;
  4336. auto line_beg = line_reader.ptr();
  4337. auto line_end =
  4338. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4339. if (!parse_header(line_beg, line_end,
  4340. [&](const std::string &key, const std::string &val) {
  4341. if (declared_trailers.find(key) !=
  4342. declared_trailers.end()) {
  4343. dest.emplace(key, val);
  4344. trailer_header_count++;
  4345. }
  4346. })) {
  4347. return false;
  4348. }
  4349. if (!line_reader.getline()) { return false; }
  4350. }
  4351. return true;
  4352. }
  4353. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4354. size_t right) {
  4355. while (b + left < e && is_space_or_tab(b[left])) {
  4356. left++;
  4357. }
  4358. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4359. right--;
  4360. }
  4361. return std::make_pair(left, right);
  4362. }
  4363. inline std::string trim_copy(const std::string &s) {
  4364. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4365. return s.substr(r.first, r.second - r.first);
  4366. }
  4367. inline std::string trim_double_quotes_copy(const std::string &s) {
  4368. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4369. return s.substr(1, s.size() - 2);
  4370. }
  4371. return s;
  4372. }
  4373. inline void
  4374. divide(const char *data, std::size_t size, char d,
  4375. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4376. fn) {
  4377. const auto it = std::find(data, data + size, d);
  4378. const auto found = static_cast<std::size_t>(it != data + size);
  4379. const auto lhs_data = data;
  4380. const auto lhs_size = static_cast<std::size_t>(it - data);
  4381. const auto rhs_data = it + found;
  4382. const auto rhs_size = size - lhs_size - found;
  4383. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4384. }
  4385. inline void
  4386. divide(const std::string &str, char d,
  4387. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4388. fn) {
  4389. divide(str.data(), str.size(), d, std::move(fn));
  4390. }
  4391. inline void split(const char *b, const char *e, char d,
  4392. std::function<void(const char *, const char *)> fn) {
  4393. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4394. }
  4395. inline void split(const char *b, const char *e, char d, size_t m,
  4396. std::function<void(const char *, const char *)> fn) {
  4397. size_t i = 0;
  4398. size_t beg = 0;
  4399. size_t count = 1;
  4400. while (e ? (b + i < e) : (b[i] != '\0')) {
  4401. if (b[i] == d && count < m) {
  4402. auto r = trim(b, e, beg, i);
  4403. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4404. beg = i + 1;
  4405. count++;
  4406. }
  4407. i++;
  4408. }
  4409. if (i) {
  4410. auto r = trim(b, e, beg, i);
  4411. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4412. }
  4413. }
  4414. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4415. std::function<bool(const char *, const char *)> fn) {
  4416. size_t i = 0;
  4417. size_t beg = 0;
  4418. size_t count = 1;
  4419. while (e ? (b + i < e) : (b[i] != '\0')) {
  4420. if (b[i] == d && count < m) {
  4421. auto r = trim(b, e, beg, i);
  4422. if (r.first < r.second) {
  4423. auto found = fn(&b[r.first], &b[r.second]);
  4424. if (found) { return true; }
  4425. }
  4426. beg = i + 1;
  4427. count++;
  4428. }
  4429. i++;
  4430. }
  4431. if (i) {
  4432. auto r = trim(b, e, beg, i);
  4433. if (r.first < r.second) {
  4434. auto found = fn(&b[r.first], &b[r.second]);
  4435. if (found) { return true; }
  4436. }
  4437. }
  4438. return false;
  4439. }
  4440. inline bool split_find(const char *b, const char *e, char d,
  4441. std::function<bool(const char *, const char *)> fn) {
  4442. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4443. std::move(fn));
  4444. }
  4445. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4446. size_t fixed_buffer_size)
  4447. : strm_(strm), fixed_buffer_(fixed_buffer),
  4448. fixed_buffer_size_(fixed_buffer_size) {}
  4449. inline const char *stream_line_reader::ptr() const {
  4450. if (growable_buffer_.empty()) {
  4451. return fixed_buffer_;
  4452. } else {
  4453. return growable_buffer_.data();
  4454. }
  4455. }
  4456. inline size_t stream_line_reader::size() const {
  4457. if (growable_buffer_.empty()) {
  4458. return fixed_buffer_used_size_;
  4459. } else {
  4460. return growable_buffer_.size();
  4461. }
  4462. }
  4463. inline bool stream_line_reader::end_with_crlf() const {
  4464. auto end = ptr() + size();
  4465. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4466. }
  4467. inline bool stream_line_reader::getline() {
  4468. fixed_buffer_used_size_ = 0;
  4469. growable_buffer_.clear();
  4470. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4471. char prev_byte = 0;
  4472. #endif
  4473. for (size_t i = 0;; i++) {
  4474. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4475. // Treat exceptionally long lines as an error to
  4476. // prevent infinite loops/memory exhaustion
  4477. return false;
  4478. }
  4479. char byte;
  4480. auto n = strm_.read(&byte, 1);
  4481. if (n < 0) {
  4482. return false;
  4483. } else if (n == 0) {
  4484. if (i == 0) {
  4485. return false;
  4486. } else {
  4487. break;
  4488. }
  4489. }
  4490. append(byte);
  4491. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4492. if (byte == '\n') { break; }
  4493. #else
  4494. if (prev_byte == '\r' && byte == '\n') { break; }
  4495. prev_byte = byte;
  4496. #endif
  4497. }
  4498. return true;
  4499. }
  4500. inline void stream_line_reader::append(char c) {
  4501. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4502. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4503. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4504. } else {
  4505. if (growable_buffer_.empty()) {
  4506. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4507. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4508. }
  4509. growable_buffer_ += c;
  4510. }
  4511. }
  4512. inline mmap::mmap(const char *path) { open(path); }
  4513. inline mmap::~mmap() { close(); }
  4514. inline bool mmap::open(const char *path) {
  4515. close();
  4516. #if defined(_WIN32)
  4517. auto wpath = u8string_to_wstring(path);
  4518. if (wpath.empty()) { return false; }
  4519. hFile_ =
  4520. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4521. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4522. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4523. LARGE_INTEGER size{};
  4524. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4525. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4526. // See:
  4527. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4528. if (static_cast<ULONGLONG>(size.QuadPart) >
  4529. (std::numeric_limits<decltype(size_)>::max)()) {
  4530. // `size_t` might be 32-bits, on 32-bits Windows.
  4531. return false;
  4532. }
  4533. size_ = static_cast<size_t>(size.QuadPart);
  4534. hMapping_ =
  4535. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4536. // Special treatment for an empty file...
  4537. if (hMapping_ == NULL && size_ == 0) {
  4538. close();
  4539. is_open_empty_file = true;
  4540. return true;
  4541. }
  4542. if (hMapping_ == NULL) {
  4543. close();
  4544. return false;
  4545. }
  4546. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4547. if (addr_ == nullptr) {
  4548. close();
  4549. return false;
  4550. }
  4551. #else
  4552. fd_ = ::open(path, O_RDONLY);
  4553. if (fd_ == -1) { return false; }
  4554. struct stat sb;
  4555. if (fstat(fd_, &sb) == -1) {
  4556. close();
  4557. return false;
  4558. }
  4559. size_ = static_cast<size_t>(sb.st_size);
  4560. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4561. // Special treatment for an empty file...
  4562. if (addr_ == MAP_FAILED && size_ == 0) {
  4563. close();
  4564. is_open_empty_file = true;
  4565. return false;
  4566. }
  4567. #endif
  4568. return true;
  4569. }
  4570. inline bool mmap::is_open() const {
  4571. return is_open_empty_file ? true : addr_ != nullptr;
  4572. }
  4573. inline size_t mmap::size() const { return size_; }
  4574. inline const char *mmap::data() const {
  4575. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4576. }
  4577. inline void mmap::close() {
  4578. #if defined(_WIN32)
  4579. if (addr_) {
  4580. ::UnmapViewOfFile(addr_);
  4581. addr_ = nullptr;
  4582. }
  4583. if (hMapping_) {
  4584. ::CloseHandle(hMapping_);
  4585. hMapping_ = NULL;
  4586. }
  4587. if (hFile_ != INVALID_HANDLE_VALUE) {
  4588. ::CloseHandle(hFile_);
  4589. hFile_ = INVALID_HANDLE_VALUE;
  4590. }
  4591. is_open_empty_file = false;
  4592. #else
  4593. if (addr_ != nullptr) {
  4594. munmap(addr_, size_);
  4595. addr_ = nullptr;
  4596. }
  4597. if (fd_ != -1) {
  4598. ::close(fd_);
  4599. fd_ = -1;
  4600. }
  4601. #endif
  4602. size_ = 0;
  4603. }
  4604. inline int close_socket(socket_t sock) noexcept {
  4605. #ifdef _WIN32
  4606. return closesocket(sock);
  4607. #else
  4608. return close(sock);
  4609. #endif
  4610. }
  4611. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4612. ssize_t res = 0;
  4613. while (true) {
  4614. res = fn();
  4615. if (res < 0 && errno == EINTR) {
  4616. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4617. continue;
  4618. }
  4619. break;
  4620. }
  4621. return res;
  4622. }
  4623. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4624. return handle_EINTR([&]() {
  4625. return recv(sock,
  4626. #ifdef _WIN32
  4627. static_cast<char *>(ptr), static_cast<int>(size),
  4628. #else
  4629. ptr, size,
  4630. #endif
  4631. flags);
  4632. });
  4633. }
  4634. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4635. int flags) {
  4636. return handle_EINTR([&]() {
  4637. return send(sock,
  4638. #ifdef _WIN32
  4639. static_cast<const char *>(ptr), static_cast<int>(size),
  4640. #else
  4641. ptr, size,
  4642. #endif
  4643. flags);
  4644. });
  4645. }
  4646. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4647. #ifdef _WIN32
  4648. return ::WSAPoll(fds, nfds, timeout);
  4649. #else
  4650. return ::poll(fds, nfds, timeout);
  4651. #endif
  4652. }
  4653. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4654. time_t usec) {
  4655. struct pollfd pfd;
  4656. pfd.fd = sock;
  4657. pfd.events = events;
  4658. pfd.revents = 0;
  4659. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4660. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4661. }
  4662. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4663. return select_impl(sock, POLLIN, sec, usec);
  4664. }
  4665. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4666. return select_impl(sock, POLLOUT, sec, usec);
  4667. }
  4668. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4669. time_t usec) {
  4670. struct pollfd pfd_read;
  4671. pfd_read.fd = sock;
  4672. pfd_read.events = POLLIN | POLLOUT;
  4673. pfd_read.revents = 0;
  4674. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4675. auto poll_res =
  4676. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4677. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4678. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4679. auto error = 0;
  4680. socklen_t len = sizeof(error);
  4681. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4682. reinterpret_cast<char *>(&error), &len);
  4683. auto successful = res >= 0 && !error;
  4684. return successful ? Error::Success : Error::Connection;
  4685. }
  4686. return Error::Connection;
  4687. }
  4688. inline bool is_socket_alive(socket_t sock) {
  4689. const auto val = detail::select_read(sock, 0, 0);
  4690. if (val == 0) {
  4691. return true;
  4692. } else if (val < 0 && errno == EBADF) {
  4693. return false;
  4694. }
  4695. char buf[1];
  4696. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4697. }
  4698. class SocketStream final : public Stream {
  4699. public:
  4700. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4701. time_t write_timeout_sec, time_t write_timeout_usec,
  4702. time_t max_timeout_msec = 0,
  4703. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4704. (std::chrono::steady_clock::time_point::min)());
  4705. ~SocketStream() override;
  4706. bool is_readable() const override;
  4707. bool wait_readable() const override;
  4708. bool wait_writable() const override;
  4709. bool is_peer_alive() const override;
  4710. ssize_t read(char *ptr, size_t size) override;
  4711. ssize_t write(const char *ptr, size_t size) override;
  4712. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4713. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4714. socket_t socket() const override;
  4715. time_t duration() const override;
  4716. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4717. private:
  4718. socket_t sock_;
  4719. time_t read_timeout_sec_;
  4720. time_t read_timeout_usec_;
  4721. time_t write_timeout_sec_;
  4722. time_t write_timeout_usec_;
  4723. time_t max_timeout_msec_;
  4724. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4725. std::vector<char> read_buff_;
  4726. size_t read_buff_off_ = 0;
  4727. size_t read_buff_content_size_ = 0;
  4728. static const size_t read_buff_size_ = 1024l * 4;
  4729. };
  4730. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4731. time_t keep_alive_timeout_sec) {
  4732. using namespace std::chrono;
  4733. const auto interval_usec =
  4734. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4735. // Avoid expensive `steady_clock::now()` call for the first time
  4736. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4737. const auto start = steady_clock::now() - microseconds{interval_usec};
  4738. const auto timeout = seconds{keep_alive_timeout_sec};
  4739. while (true) {
  4740. if (svr_sock == INVALID_SOCKET) {
  4741. break; // Server socket is closed
  4742. }
  4743. auto val = select_read(sock, 0, interval_usec);
  4744. if (val < 0) {
  4745. break; // Ssocket error
  4746. } else if (val == 0) {
  4747. if (steady_clock::now() - start > timeout) {
  4748. break; // Timeout
  4749. }
  4750. } else {
  4751. return true; // Ready for read
  4752. }
  4753. }
  4754. return false;
  4755. }
  4756. template <typename T>
  4757. inline bool
  4758. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4759. size_t keep_alive_max_count,
  4760. time_t keep_alive_timeout_sec, T callback) {
  4761. assert(keep_alive_max_count > 0);
  4762. auto ret = false;
  4763. auto count = keep_alive_max_count;
  4764. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4765. auto close_connection = count == 1;
  4766. auto connection_closed = false;
  4767. ret = callback(close_connection, connection_closed);
  4768. if (!ret || connection_closed) { break; }
  4769. count--;
  4770. }
  4771. return ret;
  4772. }
  4773. template <typename T>
  4774. inline bool
  4775. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4776. size_t keep_alive_max_count,
  4777. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4778. time_t read_timeout_usec, time_t write_timeout_sec,
  4779. time_t write_timeout_usec, T callback) {
  4780. return process_server_socket_core(
  4781. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4782. [&](bool close_connection, bool &connection_closed) {
  4783. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4784. write_timeout_sec, write_timeout_usec);
  4785. return callback(strm, close_connection, connection_closed);
  4786. });
  4787. }
  4788. inline bool process_client_socket(
  4789. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4790. time_t write_timeout_sec, time_t write_timeout_usec,
  4791. time_t max_timeout_msec,
  4792. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4793. std::function<bool(Stream &)> callback) {
  4794. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4795. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4796. start_time);
  4797. return callback(strm);
  4798. }
  4799. inline int shutdown_socket(socket_t sock) noexcept {
  4800. #ifdef _WIN32
  4801. return shutdown(sock, SD_BOTH);
  4802. #else
  4803. return shutdown(sock, SHUT_RDWR);
  4804. #endif
  4805. }
  4806. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4807. if (s.size() > 1 && s[0] == '\0') {
  4808. auto ret = s;
  4809. ret[0] = '@';
  4810. return ret;
  4811. }
  4812. return s;
  4813. }
  4814. inline std::string
  4815. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4816. if (s.size() > 1 && s[0] == '@') {
  4817. auto ret = s;
  4818. ret[0] = '\0';
  4819. return ret;
  4820. }
  4821. return s;
  4822. }
  4823. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4824. const struct addrinfo *hints,
  4825. struct addrinfo **res, time_t timeout_sec) {
  4826. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4827. if (timeout_sec <= 0) {
  4828. // No timeout specified, use standard getaddrinfo
  4829. return getaddrinfo(node, service, hints, res);
  4830. }
  4831. #ifdef _WIN32
  4832. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4833. OVERLAPPED overlapped = {};
  4834. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4835. if (!event) { return EAI_FAIL; }
  4836. overlapped.hEvent = event;
  4837. PADDRINFOEXW result_addrinfo = nullptr;
  4838. HANDLE cancel_handle = nullptr;
  4839. ADDRINFOEXW hints_ex = {};
  4840. if (hints) {
  4841. hints_ex.ai_flags = hints->ai_flags;
  4842. hints_ex.ai_family = hints->ai_family;
  4843. hints_ex.ai_socktype = hints->ai_socktype;
  4844. hints_ex.ai_protocol = hints->ai_protocol;
  4845. }
  4846. auto wnode = u8string_to_wstring(node);
  4847. auto wservice = u8string_to_wstring(service);
  4848. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4849. hints ? &hints_ex : nullptr, &result_addrinfo,
  4850. nullptr, &overlapped, nullptr, &cancel_handle);
  4851. if (ret == WSA_IO_PENDING) {
  4852. auto wait_result =
  4853. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4854. if (wait_result == WAIT_TIMEOUT) {
  4855. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4856. ::CloseHandle(event);
  4857. return EAI_AGAIN;
  4858. }
  4859. DWORD bytes_returned;
  4860. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4861. &bytes_returned, FALSE)) {
  4862. ::CloseHandle(event);
  4863. return ::WSAGetLastError();
  4864. }
  4865. }
  4866. ::CloseHandle(event);
  4867. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4868. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4869. return 0;
  4870. }
  4871. return ret;
  4872. #elif TARGET_OS_MAC && defined(__clang__)
  4873. if (!node) { return EAI_NONAME; }
  4874. // macOS implementation using CFHost API for asynchronous DNS resolution
  4875. CFStringRef hostname_ref = CFStringCreateWithCString(
  4876. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4877. if (!hostname_ref) { return EAI_MEMORY; }
  4878. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4879. CFRelease(hostname_ref);
  4880. if (!host_ref) { return EAI_MEMORY; }
  4881. // Set up context for callback
  4882. struct CFHostContext {
  4883. bool completed = false;
  4884. bool success = false;
  4885. CFArrayRef addresses = nullptr;
  4886. std::mutex mutex;
  4887. std::condition_variable cv;
  4888. } context;
  4889. CFHostClientContext client_context;
  4890. memset(&client_context, 0, sizeof(client_context));
  4891. client_context.info = &context;
  4892. // Set callback
  4893. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4894. const CFStreamError *error, void *info) {
  4895. auto ctx = static_cast<CFHostContext *>(info);
  4896. std::lock_guard<std::mutex> lock(ctx->mutex);
  4897. if (error && error->error != 0) {
  4898. ctx->success = false;
  4899. } else {
  4900. Boolean hasBeenResolved;
  4901. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4902. if (ctx->addresses && hasBeenResolved) {
  4903. CFRetain(ctx->addresses);
  4904. ctx->success = true;
  4905. } else {
  4906. ctx->success = false;
  4907. }
  4908. }
  4909. ctx->completed = true;
  4910. ctx->cv.notify_one();
  4911. };
  4912. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4913. CFRelease(host_ref);
  4914. return EAI_SYSTEM;
  4915. }
  4916. // Schedule on run loop
  4917. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4918. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4919. // Start resolution
  4920. CFStreamError stream_error;
  4921. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4922. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4923. CFRelease(host_ref);
  4924. return EAI_FAIL;
  4925. }
  4926. // Wait for completion with timeout
  4927. auto timeout_time =
  4928. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4929. bool timed_out = false;
  4930. {
  4931. std::unique_lock<std::mutex> lock(context.mutex);
  4932. while (!context.completed) {
  4933. auto now = std::chrono::steady_clock::now();
  4934. if (now >= timeout_time) {
  4935. timed_out = true;
  4936. break;
  4937. }
  4938. // Run the runloop for a short time
  4939. lock.unlock();
  4940. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4941. lock.lock();
  4942. }
  4943. }
  4944. // Clean up
  4945. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4946. CFHostSetClient(host_ref, nullptr, nullptr);
  4947. if (timed_out || !context.completed) {
  4948. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4949. CFRelease(host_ref);
  4950. return EAI_AGAIN;
  4951. }
  4952. if (!context.success || !context.addresses) {
  4953. CFRelease(host_ref);
  4954. return EAI_NODATA;
  4955. }
  4956. // Convert CFArray to addrinfo
  4957. CFIndex count = CFArrayGetCount(context.addresses);
  4958. if (count == 0) {
  4959. CFRelease(context.addresses);
  4960. CFRelease(host_ref);
  4961. return EAI_NODATA;
  4962. }
  4963. struct addrinfo *result_addrinfo = nullptr;
  4964. struct addrinfo **current = &result_addrinfo;
  4965. for (CFIndex i = 0; i < count; i++) {
  4966. CFDataRef addr_data =
  4967. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4968. if (!addr_data) continue;
  4969. const struct sockaddr *sockaddr_ptr =
  4970. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4971. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4972. // Allocate addrinfo structure
  4973. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4974. if (!*current) {
  4975. freeaddrinfo(result_addrinfo);
  4976. CFRelease(context.addresses);
  4977. CFRelease(host_ref);
  4978. return EAI_MEMORY;
  4979. }
  4980. memset(*current, 0, sizeof(struct addrinfo));
  4981. // Set up addrinfo fields
  4982. (*current)->ai_family = sockaddr_ptr->sa_family;
  4983. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4984. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4985. (*current)->ai_addrlen = sockaddr_len;
  4986. // Copy sockaddr
  4987. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4988. if (!(*current)->ai_addr) {
  4989. freeaddrinfo(result_addrinfo);
  4990. CFRelease(context.addresses);
  4991. CFRelease(host_ref);
  4992. return EAI_MEMORY;
  4993. }
  4994. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4995. // Set port if service is specified
  4996. if (service && *service) {
  4997. int port = 0;
  4998. if (parse_port(service, strlen(service), port)) {
  4999. if (sockaddr_ptr->sa_family == AF_INET) {
  5000. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5001. ->sin_port = htons(static_cast<uint16_t>(port));
  5002. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5003. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5004. ->sin6_port = htons(static_cast<uint16_t>(port));
  5005. }
  5006. }
  5007. }
  5008. current = &((*current)->ai_next);
  5009. }
  5010. CFRelease(context.addresses);
  5011. CFRelease(host_ref);
  5012. *res = result_addrinfo;
  5013. return 0;
  5014. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5015. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5016. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5017. // the resolver worker still references the stack-local gaicb. The cancel
  5018. // path therefore waits (gai_suspend with no timeout) for the worker to
  5019. // actually finish before letting the stack frame go. The trade-off is that
  5020. // a wedged DNS server can hold this thread for the system resolver timeout
  5021. // (~30s by default) past the caller's connection timeout.
  5022. struct gaicb request {};
  5023. struct gaicb *requests[1] = {&request};
  5024. struct sigevent sevp {};
  5025. struct timespec timeout {
  5026. timeout_sec, 0
  5027. };
  5028. request.ar_name = node;
  5029. request.ar_service = service;
  5030. request.ar_request = hints;
  5031. sevp.sigev_notify = SIGEV_NONE;
  5032. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5033. if (rc != 0) { return rc; }
  5034. auto cleanup = scope_exit([&] {
  5035. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5036. });
  5037. int wait_result = gai_suspend(requests, 1, &timeout);
  5038. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5039. int gai_result = gai_error(&request);
  5040. if (gai_result == 0) {
  5041. *res = request.ar_result;
  5042. request.ar_result = nullptr;
  5043. return 0;
  5044. }
  5045. return gai_result;
  5046. }
  5047. gai_cancel(&request);
  5048. while (gai_error(&request) == EAI_INPROGRESS) {
  5049. gai_suspend(requests, 1, nullptr);
  5050. }
  5051. return wait_result;
  5052. #else
  5053. // Fallback implementation using thread-based timeout for other Unix systems.
  5054. struct GetAddrInfoState {
  5055. ~GetAddrInfoState() {
  5056. if (info) { freeaddrinfo(info); }
  5057. }
  5058. std::mutex mutex;
  5059. std::condition_variable result_cv;
  5060. bool completed = false;
  5061. int result = EAI_SYSTEM;
  5062. std::string node;
  5063. std::string service;
  5064. struct addrinfo hints;
  5065. struct addrinfo *info = nullptr;
  5066. };
  5067. // Allocate on the heap, so the resolver thread can keep using the data.
  5068. auto state = std::make_shared<GetAddrInfoState>();
  5069. if (node) { state->node = node; }
  5070. state->service = service;
  5071. state->hints = *hints;
  5072. std::thread resolve_thread([state]() {
  5073. auto thread_result =
  5074. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5075. &state->info);
  5076. std::lock_guard<std::mutex> lock(state->mutex);
  5077. state->result = thread_result;
  5078. state->completed = true;
  5079. state->result_cv.notify_one();
  5080. });
  5081. // Wait for completion or timeout
  5082. std::unique_lock<std::mutex> lock(state->mutex);
  5083. auto finished =
  5084. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5085. [&] { return state->completed; });
  5086. if (finished) {
  5087. // Operation completed within timeout
  5088. resolve_thread.join();
  5089. *res = state->info;
  5090. state->info = nullptr; // Pass ownership to caller
  5091. return state->result;
  5092. } else {
  5093. // Timeout occurred
  5094. resolve_thread.detach(); // Let the thread finish in background
  5095. return EAI_AGAIN; // Return timeout error
  5096. }
  5097. #endif
  5098. #else
  5099. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5100. return getaddrinfo(node, service, hints, res);
  5101. #endif
  5102. }
  5103. template <typename BindOrConnect>
  5104. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5105. int address_family, int socket_flags, bool tcp_nodelay,
  5106. bool ipv6_v6only, SocketOptions socket_options,
  5107. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5108. // Get address info
  5109. const char *node = nullptr;
  5110. struct addrinfo hints;
  5111. struct addrinfo *result;
  5112. memset(&hints, 0, sizeof(struct addrinfo));
  5113. hints.ai_socktype = SOCK_STREAM;
  5114. hints.ai_protocol = IPPROTO_IP;
  5115. if (!ip.empty()) {
  5116. node = ip.c_str();
  5117. // Ask getaddrinfo to convert IP in c-string to address
  5118. hints.ai_family = AF_UNSPEC;
  5119. hints.ai_flags = AI_NUMERICHOST;
  5120. } else {
  5121. if (!host.empty()) { node = host.c_str(); }
  5122. hints.ai_family = address_family;
  5123. hints.ai_flags = socket_flags;
  5124. }
  5125. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5126. if (hints.ai_family == AF_UNIX) {
  5127. const auto addrlen = host.length();
  5128. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5129. #ifdef SOCK_CLOEXEC
  5130. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5131. hints.ai_protocol);
  5132. #else
  5133. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5134. #endif
  5135. if (sock != INVALID_SOCKET) {
  5136. sockaddr_un addr{};
  5137. addr.sun_family = AF_UNIX;
  5138. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5139. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5140. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5141. hints.ai_addrlen = static_cast<socklen_t>(
  5142. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5143. #ifndef SOCK_CLOEXEC
  5144. #ifndef _WIN32
  5145. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5146. #endif
  5147. #endif
  5148. if (socket_options) { socket_options(sock); }
  5149. #ifdef _WIN32
  5150. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5151. // remove the option.
  5152. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5153. #endif
  5154. bool dummy;
  5155. if (!bind_or_connect(sock, hints, dummy)) {
  5156. close_socket(sock);
  5157. sock = INVALID_SOCKET;
  5158. }
  5159. }
  5160. return sock;
  5161. }
  5162. #endif
  5163. auto service = std::to_string(port);
  5164. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5165. timeout_sec)) {
  5166. #if defined __linux__ && !defined __ANDROID__
  5167. res_init();
  5168. #endif
  5169. return INVALID_SOCKET;
  5170. }
  5171. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5172. for (auto rp = result; rp; rp = rp->ai_next) {
  5173. // Create a socket
  5174. #ifdef _WIN32
  5175. auto sock =
  5176. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5177. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5178. /**
  5179. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5180. * and above the socket creation fails on older Windows Systems.
  5181. *
  5182. * Let's try to create a socket the old way in this case.
  5183. *
  5184. * Reference:
  5185. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5186. *
  5187. * WSA_FLAG_NO_HANDLE_INHERIT:
  5188. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5189. * SP1, and later
  5190. *
  5191. */
  5192. if (sock == INVALID_SOCKET) {
  5193. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5194. }
  5195. #else
  5196. #ifdef SOCK_CLOEXEC
  5197. auto sock =
  5198. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5199. #else
  5200. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5201. #endif
  5202. #endif
  5203. if (sock == INVALID_SOCKET) { continue; }
  5204. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5205. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5206. close_socket(sock);
  5207. continue;
  5208. }
  5209. #endif
  5210. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5211. if (rp->ai_family == AF_INET6) {
  5212. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5213. }
  5214. if (socket_options) { socket_options(sock); }
  5215. // bind or connect
  5216. auto quit = false;
  5217. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5218. close_socket(sock);
  5219. if (quit) { break; }
  5220. }
  5221. return INVALID_SOCKET;
  5222. }
  5223. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5224. #ifdef _WIN32
  5225. auto flags = nonblocking ? 1UL : 0UL;
  5226. ioctlsocket(sock, FIONBIO, &flags);
  5227. #else
  5228. auto flags = fcntl(sock, F_GETFL, 0);
  5229. fcntl(sock, F_SETFL,
  5230. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5231. #endif
  5232. }
  5233. inline bool is_connection_error() {
  5234. #ifdef _WIN32
  5235. return WSAGetLastError() != WSAEWOULDBLOCK;
  5236. #else
  5237. return errno != EINPROGRESS;
  5238. #endif
  5239. }
  5240. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5241. struct addrinfo hints;
  5242. struct addrinfo *result;
  5243. memset(&hints, 0, sizeof(struct addrinfo));
  5244. hints.ai_family = AF_UNSPEC;
  5245. hints.ai_socktype = SOCK_STREAM;
  5246. hints.ai_protocol = 0;
  5247. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5248. return false;
  5249. }
  5250. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5251. auto ret = false;
  5252. for (auto rp = result; rp; rp = rp->ai_next) {
  5253. const auto &ai = *rp;
  5254. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5255. ret = true;
  5256. break;
  5257. }
  5258. }
  5259. return ret;
  5260. }
  5261. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5262. #define USE_IF2IP
  5263. #endif
  5264. #ifdef USE_IF2IP
  5265. inline std::string if2ip(int address_family, const std::string &ifn) {
  5266. struct ifaddrs *ifap;
  5267. getifaddrs(&ifap);
  5268. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5269. std::string addr_candidate;
  5270. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5271. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5272. (AF_UNSPEC == address_family ||
  5273. ifa->ifa_addr->sa_family == address_family)) {
  5274. if (ifa->ifa_addr->sa_family == AF_INET) {
  5275. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5276. char buf[INET_ADDRSTRLEN];
  5277. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5278. return std::string(buf, INET_ADDRSTRLEN);
  5279. }
  5280. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5281. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5282. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5283. char buf[INET6_ADDRSTRLEN] = {};
  5284. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5285. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5286. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5287. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5288. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5289. } else {
  5290. return std::string(buf, INET6_ADDRSTRLEN);
  5291. }
  5292. }
  5293. }
  5294. }
  5295. }
  5296. }
  5297. return addr_candidate;
  5298. }
  5299. #endif
  5300. inline socket_t create_client_socket(
  5301. const std::string &host, const std::string &ip, int port,
  5302. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5303. SocketOptions socket_options, time_t connection_timeout_sec,
  5304. time_t connection_timeout_usec, time_t read_timeout_sec,
  5305. time_t read_timeout_usec, time_t write_timeout_sec,
  5306. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5307. auto sock = create_socket(
  5308. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5309. std::move(socket_options),
  5310. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5311. if (!intf.empty()) {
  5312. #ifdef USE_IF2IP
  5313. auto ip_from_if = if2ip(address_family, intf);
  5314. if (ip_from_if.empty()) { ip_from_if = intf; }
  5315. if (!bind_ip_address(sock2, ip_from_if)) {
  5316. error = Error::BindIPAddress;
  5317. return false;
  5318. }
  5319. #endif
  5320. }
  5321. set_nonblocking(sock2, true);
  5322. auto ret =
  5323. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5324. if (ret < 0) {
  5325. if (is_connection_error()) {
  5326. error = Error::Connection;
  5327. return false;
  5328. }
  5329. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5330. connection_timeout_usec);
  5331. if (error != Error::Success) {
  5332. if (error == Error::ConnectionTimeout) { quit = true; }
  5333. return false;
  5334. }
  5335. }
  5336. set_nonblocking(sock2, false);
  5337. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5338. read_timeout_usec);
  5339. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5340. write_timeout_usec);
  5341. error = Error::Success;
  5342. return true;
  5343. },
  5344. connection_timeout_sec); // Pass DNS timeout
  5345. if (sock != INVALID_SOCKET) {
  5346. error = Error::Success;
  5347. } else {
  5348. if (error == Error::Success) { error = Error::Connection; }
  5349. }
  5350. return sock;
  5351. }
  5352. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5353. socklen_t addr_len, std::string &ip, int &port) {
  5354. if (addr.ss_family == AF_INET) {
  5355. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5356. } else if (addr.ss_family == AF_INET6) {
  5357. port =
  5358. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5359. } else {
  5360. return false;
  5361. }
  5362. std::array<char, NI_MAXHOST> ipstr{};
  5363. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5364. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5365. 0, NI_NUMERICHOST)) {
  5366. return false;
  5367. }
  5368. ip = ipstr.data();
  5369. return true;
  5370. }
  5371. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5372. struct sockaddr_storage addr;
  5373. socklen_t addr_len = sizeof(addr);
  5374. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5375. &addr_len)) {
  5376. get_ip_and_port(addr, addr_len, ip, port);
  5377. }
  5378. }
  5379. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5380. struct sockaddr_storage addr;
  5381. socklen_t addr_len = sizeof(addr);
  5382. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5383. &addr_len)) {
  5384. #ifndef _WIN32
  5385. if (addr.ss_family == AF_UNIX) {
  5386. #if defined(__linux__)
  5387. struct ucred ucred;
  5388. socklen_t len = sizeof(ucred);
  5389. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5390. port = ucred.pid;
  5391. }
  5392. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5393. pid_t pid;
  5394. socklen_t len = sizeof(pid);
  5395. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5396. port = pid;
  5397. }
  5398. #endif
  5399. return;
  5400. }
  5401. #endif
  5402. get_ip_and_port(addr, addr_len, ip, port);
  5403. }
  5404. }
  5405. // Recursive form retained so operator""_t below can compute hashes for
  5406. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5407. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5408. // instead, which is iterative and stack-safe.
  5409. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5410. unsigned int h) {
  5411. return (l == 0)
  5412. ? h
  5413. : str2tag_core(
  5414. s + 1, l - 1,
  5415. // Unsets the 6 high bits of h, therefore no overflow happens
  5416. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5417. h * 33) ^
  5418. static_cast<unsigned char>(*s));
  5419. }
  5420. inline unsigned int str2tag(const std::string &s) {
  5421. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5422. // for compile-time UDL evaluation of short string literals, but at runtime
  5423. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5424. // would blow the stack with one frame per character.
  5425. unsigned int h = 0;
  5426. for (auto c : s) {
  5427. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5428. static_cast<unsigned char>(c);
  5429. }
  5430. return h;
  5431. }
  5432. namespace udl {
  5433. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5434. return str2tag_core(s, l, 0);
  5435. }
  5436. } // namespace udl
  5437. inline std::string
  5438. find_content_type(const std::string &path,
  5439. const std::map<std::string, std::string> &user_data,
  5440. const std::string &default_content_type) {
  5441. auto ext = file_extension(path);
  5442. auto it = user_data.find(ext);
  5443. if (it != user_data.end()) { return it->second; }
  5444. using udl::operator""_t;
  5445. switch (str2tag(ext)) {
  5446. default: return default_content_type;
  5447. case "css"_t: return "text/css";
  5448. case "csv"_t: return "text/csv";
  5449. case "htm"_t:
  5450. case "html"_t: return "text/html";
  5451. case "js"_t:
  5452. case "mjs"_t: return "text/javascript";
  5453. case "txt"_t: return "text/plain";
  5454. case "vtt"_t: return "text/vtt";
  5455. case "apng"_t: return "image/apng";
  5456. case "avif"_t: return "image/avif";
  5457. case "bmp"_t: return "image/bmp";
  5458. case "gif"_t: return "image/gif";
  5459. case "png"_t: return "image/png";
  5460. case "svg"_t: return "image/svg+xml";
  5461. case "webp"_t: return "image/webp";
  5462. case "ico"_t: return "image/x-icon";
  5463. case "tif"_t: return "image/tiff";
  5464. case "tiff"_t: return "image/tiff";
  5465. case "jpg"_t:
  5466. case "jpeg"_t: return "image/jpeg";
  5467. case "mp4"_t: return "video/mp4";
  5468. case "mpeg"_t: return "video/mpeg";
  5469. case "webm"_t: return "video/webm";
  5470. case "mp3"_t: return "audio/mp3";
  5471. case "mpga"_t: return "audio/mpeg";
  5472. case "weba"_t: return "audio/webm";
  5473. case "wav"_t: return "audio/wave";
  5474. case "otf"_t: return "font/otf";
  5475. case "ttf"_t: return "font/ttf";
  5476. case "woff"_t: return "font/woff";
  5477. case "woff2"_t: return "font/woff2";
  5478. case "7z"_t: return "application/x-7z-compressed";
  5479. case "atom"_t: return "application/atom+xml";
  5480. case "pdf"_t: return "application/pdf";
  5481. case "json"_t: return "application/json";
  5482. case "rss"_t: return "application/rss+xml";
  5483. case "tar"_t: return "application/x-tar";
  5484. case "xht"_t:
  5485. case "xhtml"_t: return "application/xhtml+xml";
  5486. case "xslt"_t: return "application/xslt+xml";
  5487. case "xml"_t: return "application/xml";
  5488. case "gz"_t: return "application/gzip";
  5489. case "zip"_t: return "application/zip";
  5490. case "wasm"_t: return "application/wasm";
  5491. }
  5492. }
  5493. inline std::string
  5494. extract_media_type(const std::string &content_type,
  5495. std::map<std::string, std::string> *params = nullptr) {
  5496. // Extract type/subtype from Content-Type value (RFC 2045)
  5497. // e.g. "application/json; charset=utf-8" -> "application/json"
  5498. auto media_type = content_type;
  5499. auto semicolon_pos = media_type.find(';');
  5500. if (semicolon_pos != std::string::npos) {
  5501. auto param_str = media_type.substr(semicolon_pos + 1);
  5502. media_type = media_type.substr(0, semicolon_pos);
  5503. if (params) {
  5504. // Parse parameters: key=value pairs separated by ';'
  5505. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5506. [&](const char *b, const char *e) {
  5507. std::string key;
  5508. std::string val;
  5509. split(b, e, '=', [&](const char *b2, const char *e2) {
  5510. if (key.empty()) {
  5511. key.assign(b2, e2);
  5512. } else {
  5513. val.assign(b2, e2);
  5514. }
  5515. });
  5516. if (!key.empty()) {
  5517. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5518. }
  5519. });
  5520. }
  5521. }
  5522. // Trim whitespace from media type
  5523. return trim_copy(media_type);
  5524. }
  5525. inline bool can_compress_content_type(const std::string &content_type) {
  5526. using udl::operator""_t;
  5527. auto mime_type = extract_media_type(content_type);
  5528. auto tag = str2tag(mime_type);
  5529. switch (tag) {
  5530. case "image/svg+xml"_t:
  5531. case "application/javascript"_t:
  5532. case "application/x-javascript"_t:
  5533. case "application/json"_t:
  5534. case "application/ld+json"_t:
  5535. case "application/xml"_t:
  5536. case "application/xhtml+xml"_t:
  5537. case "application/rss+xml"_t:
  5538. case "application/atom+xml"_t:
  5539. case "application/xslt+xml"_t:
  5540. case "application/protobuf"_t: return true;
  5541. case "text/event-stream"_t: return false;
  5542. default: return !mime_type.rfind("text/", 0);
  5543. }
  5544. }
  5545. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5546. double &quality) {
  5547. quality = 1.0;
  5548. token.clear();
  5549. // Split on first ';': left = token name, right = parameters
  5550. const char *params_b = nullptr;
  5551. std::size_t params_len = 0;
  5552. divide(
  5553. b, static_cast<std::size_t>(e - b), ';',
  5554. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5555. auto r = trim(lb, lb + llen, 0, llen);
  5556. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5557. params_b = rb;
  5558. params_len = rlen;
  5559. });
  5560. if (token.empty()) { return false; }
  5561. if (params_len == 0) { return true; }
  5562. // Scan parameters for q= (stops on first match)
  5563. bool invalid = false;
  5564. split_find(params_b, params_b + params_len, ';',
  5565. (std::numeric_limits<size_t>::max)(),
  5566. [&](const char *pb, const char *pe) -> bool {
  5567. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5568. auto len = static_cast<size_t>(pe - pb);
  5569. if (len < 2) { return false; }
  5570. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5571. return false;
  5572. }
  5573. // Trim the value portion
  5574. auto r = trim(pb, pe, 2, len);
  5575. if (r.first >= r.second) {
  5576. invalid = true;
  5577. return true;
  5578. }
  5579. double v = 0.0;
  5580. auto res = from_chars(pb + r.first, pb + r.second, v);
  5581. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5582. invalid = true;
  5583. return true;
  5584. }
  5585. quality = v;
  5586. return true;
  5587. });
  5588. return !invalid;
  5589. }
  5590. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5591. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5592. return EncodingType::None;
  5593. }
  5594. const auto &s = req.get_header_value("Accept-Encoding");
  5595. if (s.empty()) { return EncodingType::None; }
  5596. // Single-pass: iterate tokens and track the best supported encoding.
  5597. // Server preference breaks ties (br > gzip > zstd).
  5598. EncodingType best = EncodingType::None;
  5599. double best_q = 0.0; // q=0 means "not acceptable"
  5600. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5601. auto priority = [](EncodingType t) -> int {
  5602. switch (t) {
  5603. case EncodingType::Brotli: return 0;
  5604. case EncodingType::Gzip: return 1;
  5605. case EncodingType::Zstd: return 2;
  5606. default: return 3;
  5607. }
  5608. };
  5609. std::string name;
  5610. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5611. double quality = 1.0;
  5612. if (!parse_quality(b, e, name, quality)) { return; }
  5613. if (quality <= 0.0) { return; }
  5614. EncodingType type = EncodingType::None;
  5615. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5616. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5617. #endif
  5618. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5619. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5620. type = EncodingType::Gzip;
  5621. }
  5622. #endif
  5623. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5624. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5625. type = EncodingType::Zstd;
  5626. }
  5627. #endif
  5628. if (type == EncodingType::None) { return; }
  5629. // Higher q-value wins; for equal q, server preference breaks ties
  5630. if (quality > best_q ||
  5631. (quality == best_q && priority(type) < priority(best))) {
  5632. best_q = quality;
  5633. best = type;
  5634. }
  5635. });
  5636. return best;
  5637. }
  5638. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5639. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5640. if (type == EncodingType::Gzip) {
  5641. return detail::make_unique<gzip_compressor>();
  5642. }
  5643. #endif
  5644. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5645. if (type == EncodingType::Brotli) {
  5646. return detail::make_unique<brotli_compressor>();
  5647. }
  5648. #endif
  5649. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5650. if (type == EncodingType::Zstd) {
  5651. return detail::make_unique<zstd_compressor>();
  5652. }
  5653. #endif
  5654. (void)type;
  5655. return nullptr;
  5656. }
  5657. inline const char *encoding_name(EncodingType type) {
  5658. switch (type) {
  5659. case EncodingType::Gzip: return "gzip";
  5660. case EncodingType::Brotli: return "br";
  5661. case EncodingType::Zstd: return "zstd";
  5662. default: return "";
  5663. }
  5664. }
  5665. inline bool nocompressor::compress(const char *data, size_t data_length,
  5666. bool /*last*/, Callback callback) {
  5667. if (!data_length) { return true; }
  5668. return callback(data, data_length);
  5669. }
  5670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5671. inline gzip_compressor::gzip_compressor() {
  5672. std::memset(&strm_, 0, sizeof(strm_));
  5673. strm_.zalloc = Z_NULL;
  5674. strm_.zfree = Z_NULL;
  5675. strm_.opaque = Z_NULL;
  5676. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5677. Z_DEFAULT_STRATEGY) == Z_OK;
  5678. }
  5679. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5680. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5681. bool last, Callback callback) {
  5682. assert(is_valid_);
  5683. do {
  5684. constexpr size_t max_avail_in =
  5685. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5686. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5687. (std::min)(data_length, max_avail_in));
  5688. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5689. data_length -= strm_.avail_in;
  5690. data += strm_.avail_in;
  5691. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5692. auto ret = Z_OK;
  5693. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5694. do {
  5695. strm_.avail_out = static_cast<uInt>(buff.size());
  5696. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5697. ret = deflate(&strm_, flush);
  5698. if (ret == Z_STREAM_ERROR) { return false; }
  5699. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5700. return false;
  5701. }
  5702. } while (strm_.avail_out == 0);
  5703. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5704. (flush == Z_NO_FLUSH && ret == Z_OK));
  5705. assert(strm_.avail_in == 0);
  5706. } while (data_length > 0);
  5707. return true;
  5708. }
  5709. inline gzip_decompressor::gzip_decompressor() {
  5710. std::memset(&strm_, 0, sizeof(strm_));
  5711. strm_.zalloc = Z_NULL;
  5712. strm_.zfree = Z_NULL;
  5713. strm_.opaque = Z_NULL;
  5714. // 15 is the value of wbits, which should be at the maximum possible value
  5715. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5716. // that the stream type should be automatically detected either gzip or
  5717. // deflate.
  5718. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5719. }
  5720. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5721. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5722. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5723. Callback callback) {
  5724. assert(is_valid_);
  5725. auto ret = Z_OK;
  5726. do {
  5727. constexpr size_t max_avail_in =
  5728. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5729. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5730. (std::min)(data_length, max_avail_in));
  5731. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5732. data_length -= strm_.avail_in;
  5733. data += strm_.avail_in;
  5734. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5735. while (strm_.avail_in > 0 && ret == Z_OK) {
  5736. strm_.avail_out = static_cast<uInt>(buff.size());
  5737. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5738. ret = inflate(&strm_, Z_NO_FLUSH);
  5739. assert(ret != Z_STREAM_ERROR);
  5740. switch (ret) {
  5741. case Z_NEED_DICT:
  5742. case Z_DATA_ERROR:
  5743. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5744. }
  5745. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5746. return false;
  5747. }
  5748. }
  5749. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5750. } while (data_length > 0);
  5751. return true;
  5752. }
  5753. #endif
  5754. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5755. inline brotli_compressor::brotli_compressor() {
  5756. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5757. }
  5758. inline brotli_compressor::~brotli_compressor() {
  5759. BrotliEncoderDestroyInstance(state_);
  5760. }
  5761. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5762. bool last, Callback callback) {
  5763. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5764. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5765. auto available_in = data_length;
  5766. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5767. for (;;) {
  5768. if (last) {
  5769. if (BrotliEncoderIsFinished(state_)) { break; }
  5770. } else {
  5771. if (!available_in) { break; }
  5772. }
  5773. auto available_out = buff.size();
  5774. auto next_out = buff.data();
  5775. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5776. &available_out, &next_out, nullptr)) {
  5777. return false;
  5778. }
  5779. auto output_bytes = buff.size() - available_out;
  5780. if (output_bytes) {
  5781. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5782. }
  5783. }
  5784. return true;
  5785. }
  5786. inline brotli_decompressor::brotli_decompressor() {
  5787. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5788. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5789. : BROTLI_DECODER_RESULT_ERROR;
  5790. }
  5791. inline brotli_decompressor::~brotli_decompressor() {
  5792. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5793. }
  5794. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5795. inline bool brotli_decompressor::decompress(const char *data,
  5796. size_t data_length,
  5797. Callback callback) {
  5798. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5799. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5800. return 0;
  5801. }
  5802. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5803. size_t avail_in = data_length;
  5804. size_t total_out;
  5805. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5806. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5807. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5808. char *next_out = buff.data();
  5809. size_t avail_out = buff.size();
  5810. decoder_r = BrotliDecoderDecompressStream(
  5811. decoder_s, &avail_in, &next_in, &avail_out,
  5812. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5813. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5814. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5815. }
  5816. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5817. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5818. }
  5819. #endif
  5820. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5821. inline zstd_compressor::zstd_compressor() {
  5822. ctx_ = ZSTD_createCCtx();
  5823. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5824. }
  5825. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5826. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5827. bool last, Callback callback) {
  5828. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5829. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5830. ZSTD_inBuffer input = {data, data_length, 0};
  5831. bool finished;
  5832. do {
  5833. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5834. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5835. if (ZSTD_isError(remaining)) { return false; }
  5836. if (!callback(buff.data(), output.pos)) { return false; }
  5837. finished = last ? (remaining == 0) : (input.pos == input.size);
  5838. } while (!finished);
  5839. return true;
  5840. }
  5841. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5842. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5843. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5844. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5845. Callback callback) {
  5846. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5847. ZSTD_inBuffer input = {data, data_length, 0};
  5848. while (input.pos < input.size) {
  5849. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5850. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5851. if (ZSTD_isError(remaining)) { return false; }
  5852. if (!callback(buff.data(), output.pos)) { return false; }
  5853. }
  5854. return true;
  5855. }
  5856. #endif
  5857. inline std::unique_ptr<decompressor>
  5858. create_decompressor(const std::string &encoding) {
  5859. std::unique_ptr<decompressor> decompressor;
  5860. if (encoding == "gzip" || encoding == "deflate") {
  5861. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5862. decompressor = detail::make_unique<gzip_decompressor>();
  5863. #endif
  5864. } else if (encoding.find("br") != std::string::npos) {
  5865. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5866. decompressor = detail::make_unique<brotli_decompressor>();
  5867. #endif
  5868. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5869. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5870. decompressor = detail::make_unique<zstd_decompressor>();
  5871. #endif
  5872. }
  5873. return decompressor;
  5874. }
  5875. // Returns the best available compressor and its Content-Encoding name.
  5876. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5877. inline std::pair<std::unique_ptr<compressor>, const char *>
  5878. create_compressor() {
  5879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5880. return {detail::make_unique<brotli_compressor>(), "br"};
  5881. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5882. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5883. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5884. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5885. #else
  5886. return {nullptr, nullptr};
  5887. #endif
  5888. }
  5889. inline bool is_prohibited_header_name(const std::string &name) {
  5890. using udl::operator""_t;
  5891. switch (str2tag(name)) {
  5892. case "REMOTE_ADDR"_t:
  5893. case "REMOTE_PORT"_t:
  5894. case "LOCAL_ADDR"_t:
  5895. case "LOCAL_PORT"_t: return true;
  5896. default: return false;
  5897. }
  5898. }
  5899. inline bool has_header(const Headers &headers, const std::string &key) {
  5900. if (is_prohibited_header_name(key)) { return false; }
  5901. return headers.find(key) != headers.end();
  5902. }
  5903. inline const char *get_header_value(const Headers &headers,
  5904. const std::string &key, const char *def,
  5905. size_t id) {
  5906. if (is_prohibited_header_name(key)) {
  5907. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5908. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5909. throw std::invalid_argument(msg);
  5910. #else
  5911. return "";
  5912. #endif
  5913. }
  5914. auto rng = headers.equal_range(key);
  5915. auto it = rng.first;
  5916. std::advance(it, static_cast<ssize_t>(id));
  5917. if (it != rng.second) { return it->second.c_str(); }
  5918. return def;
  5919. }
  5920. inline size_t get_header_value_count(const Headers &headers,
  5921. const std::string &key) {
  5922. auto r = headers.equal_range(key);
  5923. return static_cast<size_t>(std::distance(r.first, r.second));
  5924. }
  5925. template <typename Map>
  5926. inline typename Map::mapped_type
  5927. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5928. auto rng = m.equal_range(key);
  5929. auto it = rng.first;
  5930. std::advance(it, static_cast<ssize_t>(id));
  5931. if (it != rng.second) { return it->second; }
  5932. return typename Map::mapped_type();
  5933. }
  5934. inline void set_header(Headers &headers, const std::string &key,
  5935. const std::string &val) {
  5936. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5937. headers.emplace(key, val);
  5938. }
  5939. }
  5940. inline bool read_headers(Stream &strm, Headers &headers) {
  5941. const auto bufsiz = 2048;
  5942. char buf[bufsiz];
  5943. stream_line_reader line_reader(strm, buf, bufsiz);
  5944. size_t header_count = 0;
  5945. for (;;) {
  5946. if (!line_reader.getline()) { return false; }
  5947. // Check if the line ends with CRLF.
  5948. auto line_terminator_len = 2;
  5949. if (line_reader.end_with_crlf()) {
  5950. // Blank line indicates end of headers.
  5951. if (line_reader.size() == 2) { break; }
  5952. } else {
  5953. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5954. // Blank line indicates end of headers.
  5955. if (line_reader.size() == 1) { break; }
  5956. line_terminator_len = 1;
  5957. #else
  5958. continue; // Skip invalid line.
  5959. #endif
  5960. }
  5961. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5962. // Check header count limit
  5963. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5964. // Exclude line terminator
  5965. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5966. if (!parse_header(line_reader.ptr(), end,
  5967. [&](const std::string &key, const std::string &val) {
  5968. headers.emplace(key, val);
  5969. })) {
  5970. return false;
  5971. }
  5972. header_count++;
  5973. }
  5974. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5975. // headers that have different values to prevent request smuggling.
  5976. auto cl_range = headers.equal_range("Content-Length");
  5977. if (cl_range.first != cl_range.second) {
  5978. const auto &first_val = cl_range.first->second;
  5979. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5980. if (it->second != first_val) { return false; }
  5981. }
  5982. }
  5983. return true;
  5984. }
  5985. inline bool read_websocket_upgrade_response(Stream &strm,
  5986. const std::string &expected_accept,
  5987. std::string &selected_subprotocol) {
  5988. // Read status line
  5989. const auto bufsiz = 2048;
  5990. char buf[bufsiz];
  5991. stream_line_reader line_reader(strm, buf, bufsiz);
  5992. if (!line_reader.getline()) { return false; }
  5993. // Check for "HTTP/1.1 101"
  5994. auto line = std::string(line_reader.ptr(), line_reader.size());
  5995. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5996. // Parse headers using existing read_headers
  5997. Headers headers;
  5998. if (!read_headers(strm, headers)) { return false; }
  5999. // Verify Upgrade: websocket (case-insensitive)
  6000. auto upgrade_it = headers.find("Upgrade");
  6001. if (upgrade_it == headers.end()) { return false; }
  6002. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6003. if (upgrade_val != "websocket") { return false; }
  6004. // Verify Connection header contains "Upgrade" (case-insensitive)
  6005. auto connection_it = headers.find("Connection");
  6006. if (connection_it == headers.end()) { return false; }
  6007. auto connection_val = case_ignore::to_lower(connection_it->second);
  6008. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6009. // Verify Sec-WebSocket-Accept header value
  6010. auto it = headers.find("Sec-WebSocket-Accept");
  6011. if (it == headers.end() || it->second != expected_accept) { return false; }
  6012. // Extract negotiated subprotocol
  6013. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6014. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6015. return true;
  6016. }
  6017. enum class ReadContentResult {
  6018. Success, // Successfully read the content
  6019. PayloadTooLarge, // The content exceeds the specified payload limit
  6020. Error // An error occurred while reading the content
  6021. };
  6022. inline ReadContentResult read_content_with_length(
  6023. Stream &strm, size_t len, DownloadProgress progress,
  6024. ContentReceiverWithProgress out,
  6025. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6026. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6027. detail::BodyReader br;
  6028. br.stream = &strm;
  6029. br.has_content_length = true;
  6030. br.content_length = len;
  6031. br.payload_max_length = payload_max_length;
  6032. br.chunked = false;
  6033. br.bytes_read = 0;
  6034. br.last_error = Error::Success;
  6035. size_t r = 0;
  6036. while (r < len) {
  6037. auto read_len = static_cast<size_t>(len - r);
  6038. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6039. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6040. if (n <= 0) {
  6041. // Check if it was a payload size error
  6042. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6043. return ReadContentResult::PayloadTooLarge;
  6044. }
  6045. return ReadContentResult::Error;
  6046. }
  6047. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6048. return ReadContentResult::Error;
  6049. }
  6050. r += static_cast<size_t>(n);
  6051. if (progress) {
  6052. if (!progress(r, len)) { return ReadContentResult::Error; }
  6053. }
  6054. }
  6055. return ReadContentResult::Success;
  6056. }
  6057. inline ReadContentResult
  6058. read_content_without_length(Stream &strm, size_t payload_max_length,
  6059. ContentReceiverWithProgress out) {
  6060. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6061. size_t r = 0;
  6062. for (;;) {
  6063. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6064. if (n == 0) { return ReadContentResult::Success; }
  6065. if (n < 0) { return ReadContentResult::Error; }
  6066. // Check if adding this data would exceed the payload limit
  6067. if (r > payload_max_length ||
  6068. payload_max_length - r < static_cast<size_t>(n)) {
  6069. return ReadContentResult::PayloadTooLarge;
  6070. }
  6071. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6072. return ReadContentResult::Error;
  6073. }
  6074. r += static_cast<size_t>(n);
  6075. }
  6076. return ReadContentResult::Success;
  6077. }
  6078. template <typename T>
  6079. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6080. size_t payload_max_length,
  6081. ContentReceiverWithProgress out) {
  6082. detail::ChunkedDecoder dec(strm);
  6083. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6084. size_t total_len = 0;
  6085. for (;;) {
  6086. size_t chunk_offset = 0;
  6087. size_t chunk_total = 0;
  6088. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6089. if (n < 0) { return ReadContentResult::Error; }
  6090. if (n == 0) {
  6091. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6092. return ReadContentResult::Error;
  6093. }
  6094. return ReadContentResult::Success;
  6095. }
  6096. if (total_len > payload_max_length ||
  6097. payload_max_length - total_len < static_cast<size_t>(n)) {
  6098. return ReadContentResult::PayloadTooLarge;
  6099. }
  6100. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6101. return ReadContentResult::Error;
  6102. }
  6103. total_len += static_cast<size_t>(n);
  6104. }
  6105. }
  6106. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6107. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6108. // is the final transfer coding. A single field value may list several
  6109. // codings ("gzip, chunked"), and the list may be split across multiple
  6110. // Transfer-Encoding header lines (RFC 9110 5.3). Match the last coding token
  6111. // case-insensitively rather than comparing the whole value against "chunked".
  6112. //
  6113. // Security: reading a chunked message as unframed leaves its body in the
  6114. // socket, where a keep-alive connection parses it as a smuggled request.
  6115. // Headers is an unordered_multimap whose iteration order for duplicate keys
  6116. // is not portable, so when there is more than one Transfer-Encoding line we
  6117. // cannot tell which coding is truly final. In that ambiguous case we fail
  6118. // safe by treating the message as chunked (a mis-parse just closes the
  6119. // connection, whereas the opposite error enables smuggling).
  6120. auto rng = headers.equal_range("Transfer-Encoding");
  6121. size_t line_count = 0;
  6122. bool chunked_present = false;
  6123. bool last_line_ends_with_chunked = false;
  6124. for (auto it = rng.first; it != rng.second; ++it) {
  6125. line_count++;
  6126. const auto &value = it->second;
  6127. std::string last_coding;
  6128. bool line_has_chunked = false;
  6129. split(value.data(), value.data() + value.size(), ',',
  6130. [&](const char *b, const char *e) {
  6131. last_coding.assign(b, e);
  6132. if (case_ignore::equal(last_coding, "chunked")) {
  6133. line_has_chunked = true;
  6134. }
  6135. });
  6136. if (line_has_chunked) { chunked_present = true; }
  6137. last_line_ends_with_chunked = case_ignore::equal(last_coding, "chunked");
  6138. }
  6139. if (line_count == 0) { return false; }
  6140. if (line_count == 1) { return last_line_ends_with_chunked; }
  6141. return chunked_present;
  6142. }
  6143. template <typename T, typename U>
  6144. bool prepare_content_receiver(T &x, int &status,
  6145. ContentReceiverWithProgress receiver,
  6146. bool decompress, size_t payload_max_length,
  6147. bool &exceed_payload_max_length, U callback) {
  6148. if (decompress) {
  6149. std::string encoding = x.get_header_value("Content-Encoding");
  6150. std::unique_ptr<decompressor> decompressor;
  6151. if (!encoding.empty()) {
  6152. decompressor = detail::create_decompressor(encoding);
  6153. if (!decompressor) {
  6154. // Unsupported encoding or no support compiled in
  6155. status = StatusCode::UnsupportedMediaType_415;
  6156. return false;
  6157. }
  6158. }
  6159. if (decompressor) {
  6160. if (decompressor->is_valid()) {
  6161. size_t decompressed_size = 0;
  6162. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6163. size_t off, size_t len) {
  6164. return decompressor->decompress(
  6165. buf, n, [&](const char *buf2, size_t n2) {
  6166. // Guard against zip-bomb: check
  6167. // decompressed size against limit.
  6168. if (payload_max_length > 0 &&
  6169. (decompressed_size >= payload_max_length ||
  6170. n2 > payload_max_length - decompressed_size)) {
  6171. exceed_payload_max_length = true;
  6172. return false;
  6173. }
  6174. decompressed_size += n2;
  6175. return receiver(buf2, n2, off, len);
  6176. });
  6177. };
  6178. return callback(std::move(out));
  6179. } else {
  6180. status = StatusCode::InternalServerError_500;
  6181. return false;
  6182. }
  6183. }
  6184. }
  6185. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6186. size_t len) {
  6187. return receiver(buf, n, off, len);
  6188. };
  6189. return callback(std::move(out));
  6190. }
  6191. template <typename T>
  6192. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6193. DownloadProgress progress,
  6194. ContentReceiverWithProgress receiver, bool decompress) {
  6195. bool exceed_payload_max_length = false;
  6196. return prepare_content_receiver(
  6197. x, status, std::move(receiver), decompress, payload_max_length,
  6198. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6199. auto ret = true;
  6200. // Note: exceed_payload_max_length may also be set by the decompressor
  6201. // wrapper in prepare_content_receiver when the decompressed payload
  6202. // size exceeds the limit.
  6203. if (is_chunked_transfer_encoding(x.headers)) {
  6204. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6205. if (result == ReadContentResult::Success) {
  6206. ret = true;
  6207. } else if (result == ReadContentResult::PayloadTooLarge) {
  6208. exceed_payload_max_length = true;
  6209. ret = false;
  6210. } else {
  6211. ret = false;
  6212. }
  6213. } else if (!has_header(x.headers, "Content-Length")) {
  6214. auto result =
  6215. read_content_without_length(strm, payload_max_length, out);
  6216. if (result == ReadContentResult::Success) {
  6217. ret = true;
  6218. } else if (result == ReadContentResult::PayloadTooLarge) {
  6219. exceed_payload_max_length = true;
  6220. ret = false;
  6221. } else {
  6222. ret = false;
  6223. }
  6224. } else {
  6225. auto is_invalid_value = false;
  6226. auto len = get_header_value_u64(x.headers, "Content-Length",
  6227. (std::numeric_limits<size_t>::max)(),
  6228. 0, is_invalid_value);
  6229. if (is_invalid_value) {
  6230. ret = false;
  6231. } else if (len > 0) {
  6232. auto result = read_content_with_length(
  6233. strm, len, std::move(progress), out, payload_max_length);
  6234. ret = (result == ReadContentResult::Success);
  6235. if (result == ReadContentResult::PayloadTooLarge) {
  6236. exceed_payload_max_length = true;
  6237. }
  6238. }
  6239. }
  6240. if (!ret) {
  6241. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6242. : StatusCode::BadRequest_400;
  6243. }
  6244. return ret;
  6245. });
  6246. }
  6247. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6248. const std::string &path) {
  6249. // A request target must not carry CR/LF (or other control octets); otherwise
  6250. // a value smuggled into it splits the request line and injects headers or a
  6251. // whole request. The same field-value check already guards header values in
  6252. // check_and_write_headers and the request target in
  6253. // perform_websocket_handshake; apply it here too.
  6254. if (!fields::is_field_value(path)) { return -1; }
  6255. std::string s = method;
  6256. s += ' ';
  6257. s += path;
  6258. s += " HTTP/1.1\r\n";
  6259. return strm.write(s.data(), s.size());
  6260. }
  6261. inline ssize_t write_response_line(Stream &strm, int status) {
  6262. std::string s = "HTTP/1.1 ";
  6263. s += std::to_string(status);
  6264. s += ' ';
  6265. s += httplib::status_message(status);
  6266. s += "\r\n";
  6267. return strm.write(s.data(), s.size());
  6268. }
  6269. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6270. ssize_t write_len = 0;
  6271. for (const auto &x : headers) {
  6272. std::string s;
  6273. s = x.first;
  6274. s += ": ";
  6275. s += x.second;
  6276. s += "\r\n";
  6277. auto len = strm.write(s.data(), s.size());
  6278. if (len < 0) { return len; }
  6279. write_len += len;
  6280. }
  6281. auto len = strm.write("\r\n");
  6282. if (len < 0) { return len; }
  6283. write_len += len;
  6284. return write_len;
  6285. }
  6286. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6287. size_t offset = 0;
  6288. while (offset < l) {
  6289. auto length = strm.write(d + offset, l - offset);
  6290. if (length < 0) { return false; }
  6291. offset += static_cast<size_t>(length);
  6292. }
  6293. return true;
  6294. }
  6295. template <typename T>
  6296. inline bool write_content_with_progress(Stream &strm,
  6297. const ContentProvider &content_provider,
  6298. size_t offset, size_t length,
  6299. T is_shutting_down,
  6300. const UploadProgress &upload_progress,
  6301. Error &error) {
  6302. size_t end_offset = offset + length;
  6303. size_t start_offset = offset;
  6304. auto ok = true;
  6305. DataSink data_sink;
  6306. data_sink.write = [&](const char *d, size_t l) -> bool {
  6307. if (ok) {
  6308. if (write_data(strm, d, l)) {
  6309. offset += l;
  6310. if (upload_progress && length > 0) {
  6311. size_t current_written = offset - start_offset;
  6312. if (!upload_progress(current_written, length)) {
  6313. ok = false;
  6314. return false;
  6315. }
  6316. }
  6317. } else {
  6318. ok = false;
  6319. }
  6320. }
  6321. return ok;
  6322. };
  6323. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6324. while (offset < end_offset && !is_shutting_down()) {
  6325. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6326. error = Error::Write;
  6327. return false;
  6328. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6329. error = Error::Canceled;
  6330. return false;
  6331. } else if (!ok) {
  6332. error = Error::Write;
  6333. return false;
  6334. }
  6335. }
  6336. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6337. error = Error::Write;
  6338. return false;
  6339. }
  6340. error = Error::Success;
  6341. return true;
  6342. }
  6343. template <typename T>
  6344. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6345. size_t offset, size_t length, T is_shutting_down,
  6346. Error &error) {
  6347. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6348. is_shutting_down, nullptr, error);
  6349. }
  6350. template <typename T>
  6351. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6352. size_t offset, size_t length,
  6353. const T &is_shutting_down) {
  6354. auto error = Error::Success;
  6355. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6356. error);
  6357. }
  6358. template <typename T>
  6359. inline bool
  6360. write_content_without_length(Stream &strm,
  6361. const ContentProvider &content_provider,
  6362. const T &is_shutting_down) {
  6363. size_t offset = 0;
  6364. auto data_available = true;
  6365. auto ok = true;
  6366. DataSink data_sink;
  6367. data_sink.write = [&](const char *d, size_t l) -> bool {
  6368. if (ok) {
  6369. offset += l;
  6370. if (!write_data(strm, d, l)) { ok = false; }
  6371. }
  6372. return ok;
  6373. };
  6374. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6375. data_sink.done = [&](void) { data_available = false; };
  6376. while (data_available && !is_shutting_down()) {
  6377. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6378. return false;
  6379. } else if (!content_provider(offset, 0, data_sink)) {
  6380. return false;
  6381. } else if (!ok) {
  6382. return false;
  6383. }
  6384. }
  6385. return !data_available; // true only if done() was called, false if shutting
  6386. // down
  6387. }
  6388. template <typename T, typename U>
  6389. inline bool
  6390. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6391. const T &is_shutting_down, U &compressor, Error &error) {
  6392. size_t offset = 0;
  6393. auto data_available = true;
  6394. auto ok = true;
  6395. DataSink data_sink;
  6396. data_sink.write = [&](const char *d, size_t l) -> bool {
  6397. if (ok) {
  6398. data_available = l > 0;
  6399. offset += l;
  6400. std::string payload;
  6401. if (compressor.compress(d, l, false,
  6402. [&](const char *data, size_t data_len) {
  6403. payload.append(data, data_len);
  6404. return true;
  6405. })) {
  6406. if (!payload.empty()) {
  6407. // Emit chunked response header and footer for each chunk
  6408. auto chunk =
  6409. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6410. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6411. }
  6412. } else {
  6413. ok = false;
  6414. }
  6415. }
  6416. return ok;
  6417. };
  6418. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6419. auto done_with_trailer = [&](const Headers *trailer) {
  6420. if (!ok) { return; }
  6421. data_available = false;
  6422. std::string payload;
  6423. if (!compressor.compress(nullptr, 0, true,
  6424. [&](const char *data, size_t data_len) {
  6425. payload.append(data, data_len);
  6426. return true;
  6427. })) {
  6428. ok = false;
  6429. return;
  6430. }
  6431. if (!payload.empty()) {
  6432. // Emit chunked response header and footer for each chunk
  6433. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6434. if (!write_data(strm, chunk.data(), chunk.size())) {
  6435. ok = false;
  6436. return;
  6437. }
  6438. }
  6439. constexpr const char done_marker[] = "0\r\n";
  6440. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6441. // Trailer
  6442. if (trailer) {
  6443. for (const auto &kv : *trailer) {
  6444. // Skip fields with invalid names or values to prevent response
  6445. // splitting via CR/LF injection, matching set_header().
  6446. if (!fields::is_field_name(kv.first) ||
  6447. !fields::is_field_value(kv.second)) {
  6448. continue;
  6449. }
  6450. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6451. if (!write_data(strm, field_line.data(), field_line.size())) {
  6452. ok = false;
  6453. }
  6454. }
  6455. }
  6456. constexpr const char crlf[] = "\r\n";
  6457. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6458. };
  6459. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6460. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6461. done_with_trailer(&trailer);
  6462. };
  6463. while (data_available && !is_shutting_down()) {
  6464. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6465. error = Error::Write;
  6466. return false;
  6467. } else if (!content_provider(offset, 0, data_sink)) {
  6468. error = Error::Canceled;
  6469. return false;
  6470. } else if (!ok) {
  6471. error = Error::Write;
  6472. return false;
  6473. }
  6474. }
  6475. if (data_available) { // exited due to is_shutting_down(), not done()
  6476. error = Error::Write;
  6477. return false;
  6478. }
  6479. error = Error::Success;
  6480. return true;
  6481. }
  6482. template <typename T, typename U>
  6483. inline bool write_content_chunked(Stream &strm,
  6484. const ContentProvider &content_provider,
  6485. const T &is_shutting_down, U &compressor) {
  6486. auto error = Error::Success;
  6487. return write_content_chunked(strm, content_provider, is_shutting_down,
  6488. compressor, error);
  6489. }
  6490. template <typename T>
  6491. inline bool redirect(T &cli, Request &req, Response &res,
  6492. const std::string &path, const std::string &location,
  6493. Error &error) {
  6494. Request new_req = req;
  6495. new_req.path = path;
  6496. new_req.redirect_count_ -= 1;
  6497. if (res.status == StatusCode::SeeOther_303 &&
  6498. (req.method != "GET" && req.method != "HEAD")) {
  6499. new_req.method = "GET";
  6500. new_req.body.clear();
  6501. new_req.headers.clear();
  6502. }
  6503. Response new_res;
  6504. auto ret = cli.send(new_req, new_res, error);
  6505. if (ret) {
  6506. req = std::move(new_req);
  6507. res = std::move(new_res);
  6508. if (res.location.empty()) { res.location = location; }
  6509. }
  6510. return ret;
  6511. }
  6512. inline std::string params_to_query_str(const Params &params) {
  6513. std::string query;
  6514. for (auto it = params.begin(); it != params.end(); ++it) {
  6515. if (it != params.begin()) { query += '&'; }
  6516. query += encode_query_component(it->first);
  6517. query += '=';
  6518. query += encode_query_component(it->second);
  6519. }
  6520. return query;
  6521. }
  6522. inline void parse_query_text(const char *data, std::size_t size,
  6523. Params &params) {
  6524. std::set<std::string> cache;
  6525. split(data, data + size, '&', [&](const char *b, const char *e) {
  6526. std::string kv(b, e);
  6527. if (cache.find(kv) != cache.end()) { return; }
  6528. cache.insert(std::move(kv));
  6529. std::string key;
  6530. std::string val;
  6531. divide(b, static_cast<std::size_t>(e - b), '=',
  6532. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6533. std::size_t rhs_size) {
  6534. key.assign(lhs_data, lhs_size);
  6535. val.assign(rhs_data, rhs_size);
  6536. });
  6537. if (!key.empty()) {
  6538. params.emplace(decode_query_component(key), decode_query_component(val));
  6539. }
  6540. });
  6541. }
  6542. inline void parse_query_text(const std::string &s, Params &params) {
  6543. parse_query_text(s.data(), s.size(), params);
  6544. }
  6545. // Normalize a query string by decoding and re-encoding each key/value pair
  6546. // while preserving the original parameter order. This avoids double-encoding
  6547. // and ensures consistent encoding without reordering (unlike Params which
  6548. // uses std::multimap and sorts keys).
  6549. inline std::string normalize_query_string(const std::string &query) {
  6550. std::string result;
  6551. split(query.data(), query.data() + query.size(), '&',
  6552. [&](const char *b, const char *e) {
  6553. std::string key;
  6554. std::string val;
  6555. divide(b, static_cast<std::size_t>(e - b), '=',
  6556. [&](const char *lhs_data, std::size_t lhs_size,
  6557. const char *rhs_data, std::size_t rhs_size) {
  6558. key.assign(lhs_data, lhs_size);
  6559. val.assign(rhs_data, rhs_size);
  6560. });
  6561. if (!key.empty()) {
  6562. auto dec_key = decode_query_component(key);
  6563. auto dec_val = decode_query_component(val);
  6564. if (!result.empty()) { result += '&'; }
  6565. result += encode_query_component(dec_key);
  6566. if (!val.empty() || std::find(b, e, '=') != e) {
  6567. result += '=';
  6568. result += encode_query_component(dec_val);
  6569. }
  6570. }
  6571. });
  6572. return result;
  6573. }
  6574. inline bool parse_multipart_boundary(const std::string &content_type,
  6575. std::string &boundary) {
  6576. std::map<std::string, std::string> params;
  6577. extract_media_type(content_type, &params);
  6578. auto it = params.find("boundary");
  6579. if (it == params.end()) { return false; }
  6580. boundary = it->second;
  6581. return !boundary.empty();
  6582. }
  6583. inline void parse_disposition_params(const std::string &s, Params &params) {
  6584. std::set<std::string> cache;
  6585. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6586. std::string kv(b, e);
  6587. if (cache.find(kv) != cache.end()) { return; }
  6588. cache.insert(kv);
  6589. std::string key;
  6590. std::string val;
  6591. split(b, e, '=', [&](const char *b2, const char *e2) {
  6592. if (key.empty()) {
  6593. key.assign(b2, e2);
  6594. } else {
  6595. val.assign(b2, e2);
  6596. }
  6597. });
  6598. if (!key.empty()) {
  6599. params.emplace(trim_double_quotes_copy((key)),
  6600. trim_double_quotes_copy((val)));
  6601. }
  6602. });
  6603. }
  6604. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6605. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6606. #else
  6607. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6608. #endif
  6609. auto is_valid = [](const std::string &str) {
  6610. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6611. };
  6612. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6613. const auto pos = static_cast<size_t>(6);
  6614. const auto len = static_cast<size_t>(s.size() - 6);
  6615. auto all_valid_ranges = true;
  6616. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6617. if (!all_valid_ranges) { return; }
  6618. const auto it = std::find(b, e, '-');
  6619. if (it == e) {
  6620. all_valid_ranges = false;
  6621. return;
  6622. }
  6623. const auto lhs = std::string(b, it);
  6624. const auto rhs = std::string(it + 1, e);
  6625. if (!is_valid(lhs) || !is_valid(rhs)) {
  6626. all_valid_ranges = false;
  6627. return;
  6628. }
  6629. ssize_t first = -1;
  6630. if (!lhs.empty()) {
  6631. ssize_t v;
  6632. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6633. if (res.ec == std::errc{}) { first = v; }
  6634. }
  6635. ssize_t last = -1;
  6636. if (!rhs.empty()) {
  6637. ssize_t v;
  6638. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6639. if (res.ec == std::errc{}) { last = v; }
  6640. }
  6641. if ((first == -1 && last == -1) ||
  6642. (first != -1 && last != -1 && first > last)) {
  6643. all_valid_ranges = false;
  6644. return;
  6645. }
  6646. ranges.emplace_back(first, last);
  6647. });
  6648. return all_valid_ranges && !ranges.empty();
  6649. }
  6650. return false;
  6651. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6652. }
  6653. #else
  6654. } catch (...) { return false; }
  6655. #endif
  6656. inline bool parse_accept_header(const std::string &s,
  6657. std::vector<std::string> &content_types) {
  6658. content_types.clear();
  6659. // Empty string is considered valid (no preference)
  6660. if (s.empty()) { return true; }
  6661. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6662. if (s.front() == ',' || s.back() == ',' ||
  6663. s.find(",,") != std::string::npos) {
  6664. return false;
  6665. }
  6666. struct AcceptEntry {
  6667. std::string media_type;
  6668. double quality;
  6669. int order;
  6670. };
  6671. std::vector<AcceptEntry> entries;
  6672. int order = 0;
  6673. bool has_invalid_entry = false;
  6674. // Split by comma and parse each entry
  6675. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6676. std::string entry(b, e);
  6677. entry = trim_copy(entry);
  6678. if (entry.empty()) {
  6679. has_invalid_entry = true;
  6680. return;
  6681. }
  6682. AcceptEntry accept_entry;
  6683. accept_entry.order = order++;
  6684. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6685. accept_entry.media_type, accept_entry.quality)) {
  6686. has_invalid_entry = true;
  6687. return;
  6688. }
  6689. // Remove additional parameters from media type
  6690. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6691. // Basic validation of media type format
  6692. if (accept_entry.media_type.empty()) {
  6693. has_invalid_entry = true;
  6694. return;
  6695. }
  6696. // Check for basic media type format (should contain '/' or be '*')
  6697. if (accept_entry.media_type != "*" &&
  6698. accept_entry.media_type.find('/') == std::string::npos) {
  6699. has_invalid_entry = true;
  6700. return;
  6701. }
  6702. entries.push_back(std::move(accept_entry));
  6703. });
  6704. // Return false if any invalid entry was found
  6705. if (has_invalid_entry) { return false; }
  6706. // Sort by quality (descending), then by original order (ascending)
  6707. std::sort(entries.begin(), entries.end(),
  6708. [](const AcceptEntry &a, const AcceptEntry &b) {
  6709. if (a.quality != b.quality) {
  6710. return a.quality > b.quality; // Higher quality first
  6711. }
  6712. return a.order < b.order; // Earlier order first for same quality
  6713. });
  6714. // Extract sorted media types
  6715. content_types.reserve(entries.size());
  6716. for (auto &entry : entries) {
  6717. content_types.push_back(std::move(entry.media_type));
  6718. }
  6719. return true;
  6720. }
  6721. class FormDataParser {
  6722. public:
  6723. FormDataParser() = default;
  6724. void set_boundary(std::string &&boundary) {
  6725. boundary_ = std::move(boundary);
  6726. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6727. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6728. }
  6729. bool is_valid() const { return is_valid_; }
  6730. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6731. const ContentReceiver &content_callback) {
  6732. buf_append(buf, n);
  6733. while (buf_size() > 0) {
  6734. switch (state_) {
  6735. case 0: { // Initial boundary
  6736. auto pos = buf_find(dash_boundary_crlf_);
  6737. if (pos == buf_size()) { return true; }
  6738. buf_erase(pos + dash_boundary_crlf_.size());
  6739. state_ = 1;
  6740. break;
  6741. }
  6742. case 1: { // New entry
  6743. clear_file_info();
  6744. state_ = 2;
  6745. break;
  6746. }
  6747. case 2: { // Headers
  6748. auto pos = buf_find(crlf_);
  6749. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6750. while (pos < buf_size()) {
  6751. // Empty line
  6752. if (pos == 0) {
  6753. if (!header_callback(file_)) {
  6754. is_valid_ = false;
  6755. return false;
  6756. }
  6757. buf_erase(crlf_.size());
  6758. state_ = 3;
  6759. break;
  6760. }
  6761. const auto header = buf_head(pos);
  6762. if (!parse_header(header.data(), header.data() + header.size(),
  6763. [&](const std::string &, const std::string &) {})) {
  6764. is_valid_ = false;
  6765. return false;
  6766. }
  6767. // Parse and emplace space trimmed headers into a map
  6768. if (!parse_header(
  6769. header.data(), header.data() + header.size(),
  6770. [&](const std::string &key, const std::string &val) {
  6771. file_.headers.emplace(key, val);
  6772. })) {
  6773. is_valid_ = false;
  6774. return false;
  6775. }
  6776. constexpr const char header_content_type[] = "Content-Type:";
  6777. if (start_with_case_ignore(header, header_content_type)) {
  6778. file_.content_type =
  6779. trim_copy(header.substr(str_len(header_content_type)));
  6780. } else {
  6781. std::string disposition_params;
  6782. if (parse_content_disposition(header, disposition_params)) {
  6783. Params params;
  6784. parse_disposition_params(disposition_params, params);
  6785. auto it = params.find("name");
  6786. if (it != params.end()) {
  6787. file_.name = it->second;
  6788. } else {
  6789. is_valid_ = false;
  6790. return false;
  6791. }
  6792. it = params.find("filename");
  6793. if (it != params.end()) { file_.filename = it->second; }
  6794. it = params.find("filename*");
  6795. if (it != params.end()) {
  6796. // RFC 5987: only UTF-8 encoding is allowed
  6797. const auto &val = it->second;
  6798. constexpr const char utf8_prefix[] = "UTF-8''";
  6799. constexpr size_t prefix_len = str_len(utf8_prefix);
  6800. if (val.size() > prefix_len &&
  6801. start_with_case_ignore(val, utf8_prefix)) {
  6802. file_.filename = decode_path_component(
  6803. val.substr(prefix_len)); // override...
  6804. } else {
  6805. is_valid_ = false;
  6806. return false;
  6807. }
  6808. }
  6809. }
  6810. }
  6811. buf_erase(pos + crlf_.size());
  6812. pos = buf_find(crlf_);
  6813. }
  6814. if (state_ != 3) { return true; }
  6815. break;
  6816. }
  6817. case 3: { // Body
  6818. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6819. auto pos = buf_find(crlf_dash_boundary_);
  6820. if (pos < buf_size()) {
  6821. if (!content_callback(buf_data(), pos)) {
  6822. is_valid_ = false;
  6823. return false;
  6824. }
  6825. buf_erase(pos + crlf_dash_boundary_.size());
  6826. state_ = 4;
  6827. } else {
  6828. auto len = buf_size() - crlf_dash_boundary_.size();
  6829. if (len > 0) {
  6830. if (!content_callback(buf_data(), len)) {
  6831. is_valid_ = false;
  6832. return false;
  6833. }
  6834. buf_erase(len);
  6835. }
  6836. return true;
  6837. }
  6838. break;
  6839. }
  6840. case 4: { // Boundary
  6841. if (crlf_.size() > buf_size()) { return true; }
  6842. if (buf_start_with(crlf_)) {
  6843. buf_erase(crlf_.size());
  6844. state_ = 1;
  6845. } else {
  6846. if (dash_.size() > buf_size()) { return true; }
  6847. if (buf_start_with(dash_)) {
  6848. buf_erase(dash_.size());
  6849. is_valid_ = true;
  6850. buf_erase(buf_size()); // Remove epilogue
  6851. } else {
  6852. return true;
  6853. }
  6854. }
  6855. break;
  6856. }
  6857. }
  6858. }
  6859. return true;
  6860. }
  6861. private:
  6862. void clear_file_info() {
  6863. file_.name.clear();
  6864. file_.filename.clear();
  6865. file_.content_type.clear();
  6866. file_.headers.clear();
  6867. }
  6868. bool start_with_case_ignore(const std::string &a, const char *b,
  6869. size_t offset = 0) const {
  6870. const auto b_len = strlen(b);
  6871. if (a.size() < offset + b_len) { return false; }
  6872. for (size_t i = 0; i < b_len; i++) {
  6873. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6874. return false;
  6875. }
  6876. }
  6877. return true;
  6878. }
  6879. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6880. // Returns true if header matches, with the params portion in `params_out`.
  6881. bool parse_content_disposition(const std::string &header,
  6882. std::string &params_out) const {
  6883. constexpr const char prefix[] = "Content-Disposition:";
  6884. constexpr size_t prefix_len = str_len(prefix);
  6885. if (!start_with_case_ignore(header, prefix)) { return false; }
  6886. // Skip whitespace after "Content-Disposition:"
  6887. auto pos = prefix_len;
  6888. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6889. pos++;
  6890. }
  6891. // Match "form-data;" (case-insensitive)
  6892. constexpr const char form_data[] = "form-data;";
  6893. constexpr size_t form_data_len = str_len(form_data);
  6894. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6895. pos += form_data_len;
  6896. // Skip whitespace after "form-data;"
  6897. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6898. pos++;
  6899. }
  6900. params_out = header.substr(pos);
  6901. return true;
  6902. }
  6903. const std::string dash_ = "--";
  6904. const std::string crlf_ = "\r\n";
  6905. std::string boundary_;
  6906. std::string dash_boundary_crlf_;
  6907. std::string crlf_dash_boundary_;
  6908. size_t state_ = 0;
  6909. bool is_valid_ = false;
  6910. FormData file_;
  6911. // Buffer
  6912. bool start_with(const std::string &a, size_t spos, size_t epos,
  6913. const std::string &b) const {
  6914. if (epos - spos < b.size()) { return false; }
  6915. for (size_t i = 0; i < b.size(); i++) {
  6916. if (a[i + spos] != b[i]) { return false; }
  6917. }
  6918. return true;
  6919. }
  6920. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6921. const char *buf_data() const { return &buf_[buf_spos_]; }
  6922. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6923. bool buf_start_with(const std::string &s) const {
  6924. return start_with(buf_, buf_spos_, buf_epos_, s);
  6925. }
  6926. size_t buf_find(const std::string &s) const {
  6927. auto c = s.front();
  6928. size_t off = buf_spos_;
  6929. while (off < buf_epos_) {
  6930. auto pos = off;
  6931. while (true) {
  6932. if (pos == buf_epos_) { return buf_size(); }
  6933. if (buf_[pos] == c) { break; }
  6934. pos++;
  6935. }
  6936. auto remaining_size = buf_epos_ - pos;
  6937. if (s.size() > remaining_size) { return buf_size(); }
  6938. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6939. off = pos + 1;
  6940. }
  6941. return buf_size();
  6942. }
  6943. void buf_append(const char *data, size_t n) {
  6944. auto remaining_size = buf_size();
  6945. if (remaining_size > 0 && buf_spos_ > 0) {
  6946. for (size_t i = 0; i < remaining_size; i++) {
  6947. buf_[i] = buf_[buf_spos_ + i];
  6948. }
  6949. }
  6950. buf_spos_ = 0;
  6951. buf_epos_ = remaining_size;
  6952. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6953. for (size_t i = 0; i < n; i++) {
  6954. buf_[buf_epos_ + i] = data[i];
  6955. }
  6956. buf_epos_ += n;
  6957. }
  6958. void buf_erase(size_t size) { buf_spos_ += size; }
  6959. std::string buf_;
  6960. size_t buf_spos_ = 0;
  6961. size_t buf_epos_ = 0;
  6962. };
  6963. inline std::string random_string(size_t length) {
  6964. constexpr const char data[] =
  6965. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6966. thread_local auto engine([]() {
  6967. // std::random_device might actually be deterministic on some
  6968. // platforms, but due to lack of support in the c++ standard library,
  6969. // doing better requires either some ugly hacks or breaking portability.
  6970. std::random_device seed_gen;
  6971. // Request 128 bits of entropy for initialization
  6972. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6973. return std::mt19937(seed_sequence);
  6974. }());
  6975. std::string result;
  6976. for (size_t i = 0; i < length; i++) {
  6977. result += data[engine() % (sizeof(data) - 1)];
  6978. }
  6979. return result;
  6980. }
  6981. inline std::string make_multipart_data_boundary() {
  6982. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6983. }
  6984. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6985. auto valid = true;
  6986. for (size_t i = 0; i < boundary.size(); i++) {
  6987. auto c = boundary[i];
  6988. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  6989. valid = false;
  6990. break;
  6991. }
  6992. }
  6993. return valid;
  6994. }
  6995. // Escape a multipart field name/filename following the WHATWG HTML standard
  6996. // ("escape a multipart form-data name"), which is what browsers send:
  6997. // '"' -> %22, CR -> %0D, LF -> %0A
  6998. // With escape_quote = false, only CR and LF are escaped; this is for header
  6999. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  7000. inline std::string escape_multipart_field(const std::string &s,
  7001. bool escape_quote = true) {
  7002. std::string result;
  7003. result.reserve(s.size());
  7004. for (auto c : s) {
  7005. switch (c) {
  7006. case '"':
  7007. if (escape_quote) {
  7008. result += "%22";
  7009. } else {
  7010. result += c;
  7011. }
  7012. break;
  7013. case '\r': result += "%0D"; break;
  7014. case '\n': result += "%0A"; break;
  7015. default: result += c; break;
  7016. }
  7017. }
  7018. return result;
  7019. }
  7020. template <typename T>
  7021. inline std::string
  7022. serialize_multipart_formdata_item_begin(const T &item,
  7023. const std::string &boundary) {
  7024. std::string body = "--" + boundary + "\r\n";
  7025. body += "Content-Disposition: form-data; name=\"" +
  7026. escape_multipart_field(item.name) + "\"";
  7027. if (!item.filename.empty()) {
  7028. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  7029. }
  7030. body += "\r\n";
  7031. if (!item.content_type.empty()) {
  7032. body +=
  7033. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  7034. "\r\n";
  7035. }
  7036. body += "\r\n";
  7037. return body;
  7038. }
  7039. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7040. inline std::string
  7041. serialize_multipart_formdata_finish(const std::string &boundary) {
  7042. return "--" + boundary + "--\r\n";
  7043. }
  7044. inline std::string
  7045. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7046. return "multipart/form-data; boundary=" + boundary;
  7047. }
  7048. inline std::string
  7049. serialize_multipart_formdata(const UploadFormDataItems &items,
  7050. const std::string &boundary, bool finish = true) {
  7051. std::string body;
  7052. for (const auto &item : items) {
  7053. body += serialize_multipart_formdata_item_begin(item, boundary);
  7054. body += item.content + serialize_multipart_formdata_item_end();
  7055. }
  7056. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7057. return body;
  7058. }
  7059. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7060. const std::string &boundary) {
  7061. size_t total = 0;
  7062. for (const auto &item : items) {
  7063. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7064. total += item.content.size();
  7065. total += serialize_multipart_formdata_item_end().size();
  7066. }
  7067. total += serialize_multipart_formdata_finish(boundary).size();
  7068. return total;
  7069. }
  7070. struct MultipartSegment {
  7071. const char *data;
  7072. size_t size;
  7073. };
  7074. // NOTE: items must outlive the returned ContentProvider
  7075. // (safe for synchronous use inside Post/Put/Patch)
  7076. inline ContentProvider
  7077. make_multipart_content_provider(const UploadFormDataItems &items,
  7078. const std::string &boundary) {
  7079. // Own the per-item header strings and the finish string
  7080. std::vector<std::string> owned;
  7081. owned.reserve(items.size() + 1);
  7082. for (const auto &item : items)
  7083. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7084. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7085. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7086. std::vector<MultipartSegment> segs;
  7087. segs.reserve(items.size() * 3 + 1);
  7088. static const char crlf[] = "\r\n";
  7089. for (size_t i = 0; i < items.size(); i++) {
  7090. segs.push_back({owned[i].data(), owned[i].size()});
  7091. segs.push_back({items[i].content.data(), items[i].content.size()});
  7092. segs.push_back({crlf, 2});
  7093. }
  7094. segs.push_back({owned.back().data(), owned.back().size()});
  7095. struct MultipartState {
  7096. std::vector<std::string> owned;
  7097. std::vector<MultipartSegment> segs;
  7098. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7099. };
  7100. auto state = std::make_shared<MultipartState>();
  7101. state->owned = std::move(owned);
  7102. // `segs` holds raw pointers into owned strings; std::string move preserves
  7103. // the data pointer, so these pointers remain valid after the move above.
  7104. state->segs = std::move(segs);
  7105. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7106. // Buffer multiple small segments into fewer, larger writes to avoid
  7107. // excessive TCP packets when there are many form data items (#2410)
  7108. auto &buf = state->buf;
  7109. auto buf_size = buf.size();
  7110. size_t buf_len = 0;
  7111. size_t remaining = length;
  7112. // Find the first segment containing 'offset'
  7113. size_t pos = 0;
  7114. size_t seg_idx = 0;
  7115. for (; seg_idx < state->segs.size(); seg_idx++) {
  7116. const auto &seg = state->segs[seg_idx];
  7117. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7118. pos += seg.size;
  7119. }
  7120. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7121. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7122. const auto &seg = state->segs[seg_idx];
  7123. size_t available = seg.size - seg_offset;
  7124. size_t to_copy = (std::min)(available, remaining);
  7125. const char *src = seg.data + seg_offset;
  7126. seg_offset = 0; // only the first segment has a non-zero offset
  7127. while (to_copy > 0) {
  7128. size_t space = buf_size - buf_len;
  7129. size_t chunk = (std::min)(to_copy, space);
  7130. std::memcpy(buf.data() + buf_len, src, chunk);
  7131. buf_len += chunk;
  7132. src += chunk;
  7133. to_copy -= chunk;
  7134. remaining -= chunk;
  7135. if (buf_len == buf_size) {
  7136. if (!sink.write(buf.data(), buf_len)) { return false; }
  7137. buf_len = 0;
  7138. }
  7139. }
  7140. }
  7141. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7142. return true;
  7143. };
  7144. }
  7145. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7146. if (ranges.size() <= 1) return;
  7147. // Sort ranges by start position
  7148. std::sort(ranges.begin(), ranges.end(),
  7149. [](const Range &a, const Range &b) { return a.first < b.first; });
  7150. Ranges coalesced;
  7151. coalesced.reserve(ranges.size());
  7152. for (auto &r : ranges) {
  7153. auto first_pos = r.first;
  7154. auto last_pos = r.second;
  7155. // Handle special cases like in range_error
  7156. if (first_pos == -1 && last_pos == -1) {
  7157. first_pos = 0;
  7158. last_pos = static_cast<ssize_t>(content_length);
  7159. }
  7160. if (first_pos == -1) {
  7161. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7162. last_pos = static_cast<ssize_t>(content_length) - 1;
  7163. }
  7164. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7165. last_pos = static_cast<ssize_t>(content_length) - 1;
  7166. }
  7167. // Skip invalid ranges
  7168. if (!(0 <= first_pos && first_pos <= last_pos &&
  7169. last_pos < static_cast<ssize_t>(content_length))) {
  7170. continue;
  7171. }
  7172. // Coalesce with previous range if overlapping or adjacent (but not
  7173. // identical)
  7174. if (!coalesced.empty()) {
  7175. auto &prev = coalesced.back();
  7176. // Check if current range overlaps or is adjacent to previous range
  7177. // but don't coalesce identical ranges (allow duplicates)
  7178. if (first_pos <= prev.second + 1 &&
  7179. !(first_pos == prev.first && last_pos == prev.second)) {
  7180. // Extend the previous range
  7181. prev.second = (std::max)(prev.second, last_pos);
  7182. continue;
  7183. }
  7184. }
  7185. // Add new range
  7186. coalesced.emplace_back(first_pos, last_pos);
  7187. }
  7188. ranges = std::move(coalesced);
  7189. }
  7190. inline bool range_error(Request &req, Response &res) {
  7191. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7192. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7193. req.ranges.clear();
  7194. if (res.status == StatusCode::PartialContent_206) {
  7195. res.status = StatusCode::OK_200;
  7196. }
  7197. return false;
  7198. }
  7199. ssize_t content_len = static_cast<ssize_t>(
  7200. res.content_length_ ? res.content_length_ : res.body.size());
  7201. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7202. size_t overwrapping_count = 0;
  7203. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7204. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7205. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7206. // Too many ranges
  7207. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7208. for (auto &r : req.ranges) {
  7209. auto &first_pos = r.first;
  7210. auto &last_pos = r.second;
  7211. if (first_pos == -1 && last_pos == -1) {
  7212. first_pos = 0;
  7213. last_pos = content_len;
  7214. }
  7215. if (first_pos == -1) {
  7216. first_pos = content_len - last_pos;
  7217. last_pos = content_len - 1;
  7218. }
  7219. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7220. // A client can limit the number of bytes requested without knowing the
  7221. // size of the selected representation. If the last-pos value is absent,
  7222. // or if the value is greater than or equal to the current length of the
  7223. // representation data, the byte range is interpreted as the remainder of
  7224. // the representation (i.e., the server replaces the value of last-pos
  7225. // with a value that is one less than the current length of the selected
  7226. // representation).
  7227. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7228. if (last_pos == -1 || last_pos >= content_len) {
  7229. last_pos = content_len - 1;
  7230. }
  7231. // Range must be within content length
  7232. if (!(0 <= first_pos && first_pos <= last_pos &&
  7233. last_pos <= content_len - 1)) {
  7234. return true;
  7235. }
  7236. // Request must not have more than two overlapping ranges
  7237. for (const auto &processed_range : processed_ranges) {
  7238. if (!(last_pos < processed_range.first ||
  7239. first_pos > processed_range.second)) {
  7240. overwrapping_count++;
  7241. if (overwrapping_count > 2) { return true; }
  7242. break; // Only count once per range
  7243. }
  7244. }
  7245. processed_ranges.emplace_back(first_pos, last_pos);
  7246. }
  7247. // After validation, coalesce overlapping ranges as per RFC 9110
  7248. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7249. }
  7250. return false;
  7251. }
  7252. inline std::pair<size_t, size_t>
  7253. get_range_offset_and_length(Range r, size_t content_length) {
  7254. assert(r.first != -1 && r.second != -1);
  7255. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7256. assert(r.first <= r.second &&
  7257. r.second < static_cast<ssize_t>(content_length));
  7258. (void)(content_length);
  7259. return std::make_pair(static_cast<size_t>(r.first),
  7260. static_cast<size_t>(r.second - r.first) + 1);
  7261. }
  7262. inline std::string make_content_range_header_field(
  7263. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7264. auto st = offset_and_length.first;
  7265. auto ed = st + offset_and_length.second - 1;
  7266. std::string field = "bytes ";
  7267. field += std::to_string(st);
  7268. field += '-';
  7269. field += std::to_string(ed);
  7270. field += '/';
  7271. field += std::to_string(content_length);
  7272. return field;
  7273. }
  7274. template <typename SToken, typename CToken, typename Content>
  7275. bool process_multipart_ranges_data(const Request &req,
  7276. const std::string &boundary,
  7277. const std::string &content_type,
  7278. size_t content_length, SToken stoken,
  7279. CToken ctoken, Content content) {
  7280. for (size_t i = 0; i < req.ranges.size(); i++) {
  7281. ctoken("--");
  7282. stoken(boundary);
  7283. ctoken("\r\n");
  7284. if (!content_type.empty()) {
  7285. ctoken("Content-Type: ");
  7286. stoken(content_type);
  7287. ctoken("\r\n");
  7288. }
  7289. auto offset_and_length =
  7290. get_range_offset_and_length(req.ranges[i], content_length);
  7291. ctoken("Content-Range: ");
  7292. stoken(make_content_range_header_field(offset_and_length, content_length));
  7293. ctoken("\r\n");
  7294. ctoken("\r\n");
  7295. if (!content(offset_and_length.first, offset_and_length.second)) {
  7296. return false;
  7297. }
  7298. ctoken("\r\n");
  7299. }
  7300. ctoken("--");
  7301. stoken(boundary);
  7302. ctoken("--");
  7303. return true;
  7304. }
  7305. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7306. const std::string &boundary,
  7307. const std::string &content_type,
  7308. size_t content_length,
  7309. std::string &data) {
  7310. process_multipart_ranges_data(
  7311. req, boundary, content_type, content_length,
  7312. [&](const std::string &token) { data += token; },
  7313. [&](const std::string &token) { data += token; },
  7314. [&](size_t offset, size_t length) {
  7315. assert(offset + length <= content_length);
  7316. data += res.body.substr(offset, length);
  7317. return true;
  7318. });
  7319. }
  7320. inline size_t get_multipart_ranges_data_length(const Request &req,
  7321. const std::string &boundary,
  7322. const std::string &content_type,
  7323. size_t content_length) {
  7324. size_t data_length = 0;
  7325. process_multipart_ranges_data(
  7326. req, boundary, content_type, content_length,
  7327. [&](const std::string &token) { data_length += token.size(); },
  7328. [&](const std::string &token) { data_length += token.size(); },
  7329. [&](size_t /*offset*/, size_t length) {
  7330. data_length += length;
  7331. return true;
  7332. });
  7333. return data_length;
  7334. }
  7335. template <typename T>
  7336. inline bool
  7337. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7338. const std::string &boundary,
  7339. const std::string &content_type,
  7340. size_t content_length, const T &is_shutting_down) {
  7341. return process_multipart_ranges_data(
  7342. req, boundary, content_type, content_length,
  7343. [&](const std::string &token) { strm.write(token); },
  7344. [&](const std::string &token) { strm.write(token); },
  7345. [&](size_t offset, size_t length) {
  7346. return write_content(strm, res.content_provider_, offset, length,
  7347. is_shutting_down);
  7348. });
  7349. }
  7350. inline bool has_framed_body(const Request &req) {
  7351. return is_chunked_transfer_encoding(req.headers) ||
  7352. req.get_header_value_u64("Content-Length") > 0;
  7353. }
  7354. inline bool is_connection_persistent(const Request &req) {
  7355. auto conn = req.get_header_value("Connection");
  7356. if (conn == "close") { return false; }
  7357. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7358. return true;
  7359. }
  7360. inline bool expect_content(const Request &req) {
  7361. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7362. req.method == "DELETE") {
  7363. return true;
  7364. }
  7365. return has_framed_body(req);
  7366. }
  7367. #ifdef _WIN32
  7368. class WSInit {
  7369. public:
  7370. WSInit() {
  7371. WSADATA wsaData;
  7372. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7373. }
  7374. ~WSInit() {
  7375. if (is_valid_) WSACleanup();
  7376. }
  7377. bool is_valid_ = false;
  7378. };
  7379. static WSInit wsinit_;
  7380. #endif
  7381. inline bool parse_www_authenticate(const Response &res,
  7382. std::map<std::string, std::string> &auth,
  7383. bool is_proxy) {
  7384. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7385. if (res.has_header(auth_key)) {
  7386. thread_local auto re =
  7387. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7388. auto s = res.get_header_value(auth_key);
  7389. auto pos = s.find(' ');
  7390. if (pos != std::string::npos) {
  7391. auto type = s.substr(0, pos);
  7392. if (type == "Basic") {
  7393. return false;
  7394. } else if (type == "Digest") {
  7395. s = s.substr(pos + 1);
  7396. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7397. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7398. const auto &m = *i;
  7399. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7400. static_cast<size_t>(m.length(1)));
  7401. auto val = m.length(2) > 0
  7402. ? s.substr(static_cast<size_t>(m.position(2)),
  7403. static_cast<size_t>(m.length(2)))
  7404. : s.substr(static_cast<size_t>(m.position(3)),
  7405. static_cast<size_t>(m.length(3)));
  7406. auth[std::move(key)] = std::move(val);
  7407. }
  7408. return true;
  7409. }
  7410. }
  7411. }
  7412. return false;
  7413. }
  7414. class ContentProviderAdapter {
  7415. public:
  7416. explicit ContentProviderAdapter(
  7417. ContentProviderWithoutLength &&content_provider)
  7418. : content_provider_(std::move(content_provider)) {}
  7419. bool operator()(size_t offset, size_t, DataSink &sink) {
  7420. return content_provider_(offset, sink);
  7421. }
  7422. private:
  7423. ContentProviderWithoutLength content_provider_;
  7424. };
  7425. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7426. namespace fields {
  7427. inline bool is_token_char(char c) {
  7428. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7429. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7430. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7431. }
  7432. inline bool is_token(const std::string &s) {
  7433. if (s.empty()) { return false; }
  7434. for (auto c : s) {
  7435. if (!is_token_char(c)) { return false; }
  7436. }
  7437. return true;
  7438. }
  7439. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7440. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7441. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7442. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7443. inline bool is_field_content(const std::string &s) {
  7444. if (s.empty()) { return true; }
  7445. if (s.size() == 1) {
  7446. return is_field_vchar(s[0]);
  7447. } else if (s.size() == 2) {
  7448. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7449. } else {
  7450. size_t i = 0;
  7451. if (!is_field_vchar(s[i])) { return false; }
  7452. i++;
  7453. while (i < s.size() - 1) {
  7454. auto c = s[i++];
  7455. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7456. } else {
  7457. return false;
  7458. }
  7459. }
  7460. return is_field_vchar(s[i]);
  7461. }
  7462. }
  7463. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7464. } // namespace fields
  7465. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7466. int port, bool is_ssl,
  7467. const std::string &path,
  7468. const Headers &headers,
  7469. std::string &selected_subprotocol) {
  7470. // Validate path and host
  7471. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7472. return false;
  7473. }
  7474. // Validate user-provided headers
  7475. for (const auto &h : headers) {
  7476. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7477. return false;
  7478. }
  7479. }
  7480. // Generate random Sec-WebSocket-Key
  7481. thread_local std::mt19937 rng(std::random_device{}());
  7482. std::string key_bytes(16, '\0');
  7483. for (size_t i = 0; i < 16; i += 4) {
  7484. auto r = rng();
  7485. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7486. }
  7487. auto client_key = base64_encode(key_bytes);
  7488. // Build upgrade request
  7489. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7490. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7491. req_str += "Upgrade: websocket\r\n";
  7492. req_str += "Connection: Upgrade\r\n";
  7493. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7494. req_str += "Sec-WebSocket-Version: 13\r\n";
  7495. for (const auto &h : headers) {
  7496. req_str += h.first + ": " + h.second + "\r\n";
  7497. }
  7498. req_str += "\r\n";
  7499. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7500. // Verify 101 response and Sec-WebSocket-Accept header
  7501. auto expected_accept = websocket_accept_key(client_key);
  7502. return read_websocket_upgrade_response(strm, expected_accept,
  7503. selected_subprotocol);
  7504. }
  7505. } // namespace detail
  7506. /*
  7507. * Group 2: detail namespace - SSL common utilities
  7508. */
  7509. #ifdef CPPHTTPLIB_SSL_ENABLED
  7510. namespace detail {
  7511. class SSLSocketStream final : public Stream {
  7512. public:
  7513. SSLSocketStream(
  7514. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7515. time_t read_timeout_usec, time_t write_timeout_sec,
  7516. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7517. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7518. (std::chrono::steady_clock::time_point::min)());
  7519. ~SSLSocketStream() override;
  7520. bool is_readable() const override;
  7521. bool wait_readable() const override;
  7522. bool wait_writable() const override;
  7523. bool is_peer_alive() const override;
  7524. ssize_t read(char *ptr, size_t size) override;
  7525. ssize_t write(const char *ptr, size_t size) override;
  7526. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7527. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7528. socket_t socket() const override;
  7529. time_t duration() const override;
  7530. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7531. private:
  7532. socket_t sock_;
  7533. tls::session_t session_;
  7534. time_t read_timeout_sec_;
  7535. time_t read_timeout_usec_;
  7536. time_t write_timeout_sec_;
  7537. time_t write_timeout_usec_;
  7538. time_t max_timeout_msec_;
  7539. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7540. };
  7541. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7542. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7543. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7544. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7545. unsigned int hash_length = 0;
  7546. unsigned char hash[EVP_MAX_MD_SIZE];
  7547. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7548. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7549. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7550. std::stringstream ss;
  7551. for (auto i = 0u; i < hash_length; ++i) {
  7552. ss << std::hex << std::setw(2) << std::setfill('0')
  7553. << static_cast<unsigned int>(hash[i]);
  7554. }
  7555. return ss.str();
  7556. }
  7557. inline std::string MD5(const std::string &s) {
  7558. return message_digest(s, EVP_md5());
  7559. }
  7560. inline std::string SHA_256(const std::string &s) {
  7561. return message_digest(s, EVP_sha256());
  7562. }
  7563. inline std::string SHA_512(const std::string &s) {
  7564. return message_digest(s, EVP_sha512());
  7565. }
  7566. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7567. namespace {
  7568. template <size_t N>
  7569. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7570. std::stringstream ss;
  7571. for (size_t i = 0; i < N; ++i) {
  7572. ss << std::hex << std::setw(2) << std::setfill('0')
  7573. << static_cast<unsigned int>(hash[i]);
  7574. }
  7575. return ss.str();
  7576. }
  7577. } // namespace
  7578. inline std::string MD5(const std::string &s) {
  7579. unsigned char hash[16];
  7580. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7581. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7582. hash);
  7583. #else
  7584. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7585. hash);
  7586. #endif
  7587. return hash_to_hex(hash);
  7588. }
  7589. inline std::string SHA_256(const std::string &s) {
  7590. unsigned char hash[32];
  7591. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7592. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7593. hash, 0);
  7594. #else
  7595. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7596. s.size(), hash, 0);
  7597. #endif
  7598. return hash_to_hex(hash);
  7599. }
  7600. inline std::string SHA_512(const std::string &s) {
  7601. unsigned char hash[64];
  7602. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7603. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7604. hash, 0);
  7605. #else
  7606. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7607. s.size(), hash, 0);
  7608. #endif
  7609. return hash_to_hex(hash);
  7610. }
  7611. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7612. namespace {
  7613. template <size_t N>
  7614. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7615. std::stringstream ss;
  7616. for (size_t i = 0; i < N; ++i) {
  7617. ss << std::hex << std::setw(2) << std::setfill('0')
  7618. << static_cast<unsigned int>(hash[i]);
  7619. }
  7620. return ss.str();
  7621. }
  7622. } // namespace
  7623. inline std::string MD5(const std::string &s) {
  7624. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7625. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7626. static_cast<word32>(s.size()), hash);
  7627. return hash_to_hex(hash);
  7628. }
  7629. inline std::string SHA_256(const std::string &s) {
  7630. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7631. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7632. static_cast<word32>(s.size()), hash);
  7633. return hash_to_hex(hash);
  7634. }
  7635. inline std::string SHA_512(const std::string &s) {
  7636. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7637. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7638. static_cast<word32>(s.size()), hash);
  7639. return hash_to_hex(hash);
  7640. }
  7641. #endif
  7642. inline bool is_ip_address(const std::string &host) {
  7643. struct in_addr addr4;
  7644. struct in6_addr addr6;
  7645. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7646. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7647. }
  7648. template <typename T>
  7649. inline bool process_server_socket_ssl(
  7650. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7651. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7652. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7653. time_t write_timeout_usec, T callback) {
  7654. return process_server_socket_core(
  7655. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7656. [&](bool close_connection, bool &connection_closed) {
  7657. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7658. write_timeout_sec, write_timeout_usec);
  7659. return callback(strm, close_connection, connection_closed);
  7660. });
  7661. }
  7662. template <typename T>
  7663. inline bool process_client_socket_ssl(
  7664. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7665. time_t read_timeout_usec, time_t write_timeout_sec,
  7666. time_t write_timeout_usec, time_t max_timeout_msec,
  7667. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7668. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7669. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7670. start_time);
  7671. return callback(strm);
  7672. }
  7673. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7674. const Request &req, const std::map<std::string, std::string> &auth,
  7675. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7676. const std::string &password, bool is_proxy = false) {
  7677. std::string nc;
  7678. {
  7679. std::stringstream ss;
  7680. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7681. nc = ss.str();
  7682. }
  7683. std::string qop;
  7684. if (auth.find("qop") != auth.end()) {
  7685. qop = auth.at("qop");
  7686. if (qop.find("auth-int") != std::string::npos) {
  7687. qop = "auth-int";
  7688. } else if (qop.find("auth") != std::string::npos) {
  7689. qop = "auth";
  7690. } else {
  7691. qop.clear();
  7692. }
  7693. }
  7694. std::string algo = "MD5";
  7695. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7696. std::string response;
  7697. {
  7698. auto H = algo == "SHA-256" ? detail::SHA_256
  7699. : algo == "SHA-512" ? detail::SHA_512
  7700. : detail::MD5;
  7701. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7702. auto A2 = req.method + ":" + req.path;
  7703. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7704. if (qop.empty()) {
  7705. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7706. } else {
  7707. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7708. ":" + qop + ":" + H(A2));
  7709. }
  7710. }
  7711. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7712. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7713. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7714. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7715. (qop.empty() ? ", response=\""
  7716. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7717. cnonce + "\", response=\"") +
  7718. response + "\"" +
  7719. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7720. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7721. return std::make_pair(key, field);
  7722. }
  7723. inline bool match_hostname(const std::string &pattern,
  7724. const std::string &hostname) {
  7725. // Exact match (case-insensitive)
  7726. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7727. // Split both pattern and hostname into components by '.'
  7728. std::vector<std::string> pattern_components;
  7729. if (!pattern.empty()) {
  7730. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7731. [&](const char *b, const char *e) {
  7732. pattern_components.emplace_back(b, e);
  7733. });
  7734. }
  7735. std::vector<std::string> host_components;
  7736. if (!hostname.empty()) {
  7737. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7738. [&](const char *b, const char *e) {
  7739. host_components.emplace_back(b, e);
  7740. });
  7741. }
  7742. // Component count must match
  7743. if (host_components.size() != pattern_components.size()) { return false; }
  7744. // Compare each component with wildcard support
  7745. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7746. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7747. auto itr = pattern_components.begin();
  7748. for (const auto &h : host_components) {
  7749. auto &p = *itr;
  7750. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7751. bool partial_match = false;
  7752. if (!p.empty() && p[p.size() - 1] == '*') {
  7753. const auto prefix_length = p.size() - 1;
  7754. if (prefix_length == 0) {
  7755. partial_match = true;
  7756. } else if (h.size() >= prefix_length) {
  7757. partial_match =
  7758. std::equal(p.begin(),
  7759. p.begin() + static_cast<std::string::difference_type>(
  7760. prefix_length),
  7761. h.begin(), [](const char ca, const char cb) {
  7762. return detail::case_ignore::to_lower(ca) ==
  7763. detail::case_ignore::to_lower(cb);
  7764. });
  7765. }
  7766. }
  7767. if (!partial_match) { return false; }
  7768. }
  7769. ++itr;
  7770. }
  7771. return true;
  7772. }
  7773. #ifdef _WIN32
  7774. // Verify certificate using Windows CertGetCertificateChain API.
  7775. // This provides real-time certificate validation with Windows Update
  7776. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7777. inline bool
  7778. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7779. const std::string &hostname,
  7780. bool verify_hostname, uint64_t &out_error) {
  7781. if (der_cert.empty()) { return false; }
  7782. out_error = 0;
  7783. // Create Windows certificate context from DER data
  7784. auto cert_context = CertCreateCertificateContext(
  7785. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7786. static_cast<DWORD>(der_cert.size()));
  7787. if (!cert_context) {
  7788. out_error = GetLastError();
  7789. return false;
  7790. }
  7791. auto cert_guard =
  7792. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7793. // Setup chain parameters
  7794. CERT_CHAIN_PARA chain_para = {};
  7795. chain_para.cbSize = sizeof(chain_para);
  7796. // Build certificate chain with revocation checking
  7797. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7798. auto chain_result = CertGetCertificateChain(
  7799. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7800. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7801. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7802. nullptr, &chain_context);
  7803. if (!chain_result || !chain_context) {
  7804. out_error = GetLastError();
  7805. return false;
  7806. }
  7807. auto chain_guard =
  7808. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7809. // Check if chain has errors
  7810. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7811. out_error = chain_context->TrustStatus.dwErrorStatus;
  7812. return false;
  7813. }
  7814. // Verify SSL policy
  7815. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7816. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7817. #ifdef AUTHTYPE_SERVER
  7818. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7819. #endif
  7820. std::wstring whost;
  7821. if (verify_hostname) {
  7822. whost = u8string_to_wstring(hostname.c_str());
  7823. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7824. }
  7825. CERT_CHAIN_POLICY_PARA policy_para = {};
  7826. policy_para.cbSize = sizeof(policy_para);
  7827. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7828. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7829. #else
  7830. policy_para.dwFlags = 0;
  7831. #endif
  7832. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7833. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7834. policy_status.cbSize = sizeof(policy_status);
  7835. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7836. &policy_para, &policy_status)) {
  7837. out_error = GetLastError();
  7838. return false;
  7839. }
  7840. if (policy_status.dwError != 0) {
  7841. out_error = policy_status.dwError;
  7842. return false;
  7843. }
  7844. return true;
  7845. }
  7846. #endif // _WIN32
  7847. // Loads CA file/dir configuration and applies the system CA policy to a
  7848. // client TLS context. PEM data and native stores are applied to the context
  7849. // directly at set time; has_custom_store reflects them for the Auto policy
  7850. // decision.
  7851. inline bool load_client_ca_config(tls::ctx_t ctx,
  7852. const std::string &ca_cert_file_path,
  7853. const std::string &ca_cert_dir_path,
  7854. bool has_custom_store, SystemCAMode mode,
  7855. uint64_t &backend_error) {
  7856. auto ret = true;
  7857. if (!ca_cert_file_path.empty()) {
  7858. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7859. backend_error = tls::get_error();
  7860. ret = false;
  7861. }
  7862. } else if (!ca_cert_dir_path.empty()) {
  7863. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7864. backend_error = tls::get_error();
  7865. ret = false;
  7866. }
  7867. }
  7868. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7869. !ca_cert_dir_path.empty() || has_custom_store;
  7870. if (mode == SystemCAMode::Enabled ||
  7871. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7872. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7873. }
  7874. return ret;
  7875. }
  7876. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7877. tls::session_t &session, socket_t sock,
  7878. bool server_certificate_verification,
  7879. time_t timeout_sec, time_t timeout_usec) {
  7880. using namespace tls;
  7881. if (!ctx) { return false; }
  7882. bool is_ip = is_ip_address(host);
  7883. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7884. // Chain verification happens during the handshake even for IP hosts; the
  7885. // certificate identity is verified post-handshake via verify_hostname()
  7886. set_verify_client(ctx, server_certificate_verification);
  7887. #endif
  7888. session = create_session(ctx, sock);
  7889. if (!session) { return false; }
  7890. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7891. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7892. // their identity is checked post-handshake below instead.
  7893. if (!is_ip) {
  7894. if (server_certificate_verification) {
  7895. set_hostname(session, host.c_str());
  7896. } else {
  7897. set_sni(session, host.c_str());
  7898. }
  7899. }
  7900. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7901. return false;
  7902. }
  7903. if (server_certificate_verification) {
  7904. if (get_verify_result(session) != 0) { return false; }
  7905. // Identity check against the peer certificate, post-handshake for all
  7906. // backends (same as SSLClient). For IP hosts this is the only identity
  7907. // verification since no hostname is bound during the handshake.
  7908. auto server_cert = get_peer_cert(session);
  7909. if (!server_cert) { return false; }
  7910. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7911. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7912. }
  7913. return true;
  7914. }
  7915. } // namespace detail
  7916. #endif // CPPHTTPLIB_SSL_ENABLED
  7917. /*
  7918. * Group 3: httplib namespace - Non-SSL public API implementations
  7919. */
  7920. inline void default_socket_options(socket_t sock) {
  7921. set_socket_opt(sock, SOL_SOCKET,
  7922. #ifdef SO_REUSEPORT
  7923. SO_REUSEPORT,
  7924. #else
  7925. SO_REUSEADDR,
  7926. #endif
  7927. 1);
  7928. }
  7929. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7930. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7931. sizeof(optval));
  7932. }
  7933. inline std::string get_bearer_token_auth(const Request &req) {
  7934. if (req.has_header("Authorization")) {
  7935. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7936. return req.get_header_value("Authorization")
  7937. .substr(bearer_header_prefix_len);
  7938. }
  7939. return "";
  7940. }
  7941. inline const char *status_message(int status) {
  7942. switch (status) {
  7943. case StatusCode::Continue_100: return "Continue";
  7944. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7945. case StatusCode::Processing_102: return "Processing";
  7946. case StatusCode::EarlyHints_103: return "Early Hints";
  7947. case StatusCode::OK_200: return "OK";
  7948. case StatusCode::Created_201: return "Created";
  7949. case StatusCode::Accepted_202: return "Accepted";
  7950. case StatusCode::NonAuthoritativeInformation_203:
  7951. return "Non-Authoritative Information";
  7952. case StatusCode::NoContent_204: return "No Content";
  7953. case StatusCode::ResetContent_205: return "Reset Content";
  7954. case StatusCode::PartialContent_206: return "Partial Content";
  7955. case StatusCode::MultiStatus_207: return "Multi-Status";
  7956. case StatusCode::AlreadyReported_208: return "Already Reported";
  7957. case StatusCode::IMUsed_226: return "IM Used";
  7958. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7959. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7960. case StatusCode::Found_302: return "Found";
  7961. case StatusCode::SeeOther_303: return "See Other";
  7962. case StatusCode::NotModified_304: return "Not Modified";
  7963. case StatusCode::UseProxy_305: return "Use Proxy";
  7964. case StatusCode::unused_306: return "unused";
  7965. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7966. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7967. case StatusCode::BadRequest_400: return "Bad Request";
  7968. case StatusCode::Unauthorized_401: return "Unauthorized";
  7969. case StatusCode::PaymentRequired_402: return "Payment Required";
  7970. case StatusCode::Forbidden_403: return "Forbidden";
  7971. case StatusCode::NotFound_404: return "Not Found";
  7972. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7973. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7974. case StatusCode::ProxyAuthenticationRequired_407:
  7975. return "Proxy Authentication Required";
  7976. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7977. case StatusCode::Conflict_409: return "Conflict";
  7978. case StatusCode::Gone_410: return "Gone";
  7979. case StatusCode::LengthRequired_411: return "Length Required";
  7980. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7981. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7982. case StatusCode::UriTooLong_414: return "URI Too Long";
  7983. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7984. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7985. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7986. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7987. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7988. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7989. case StatusCode::Locked_423: return "Locked";
  7990. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7991. case StatusCode::TooEarly_425: return "Too Early";
  7992. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7993. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7994. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7995. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7996. return "Request Header Fields Too Large";
  7997. case StatusCode::UnavailableForLegalReasons_451:
  7998. return "Unavailable For Legal Reasons";
  7999. case StatusCode::NotImplemented_501: return "Not Implemented";
  8000. case StatusCode::BadGateway_502: return "Bad Gateway";
  8001. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  8002. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  8003. case StatusCode::HttpVersionNotSupported_505:
  8004. return "HTTP Version Not Supported";
  8005. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  8006. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  8007. case StatusCode::LoopDetected_508: return "Loop Detected";
  8008. case StatusCode::NotExtended_510: return "Not Extended";
  8009. case StatusCode::NetworkAuthenticationRequired_511:
  8010. return "Network Authentication Required";
  8011. default:
  8012. case StatusCode::InternalServerError_500: return "Internal Server Error";
  8013. }
  8014. }
  8015. inline std::string to_string(const Error error) {
  8016. switch (error) {
  8017. case Error::Success: return "Success (no error)";
  8018. case Error::Unknown: return "Unknown";
  8019. case Error::Connection: return "Could not establish connection";
  8020. case Error::BindIPAddress: return "Failed to bind IP address";
  8021. case Error::Read: return "Failed to read connection";
  8022. case Error::Write: return "Failed to write connection";
  8023. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  8024. case Error::Canceled: return "Connection handling canceled";
  8025. case Error::SSLConnection: return "SSL connection failed";
  8026. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  8027. case Error::SSLServerVerification: return "SSL server verification failed";
  8028. case Error::SSLServerHostnameVerification:
  8029. return "SSL server hostname verification failed";
  8030. case Error::UnsupportedMultipartBoundaryChars:
  8031. return "Unsupported HTTP multipart boundary characters";
  8032. case Error::Compression: return "Compression failed";
  8033. case Error::ConnectionTimeout: return "Connection timed out";
  8034. case Error::ProxyConnection: return "Proxy connection failed";
  8035. case Error::ConnectionClosed: return "Connection closed by server";
  8036. case Error::Timeout: return "Read timeout";
  8037. case Error::ResourceExhaustion: return "Resource exhaustion";
  8038. case Error::TooManyFormDataFiles: return "Too many form data files";
  8039. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8040. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8041. case Error::ExceedMaxSocketDescriptorCount:
  8042. return "Exceeded maximum socket descriptor count";
  8043. case Error::InvalidRequestLine: return "Invalid request line";
  8044. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8045. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8046. case Error::InvalidHeaders: return "Invalid headers";
  8047. case Error::MultipartParsing: return "Multipart parsing failed";
  8048. case Error::OpenFile: return "Failed to open file";
  8049. case Error::Listen: return "Failed to listen on socket";
  8050. case Error::GetSockName: return "Failed to get socket name";
  8051. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8052. case Error::HTTPParsing: return "HTTP parsing failed";
  8053. case Error::InvalidRangeHeader: return "Invalid Range header";
  8054. default: break;
  8055. }
  8056. return "Invalid";
  8057. }
  8058. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8059. os << to_string(obj);
  8060. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8061. return os;
  8062. }
  8063. inline std::string hosted_at(const std::string &hostname) {
  8064. std::vector<std::string> addrs;
  8065. hosted_at(hostname, addrs);
  8066. if (addrs.empty()) { return std::string(); }
  8067. return addrs[0];
  8068. }
  8069. inline void hosted_at(const std::string &hostname,
  8070. std::vector<std::string> &addrs) {
  8071. struct addrinfo hints;
  8072. struct addrinfo *result;
  8073. memset(&hints, 0, sizeof(struct addrinfo));
  8074. hints.ai_family = AF_UNSPEC;
  8075. hints.ai_socktype = SOCK_STREAM;
  8076. hints.ai_protocol = 0;
  8077. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8078. &result, 0)) {
  8079. #if defined __linux__ && !defined __ANDROID__
  8080. res_init();
  8081. #endif
  8082. return;
  8083. }
  8084. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8085. for (auto rp = result; rp; rp = rp->ai_next) {
  8086. const auto &addr =
  8087. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8088. std::string ip;
  8089. auto dummy = -1;
  8090. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8091. dummy)) {
  8092. addrs.emplace_back(std::move(ip));
  8093. }
  8094. }
  8095. }
  8096. inline std::string encode_uri_component(const std::string &value) {
  8097. std::ostringstream escaped;
  8098. escaped.fill('0');
  8099. escaped << std::hex;
  8100. for (auto c : value) {
  8101. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8102. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8103. escaped << c;
  8104. } else {
  8105. escaped << std::uppercase;
  8106. escaped << '%' << std::setw(2)
  8107. << static_cast<int>(static_cast<unsigned char>(c));
  8108. escaped << std::nouppercase;
  8109. }
  8110. }
  8111. return escaped.str();
  8112. }
  8113. inline std::string encode_uri(const std::string &value) {
  8114. std::ostringstream escaped;
  8115. escaped.fill('0');
  8116. escaped << std::hex;
  8117. for (auto c : value) {
  8118. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8119. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8120. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8121. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8122. escaped << c;
  8123. } else {
  8124. escaped << std::uppercase;
  8125. escaped << '%' << std::setw(2)
  8126. << static_cast<int>(static_cast<unsigned char>(c));
  8127. escaped << std::nouppercase;
  8128. }
  8129. }
  8130. return escaped.str();
  8131. }
  8132. inline std::string decode_uri_component(const std::string &value) {
  8133. std::string result;
  8134. for (size_t i = 0; i < value.size(); i++) {
  8135. if (value[i] == '%' && i + 2 < value.size()) {
  8136. auto val = 0;
  8137. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8138. result += static_cast<char>(val);
  8139. i += 2;
  8140. } else {
  8141. result += value[i];
  8142. }
  8143. } else {
  8144. result += value[i];
  8145. }
  8146. }
  8147. return result;
  8148. }
  8149. inline std::string decode_uri(const std::string &value) {
  8150. std::string result;
  8151. for (size_t i = 0; i < value.size(); i++) {
  8152. if (value[i] == '%' && i + 2 < value.size()) {
  8153. auto val = 0;
  8154. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8155. result += static_cast<char>(val);
  8156. i += 2;
  8157. } else {
  8158. result += value[i];
  8159. }
  8160. } else {
  8161. result += value[i];
  8162. }
  8163. }
  8164. return result;
  8165. }
  8166. inline std::string encode_path_component(const std::string &component) {
  8167. std::string result;
  8168. result.reserve(component.size() * 3);
  8169. for (size_t i = 0; i < component.size(); i++) {
  8170. auto c = static_cast<unsigned char>(component[i]);
  8171. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8172. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8173. c == '_' || c == '~') {
  8174. result += static_cast<char>(c);
  8175. }
  8176. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8177. // "," / ";" / "="
  8178. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8179. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8180. c == '=') {
  8181. result += static_cast<char>(c);
  8182. }
  8183. // Colon is allowed in path segments except first segment
  8184. else if (c == ':') {
  8185. result += static_cast<char>(c);
  8186. }
  8187. // @ is allowed in path
  8188. else if (c == '@') {
  8189. result += static_cast<char>(c);
  8190. } else {
  8191. result += '%';
  8192. char hex[3];
  8193. snprintf(hex, sizeof(hex), "%02X", c);
  8194. result.append(hex, 2);
  8195. }
  8196. }
  8197. return result;
  8198. }
  8199. inline std::string decode_path_component(const std::string &component) {
  8200. std::string result;
  8201. result.reserve(component.size());
  8202. for (size_t i = 0; i < component.size(); i++) {
  8203. if (component[i] == '%' && i + 1 < component.size()) {
  8204. if (component[i + 1] == 'u') {
  8205. // Unicode %uXXXX encoding
  8206. auto val = 0;
  8207. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8208. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8209. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8210. char buff[4];
  8211. size_t len = detail::to_utf8(val, buff);
  8212. if (len > 0) { result.append(buff, len); }
  8213. i += 5; // 'u0000'
  8214. } else {
  8215. result += component[i];
  8216. }
  8217. } else {
  8218. // Standard %XX encoding
  8219. auto val = 0;
  8220. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8221. // 2 digits hex codes
  8222. result += static_cast<char>(val);
  8223. i += 2; // 'XX'
  8224. } else {
  8225. result += component[i];
  8226. }
  8227. }
  8228. } else {
  8229. result += component[i];
  8230. }
  8231. }
  8232. return result;
  8233. }
  8234. inline std::string encode_query_component(const std::string &component,
  8235. bool space_as_plus) {
  8236. std::string result;
  8237. result.reserve(component.size() * 3);
  8238. for (size_t i = 0; i < component.size(); i++) {
  8239. auto c = static_cast<unsigned char>(component[i]);
  8240. // Unreserved characters per RFC 3986
  8241. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8242. c == '_' || c == '~') {
  8243. result += static_cast<char>(c);
  8244. }
  8245. // Space handling
  8246. else if (c == ' ') {
  8247. if (space_as_plus) {
  8248. result += '+';
  8249. } else {
  8250. result += "%20";
  8251. }
  8252. }
  8253. // Plus sign handling
  8254. else if (c == '+') {
  8255. if (space_as_plus) {
  8256. result += "%2B";
  8257. } else {
  8258. result += static_cast<char>(c);
  8259. }
  8260. }
  8261. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8262. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8263. c == '*' || c == ',' || c == ';') {
  8264. result += static_cast<char>(c);
  8265. }
  8266. // Colon and @ are allowed in query
  8267. else if (c == ':' || c == '@') {
  8268. result += static_cast<char>(c);
  8269. }
  8270. // Forward slash is allowed in query values
  8271. else if (c == '/') {
  8272. result += static_cast<char>(c);
  8273. }
  8274. // Question mark is allowed in query values (after first ?)
  8275. else if (c == '?') {
  8276. result += static_cast<char>(c);
  8277. } else {
  8278. result += '%';
  8279. char hex[3];
  8280. snprintf(hex, sizeof(hex), "%02X", c);
  8281. result.append(hex, 2);
  8282. }
  8283. }
  8284. return result;
  8285. }
  8286. inline std::string decode_query_component(const std::string &component,
  8287. bool plus_as_space) {
  8288. std::string result;
  8289. result.reserve(component.size());
  8290. for (size_t i = 0; i < component.size(); i++) {
  8291. if (component[i] == '%' && i + 2 < component.size()) {
  8292. auto val = 0;
  8293. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8294. result += static_cast<char>(val);
  8295. i += 2;
  8296. } else {
  8297. result += component[i];
  8298. }
  8299. } else if (component[i] == '+' && plus_as_space) {
  8300. result += ' '; // + becomes space in form-urlencoded
  8301. } else {
  8302. result += component[i];
  8303. }
  8304. }
  8305. return result;
  8306. }
  8307. inline std::string sanitize_filename(const std::string &filename) {
  8308. // Extract basename: find the last path separator (/ or \)
  8309. auto pos = filename.find_last_of("/\\");
  8310. auto result =
  8311. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8312. // Strip null bytes
  8313. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8314. // Trim whitespace
  8315. {
  8316. auto start = result.find_first_not_of(" \t");
  8317. auto end = result.find_last_not_of(" \t");
  8318. result = (start == std::string::npos)
  8319. ? ""
  8320. : result.substr(start, end - start + 1);
  8321. }
  8322. // Reject . and ..
  8323. if (result == "." || result == "..") { return ""; }
  8324. return result;
  8325. }
  8326. inline std::string append_query_params(const std::string &path,
  8327. const Params &params) {
  8328. std::string path_with_query = path;
  8329. thread_local const std::regex re("[^?]+\\?.*");
  8330. auto delm = std::regex_match(path, re) ? '&' : '?';
  8331. path_with_query += delm + detail::params_to_query_str(params);
  8332. return path_with_query;
  8333. }
  8334. // Header utilities
  8335. inline std::pair<std::string, std::string>
  8336. make_range_header(const Ranges &ranges) {
  8337. std::string field = "bytes=";
  8338. auto i = 0;
  8339. for (const auto &r : ranges) {
  8340. if (i != 0) { field += ", "; }
  8341. if (r.first != -1) { field += std::to_string(r.first); }
  8342. field += '-';
  8343. if (r.second != -1) { field += std::to_string(r.second); }
  8344. i++;
  8345. }
  8346. return std::make_pair("Range", std::move(field));
  8347. }
  8348. inline std::pair<std::string, std::string>
  8349. make_basic_authentication_header(const std::string &username,
  8350. const std::string &password, bool is_proxy) {
  8351. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8352. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8353. return std::make_pair(key, std::move(field));
  8354. }
  8355. inline std::pair<std::string, std::string>
  8356. make_bearer_token_authentication_header(const std::string &token,
  8357. bool is_proxy = false) {
  8358. auto field = "Bearer " + token;
  8359. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8360. return std::make_pair(key, std::move(field));
  8361. }
  8362. // Request implementation
  8363. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8364. size_t id) const {
  8365. return detail::get_header_value_u64(headers, key, def, id);
  8366. }
  8367. inline bool Request::has_header(const std::string &key) const {
  8368. return detail::has_header(headers, key);
  8369. }
  8370. inline std::string Request::get_header_value(const std::string &key,
  8371. const char *def, size_t id) const {
  8372. return detail::get_header_value(headers, key, def, id);
  8373. }
  8374. inline size_t Request::get_header_value_count(const std::string &key) const {
  8375. return detail::get_header_value_count(headers, key);
  8376. }
  8377. inline void Request::set_header(const std::string &key,
  8378. const std::string &val) {
  8379. detail::set_header(headers, key, val);
  8380. }
  8381. inline bool Request::has_trailer(const std::string &key) const {
  8382. return trailers.find(key) != trailers.end();
  8383. }
  8384. inline std::string Request::get_trailer_value(const std::string &key,
  8385. size_t id) const {
  8386. return detail::get_multimap_value(trailers, key, id);
  8387. }
  8388. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8389. auto r = trailers.equal_range(key);
  8390. return static_cast<size_t>(std::distance(r.first, r.second));
  8391. }
  8392. inline bool Request::has_param(const std::string &key) const {
  8393. return params.find(key) != params.end();
  8394. }
  8395. inline std::string Request::get_param_value(const std::string &key,
  8396. size_t id) const {
  8397. return detail::get_multimap_value(params, key, id);
  8398. }
  8399. inline std::vector<std::string>
  8400. Request::get_param_values(const std::string &key) const {
  8401. auto rng = params.equal_range(key);
  8402. std::vector<std::string> values;
  8403. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8404. for (auto it = rng.first; it != rng.second; ++it) {
  8405. values.push_back(it->second);
  8406. }
  8407. return values;
  8408. }
  8409. inline size_t Request::get_param_value_count(const std::string &key) const {
  8410. auto r = params.equal_range(key);
  8411. return static_cast<size_t>(std::distance(r.first, r.second));
  8412. }
  8413. inline bool Request::is_multipart_form_data() const {
  8414. const auto &content_type = get_header_value("Content-Type");
  8415. return detail::extract_media_type(content_type) == "multipart/form-data";
  8416. }
  8417. // Multipart FormData implementation
  8418. inline std::string MultipartFormData::get_field(const std::string &key,
  8419. size_t id) const {
  8420. auto rng = fields.equal_range(key);
  8421. auto it = rng.first;
  8422. std::advance(it, static_cast<ssize_t>(id));
  8423. if (it != rng.second) { return it->second.content; }
  8424. return std::string();
  8425. }
  8426. inline std::vector<std::string>
  8427. MultipartFormData::get_fields(const std::string &key) const {
  8428. std::vector<std::string> values;
  8429. auto rng = fields.equal_range(key);
  8430. for (auto it = rng.first; it != rng.second; it++) {
  8431. values.push_back(it->second.content);
  8432. }
  8433. return values;
  8434. }
  8435. inline bool MultipartFormData::has_field(const std::string &key) const {
  8436. return fields.find(key) != fields.end();
  8437. }
  8438. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8439. auto r = fields.equal_range(key);
  8440. return static_cast<size_t>(std::distance(r.first, r.second));
  8441. }
  8442. inline FormData MultipartFormData::get_file(const std::string &key,
  8443. size_t id) const {
  8444. return detail::get_multimap_value(files, key, id);
  8445. }
  8446. inline std::vector<FormData>
  8447. MultipartFormData::get_files(const std::string &key) const {
  8448. std::vector<FormData> values;
  8449. auto rng = files.equal_range(key);
  8450. for (auto it = rng.first; it != rng.second; it++) {
  8451. values.push_back(it->second);
  8452. }
  8453. return values;
  8454. }
  8455. inline bool MultipartFormData::has_file(const std::string &key) const {
  8456. return files.find(key) != files.end();
  8457. }
  8458. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8459. auto r = files.equal_range(key);
  8460. return static_cast<size_t>(std::distance(r.first, r.second));
  8461. }
  8462. // Multipart FormData writer implementation
  8463. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8464. return detail::is_multipart_boundary_chars_valid(boundary);
  8465. }
  8466. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8467. : boundary_(detail::make_multipart_data_boundary()) {}
  8468. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8469. : boundary_(std::move(boundary)) {}
  8470. inline const std::string &MultipartFormDataWriter::boundary() const {
  8471. return boundary_;
  8472. }
  8473. inline std::string MultipartFormDataWriter::content_type() const {
  8474. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8475. }
  8476. inline std::string
  8477. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8478. return detail::serialize_multipart_formdata(items, boundary_);
  8479. }
  8480. inline size_t MultipartFormDataWriter::content_length(
  8481. const UploadFormDataItems &items) const {
  8482. return detail::get_multipart_content_length(items, boundary_);
  8483. }
  8484. inline std::string
  8485. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8486. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8487. }
  8488. inline std::string MultipartFormDataWriter::item_end() {
  8489. return detail::serialize_multipart_formdata_item_end();
  8490. }
  8491. inline std::string MultipartFormDataWriter::finish() const {
  8492. return detail::serialize_multipart_formdata_finish(boundary_);
  8493. }
  8494. // Response implementation
  8495. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8496. size_t id) const {
  8497. return detail::get_header_value_u64(headers, key, def, id);
  8498. }
  8499. inline bool Response::has_header(const std::string &key) const {
  8500. return headers.find(key) != headers.end();
  8501. }
  8502. inline std::string Response::get_header_value(const std::string &key,
  8503. const char *def,
  8504. size_t id) const {
  8505. return detail::get_header_value(headers, key, def, id);
  8506. }
  8507. inline size_t Response::get_header_value_count(const std::string &key) const {
  8508. return detail::get_header_value_count(headers, key);
  8509. }
  8510. inline void Response::set_header(const std::string &key,
  8511. const std::string &val) {
  8512. detail::set_header(headers, key, val);
  8513. }
  8514. inline bool Response::has_trailer(const std::string &key) const {
  8515. return trailers.find(key) != trailers.end();
  8516. }
  8517. inline std::string Response::get_trailer_value(const std::string &key,
  8518. size_t id) const {
  8519. return detail::get_multimap_value(trailers, key, id);
  8520. }
  8521. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8522. auto r = trailers.equal_range(key);
  8523. return static_cast<size_t>(std::distance(r.first, r.second));
  8524. }
  8525. inline void Response::set_redirect(const std::string &url, int stat) {
  8526. if (detail::fields::is_field_value(url)) {
  8527. set_header("Location", url);
  8528. if (300 <= stat && stat < 400) {
  8529. this->status = stat;
  8530. } else {
  8531. this->status = StatusCode::Found_302;
  8532. }
  8533. }
  8534. }
  8535. inline void Response::set_content(const char *s, size_t n,
  8536. const std::string &content_type) {
  8537. body.assign(s, n);
  8538. auto rng = headers.equal_range("Content-Type");
  8539. headers.erase(rng.first, rng.second);
  8540. set_header("Content-Type", content_type);
  8541. }
  8542. inline void Response::set_content(const std::string &s,
  8543. const std::string &content_type) {
  8544. set_content(s.data(), s.size(), content_type);
  8545. }
  8546. inline void Response::set_content(std::string &&s,
  8547. const std::string &content_type) {
  8548. body = std::move(s);
  8549. auto rng = headers.equal_range("Content-Type");
  8550. headers.erase(rng.first, rng.second);
  8551. set_header("Content-Type", content_type);
  8552. }
  8553. inline void Response::set_content_provider(
  8554. size_t in_length, const std::string &content_type, ContentProvider provider,
  8555. ContentProviderResourceReleaser resource_releaser) {
  8556. set_header("Content-Type", content_type);
  8557. content_length_ = in_length;
  8558. if (in_length > 0) { content_provider_ = std::move(provider); }
  8559. content_provider_resource_releaser_ = std::move(resource_releaser);
  8560. is_chunked_content_provider_ = false;
  8561. }
  8562. inline void Response::set_content_provider(
  8563. const std::string &content_type, ContentProviderWithoutLength provider,
  8564. ContentProviderResourceReleaser resource_releaser) {
  8565. set_header("Content-Type", content_type);
  8566. content_length_ = 0;
  8567. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8568. content_provider_resource_releaser_ = std::move(resource_releaser);
  8569. is_chunked_content_provider_ = false;
  8570. }
  8571. inline void Response::set_chunked_content_provider(
  8572. const std::string &content_type, ContentProviderWithoutLength provider,
  8573. ContentProviderResourceReleaser resource_releaser) {
  8574. set_header("Content-Type", content_type);
  8575. content_length_ = 0;
  8576. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8577. content_provider_resource_releaser_ = std::move(resource_releaser);
  8578. is_chunked_content_provider_ = true;
  8579. }
  8580. inline void Response::set_file_content(const std::string &path,
  8581. const std::string &content_type) {
  8582. file_content_path_ = path;
  8583. file_content_content_type_ = content_type;
  8584. }
  8585. inline void Response::set_file_content(const std::string &path) {
  8586. file_content_path_ = path;
  8587. }
  8588. // Result implementation
  8589. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8590. size_t def,
  8591. size_t id) const {
  8592. return detail::get_header_value_u64(request_headers_, key, def, id);
  8593. }
  8594. inline bool Result::has_request_header(const std::string &key) const {
  8595. return request_headers_.find(key) != request_headers_.end();
  8596. }
  8597. inline std::string Result::get_request_header_value(const std::string &key,
  8598. const char *def,
  8599. size_t id) const {
  8600. return detail::get_header_value(request_headers_, key, def, id);
  8601. }
  8602. inline size_t
  8603. Result::get_request_header_value_count(const std::string &key) const {
  8604. auto r = request_headers_.equal_range(key);
  8605. return static_cast<size_t>(std::distance(r.first, r.second));
  8606. }
  8607. // Stream implementation
  8608. inline ssize_t Stream::write(const char *ptr) {
  8609. return write(ptr, strlen(ptr));
  8610. }
  8611. inline ssize_t Stream::write(const std::string &s) {
  8612. return write(s.data(), s.size());
  8613. }
  8614. // BodyReader implementation
  8615. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8616. if (!stream) {
  8617. last_error = Error::Connection;
  8618. return -1;
  8619. }
  8620. if (eof) { return 0; }
  8621. if (!chunked) {
  8622. // Content-Length based reading
  8623. if (has_content_length && bytes_read >= content_length) {
  8624. eof = true;
  8625. return 0;
  8626. }
  8627. auto to_read = len;
  8628. if (has_content_length) {
  8629. auto remaining = content_length - bytes_read;
  8630. to_read = (std::min)(len, remaining);
  8631. }
  8632. auto n = stream->read(buf, to_read);
  8633. if (n < 0) {
  8634. last_error = stream->get_error();
  8635. if (last_error == Error::Success) { last_error = Error::Read; }
  8636. eof = true;
  8637. return n;
  8638. }
  8639. if (n == 0) {
  8640. // Unexpected EOF before content_length
  8641. last_error = stream->get_error();
  8642. if (last_error == Error::Success) { last_error = Error::Read; }
  8643. eof = true;
  8644. return 0;
  8645. }
  8646. bytes_read += static_cast<size_t>(n);
  8647. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8648. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8649. last_error = Error::ExceedMaxPayloadSize;
  8650. eof = true;
  8651. return -1;
  8652. }
  8653. return n;
  8654. }
  8655. // Chunked transfer encoding: delegate to shared decoder instance.
  8656. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8657. size_t chunk_offset = 0;
  8658. size_t chunk_total = 0;
  8659. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8660. if (n < 0) {
  8661. last_error = stream->get_error();
  8662. if (last_error == Error::Success) { last_error = Error::Read; }
  8663. eof = true;
  8664. return n;
  8665. }
  8666. if (n == 0) {
  8667. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8668. eof = true;
  8669. return 0;
  8670. }
  8671. bytes_read += static_cast<size_t>(n);
  8672. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8673. last_error = Error::ExceedMaxPayloadSize;
  8674. eof = true;
  8675. return -1;
  8676. }
  8677. return n;
  8678. }
  8679. // ThreadPool implementation
  8680. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8681. time_t idle_timeout_sec)
  8682. : base_thread_count_(n), max_queued_requests_(mqr),
  8683. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8684. shutdown_(false) {
  8685. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8686. if (max_n != 0 && max_n < n) {
  8687. std::string msg = "max_threads must be >= base_threads";
  8688. throw std::invalid_argument(msg);
  8689. }
  8690. #endif
  8691. max_thread_count_ = max_n == 0 ? n : max_n;
  8692. threads_.reserve(base_thread_count_);
  8693. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8694. try {
  8695. #endif
  8696. for (size_t i = 0; i < base_thread_count_; i++) {
  8697. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8698. }
  8699. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8700. } catch (...) {
  8701. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8702. // signal the workers we already spawned to exit and join them so the
  8703. // vector destructor does not see joinable threads (which would call
  8704. // std::terminate). Then rethrow so the caller learns of the failure.
  8705. {
  8706. std::unique_lock<std::mutex> lock(mutex_);
  8707. shutdown_ = true;
  8708. }
  8709. cond_.notify_all();
  8710. for (auto &t : threads_) {
  8711. if (t.joinable()) { t.join(); }
  8712. }
  8713. throw;
  8714. }
  8715. #endif
  8716. }
  8717. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8718. {
  8719. std::unique_lock<std::mutex> lock(mutex_);
  8720. if (shutdown_) { return false; }
  8721. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8722. return false;
  8723. }
  8724. jobs_.push_back(std::move(fn));
  8725. // Spawn a dynamic thread if no idle threads and under max
  8726. if (idle_thread_count_ == 0 &&
  8727. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8728. cleanup_finished_threads();
  8729. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8730. }
  8731. }
  8732. cond_.notify_one();
  8733. return true;
  8734. }
  8735. inline void ThreadPool::shutdown() {
  8736. {
  8737. std::unique_lock<std::mutex> lock(mutex_);
  8738. shutdown_ = true;
  8739. }
  8740. cond_.notify_all();
  8741. for (auto &t : threads_) {
  8742. if (t.joinable()) { t.join(); }
  8743. }
  8744. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8745. // with worker threads that call move_to_finished() concurrently.
  8746. std::list<std::thread> remaining_dynamic;
  8747. {
  8748. std::unique_lock<std::mutex> lock(mutex_);
  8749. remaining_dynamic = std::move(dynamic_threads_);
  8750. }
  8751. for (auto &t : remaining_dynamic) {
  8752. if (t.joinable()) { t.join(); }
  8753. }
  8754. std::unique_lock<std::mutex> lock(mutex_);
  8755. cleanup_finished_threads();
  8756. }
  8757. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8758. // Must be called with mutex_ held
  8759. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8760. if (it->get_id() == id) {
  8761. finished_threads_.push_back(std::move(*it));
  8762. dynamic_threads_.erase(it);
  8763. return;
  8764. }
  8765. }
  8766. }
  8767. inline void ThreadPool::cleanup_finished_threads() {
  8768. // Must be called with mutex_ held
  8769. for (auto &t : finished_threads_) {
  8770. if (t.joinable()) { t.join(); }
  8771. }
  8772. finished_threads_.clear();
  8773. }
  8774. inline void ThreadPool::worker(bool is_dynamic) {
  8775. for (;;) {
  8776. std::function<void()> fn;
  8777. {
  8778. std::unique_lock<std::mutex> lock(mutex_);
  8779. idle_thread_count_++;
  8780. if (is_dynamic) {
  8781. auto has_work =
  8782. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8783. [&] { return !jobs_.empty() || shutdown_; });
  8784. if (!has_work) {
  8785. // Timed out with no work - exit this dynamic thread
  8786. idle_thread_count_--;
  8787. move_to_finished(std::this_thread::get_id());
  8788. break;
  8789. }
  8790. } else {
  8791. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8792. }
  8793. idle_thread_count_--;
  8794. if (shutdown_ && jobs_.empty()) { break; }
  8795. fn = std::move(jobs_.front());
  8796. jobs_.pop_front();
  8797. }
  8798. assert(true == static_cast<bool>(fn));
  8799. fn();
  8800. }
  8801. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8802. !defined(LIBRESSL_VERSION_NUMBER)
  8803. OPENSSL_thread_stop();
  8804. #endif
  8805. }
  8806. /*
  8807. * Group 1 (continued): detail namespace - Stream implementations
  8808. */
  8809. namespace detail {
  8810. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8811. time_t timeout_sec, time_t timeout_usec,
  8812. time_t &actual_timeout_sec,
  8813. time_t &actual_timeout_usec) {
  8814. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8815. auto actual_timeout_msec =
  8816. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8817. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8818. actual_timeout_sec = actual_timeout_msec / 1000;
  8819. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8820. }
  8821. // Socket stream implementation
  8822. inline SocketStream::SocketStream(
  8823. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8824. time_t write_timeout_sec, time_t write_timeout_usec,
  8825. time_t max_timeout_msec,
  8826. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8827. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8828. read_timeout_usec_(read_timeout_usec),
  8829. write_timeout_sec_(write_timeout_sec),
  8830. write_timeout_usec_(write_timeout_usec),
  8831. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8832. read_buff_(read_buff_size_, 0) {}
  8833. inline SocketStream::~SocketStream() = default;
  8834. inline bool SocketStream::is_readable() const {
  8835. return read_buff_off_ < read_buff_content_size_;
  8836. }
  8837. inline bool SocketStream::wait_readable() const {
  8838. if (max_timeout_msec_ <= 0) {
  8839. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8840. }
  8841. time_t read_timeout_sec;
  8842. time_t read_timeout_usec;
  8843. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8844. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8845. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8846. }
  8847. inline bool SocketStream::wait_writable() const {
  8848. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8849. }
  8850. inline bool SocketStream::is_peer_alive() const {
  8851. return detail::is_socket_alive(sock_);
  8852. }
  8853. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8854. #ifdef _WIN32
  8855. size =
  8856. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8857. #else
  8858. size = (std::min)(size,
  8859. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8860. #endif
  8861. if (read_buff_off_ < read_buff_content_size_) {
  8862. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8863. if (size <= remaining_size) {
  8864. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8865. read_buff_off_ += size;
  8866. return static_cast<ssize_t>(size);
  8867. } else {
  8868. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8869. read_buff_off_ += remaining_size;
  8870. return static_cast<ssize_t>(remaining_size);
  8871. }
  8872. }
  8873. if (!wait_readable()) {
  8874. error_ = Error::Timeout;
  8875. return -1;
  8876. }
  8877. read_buff_off_ = 0;
  8878. read_buff_content_size_ = 0;
  8879. if (size < read_buff_size_) {
  8880. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8881. CPPHTTPLIB_RECV_FLAGS);
  8882. if (n <= 0) {
  8883. if (n == 0) {
  8884. error_ = Error::ConnectionClosed;
  8885. } else {
  8886. error_ = Error::Read;
  8887. }
  8888. return n;
  8889. } else if (n <= static_cast<ssize_t>(size)) {
  8890. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8891. return n;
  8892. } else {
  8893. memcpy(ptr, read_buff_.data(), size);
  8894. read_buff_off_ = size;
  8895. read_buff_content_size_ = static_cast<size_t>(n);
  8896. return static_cast<ssize_t>(size);
  8897. }
  8898. } else {
  8899. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8900. if (n <= 0) {
  8901. if (n == 0) {
  8902. error_ = Error::ConnectionClosed;
  8903. } else {
  8904. error_ = Error::Read;
  8905. }
  8906. }
  8907. return n;
  8908. }
  8909. }
  8910. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8911. if (!wait_writable()) { return -1; }
  8912. #if defined(_WIN32) && !defined(_WIN64)
  8913. size =
  8914. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8915. #endif
  8916. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8917. }
  8918. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8919. int &port) const {
  8920. return detail::get_remote_ip_and_port(sock_, ip, port);
  8921. }
  8922. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8923. int &port) const {
  8924. return detail::get_local_ip_and_port(sock_, ip, port);
  8925. }
  8926. inline socket_t SocketStream::socket() const { return sock_; }
  8927. inline time_t SocketStream::duration() const {
  8928. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8929. std::chrono::steady_clock::now() - start_time_)
  8930. .count();
  8931. }
  8932. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8933. read_timeout_sec_ = sec;
  8934. read_timeout_usec_ = usec;
  8935. }
  8936. // Buffer stream implementation
  8937. inline bool BufferStream::is_readable() const { return true; }
  8938. inline bool BufferStream::wait_readable() const { return true; }
  8939. inline bool BufferStream::wait_writable() const { return true; }
  8940. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8941. #if defined(_MSC_VER) && _MSC_VER < 1910
  8942. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8943. #else
  8944. auto len_read = buffer.copy(ptr, size, position);
  8945. #endif
  8946. position += static_cast<size_t>(len_read);
  8947. return static_cast<ssize_t>(len_read);
  8948. }
  8949. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8950. buffer.append(ptr, size);
  8951. return static_cast<ssize_t>(size);
  8952. }
  8953. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8954. int & /*port*/) const {}
  8955. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8956. int & /*port*/) const {}
  8957. inline socket_t BufferStream::socket() const { return 0; }
  8958. inline time_t BufferStream::duration() const { return 0; }
  8959. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8960. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8961. : MatcherBase(pattern) {
  8962. constexpr const char marker[] = "/:";
  8963. // One past the last ending position of a path param substring
  8964. std::size_t last_param_end = 0;
  8965. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8966. // Needed to ensure that parameter names are unique during matcher
  8967. // construction
  8968. // If exceptions are disabled, only last duplicate path
  8969. // parameter will be set
  8970. std::unordered_set<std::string> param_name_set;
  8971. #endif
  8972. while (true) {
  8973. const auto marker_pos = pattern.find(
  8974. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8975. if (marker_pos == std::string::npos) { break; }
  8976. static_fragments_.push_back(
  8977. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8978. const auto param_name_start = marker_pos + str_len(marker);
  8979. auto sep_pos = pattern.find(separator, param_name_start);
  8980. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8981. auto param_name =
  8982. pattern.substr(param_name_start, sep_pos - param_name_start);
  8983. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8984. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8985. std::string msg = "Encountered path parameter '" + param_name +
  8986. "' multiple times in route pattern '" + pattern + "'.";
  8987. throw std::invalid_argument(msg);
  8988. }
  8989. #endif
  8990. param_names_.push_back(std::move(param_name));
  8991. last_param_end = sep_pos + 1;
  8992. }
  8993. if (last_param_end < pattern.length()) {
  8994. static_fragments_.push_back(pattern.substr(last_param_end));
  8995. }
  8996. }
  8997. inline bool PathParamsMatcher::match(Request &request) const {
  8998. request.matches = std::smatch();
  8999. request.path_params.clear();
  9000. request.path_params.reserve(param_names_.size());
  9001. // One past the position at which the path matched the pattern last time
  9002. std::size_t starting_pos = 0;
  9003. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  9004. const auto &fragment = static_fragments_[i];
  9005. if (starting_pos + fragment.length() > request.path.length()) {
  9006. return false;
  9007. }
  9008. // Avoid unnecessary allocation by using strncmp instead of substr +
  9009. // comparison
  9010. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  9011. fragment.length()) != 0) {
  9012. return false;
  9013. }
  9014. starting_pos += fragment.length();
  9015. // Should only happen when we have a static fragment after a param
  9016. // Example: '/users/:id/subscriptions'
  9017. // The 'subscriptions' fragment here does not have a corresponding param
  9018. if (i >= param_names_.size()) { continue; }
  9019. auto sep_pos = request.path.find(separator, starting_pos);
  9020. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  9021. const auto &param_name = param_names_[i];
  9022. request.path_params.emplace(
  9023. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  9024. // Mark everything up to '/' as matched
  9025. starting_pos = sep_pos + 1;
  9026. }
  9027. // Returns false if the path is longer than the pattern
  9028. return starting_pos >= request.path.length();
  9029. }
  9030. inline bool RegexMatcher::match(Request &request) const {
  9031. request.path_params.clear();
  9032. return std::regex_match(request.path, request.matches, regex_);
  9033. }
  9034. // Enclose IPv6 address in brackets if needed
  9035. inline std::string prepare_host_string(const std::string &host) {
  9036. // Enclose IPv6 address in brackets (but not if already enclosed)
  9037. if (host.find(':') == std::string::npos ||
  9038. (!host.empty() && host[0] == '[')) {
  9039. // IPv4, hostname, or already bracketed IPv6
  9040. return host;
  9041. } else {
  9042. // IPv6 address without brackets
  9043. return "[" + host + "]";
  9044. }
  9045. }
  9046. inline std::string make_host_and_port_string(const std::string &host, int port,
  9047. bool is_ssl) {
  9048. auto result = prepare_host_string(host);
  9049. // Append port if not default
  9050. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9051. ; // do nothing
  9052. } else {
  9053. result += ":" + std::to_string(port);
  9054. }
  9055. return result;
  9056. }
  9057. // Create "host:port" string always including port number (for CONNECT method)
  9058. inline std::string
  9059. make_host_and_port_string_always_port(const std::string &host, int port) {
  9060. return prepare_host_string(host) + ":" + std::to_string(port);
  9061. }
  9062. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9063. NormalizedTarget normalize_target(const std::string &host);
  9064. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9065. bool host_matches_no_proxy(const NormalizedTarget &target,
  9066. const std::vector<NoProxyEntry> &entries);
  9067. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9068. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9069. if (prefix_bits == 0) { return true; }
  9070. int full_bytes = prefix_bits / 8;
  9071. int rem_bits = prefix_bits % 8;
  9072. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9073. static_cast<size_t>(full_bytes)) != 0) {
  9074. return false;
  9075. }
  9076. if (rem_bits == 0) { return true; }
  9077. auto i = static_cast<size_t>(full_bytes);
  9078. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9079. return (ip[i] & mask) == (net[i] & mask);
  9080. }
  9081. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9082. if (token.empty()) { return false; }
  9083. if (token == "*") {
  9084. out.kind = NoProxyKind::Wildcard;
  9085. return true;
  9086. }
  9087. auto slash = token.find('/');
  9088. std::string addr_part =
  9089. (slash == std::string::npos) ? token : token.substr(0, slash);
  9090. std::string prefix_part =
  9091. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9092. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9093. // don't silently treat it as a /32 (or /128).
  9094. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9095. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9096. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9097. // when brackets are present.
  9098. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9099. addr_part.back() == ']';
  9100. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9101. if (!bracketed) {
  9102. struct in_addr v4;
  9103. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9104. int prefix = 32;
  9105. if (!prefix_part.empty()) {
  9106. auto r = from_chars(prefix_part.data(),
  9107. prefix_part.data() + prefix_part.size(), prefix);
  9108. if (r.ec != std::errc{} ||
  9109. r.ptr != prefix_part.data() + prefix_part.size()) {
  9110. return false;
  9111. }
  9112. if (prefix < 0 || prefix > 32) { return false; }
  9113. }
  9114. out.kind = NoProxyKind::IPv4Cidr;
  9115. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9116. out.prefix_bits = prefix;
  9117. return true;
  9118. }
  9119. }
  9120. struct in6_addr v6;
  9121. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9122. int prefix = 128;
  9123. if (!prefix_part.empty()) {
  9124. auto r = from_chars(prefix_part.data(),
  9125. prefix_part.data() + prefix_part.size(), prefix);
  9126. if (r.ec != std::errc{} ||
  9127. r.ptr != prefix_part.data() + prefix_part.size()) {
  9128. return false;
  9129. }
  9130. if (prefix < 0 || prefix > 128) { return false; }
  9131. }
  9132. out.kind = NoProxyKind::IPv6Cidr;
  9133. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9134. out.prefix_bits = prefix;
  9135. return true;
  9136. }
  9137. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9138. // the entry is malformed — don't fall through to the hostname branch.
  9139. if (bracketed) { return false; }
  9140. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9141. if (slash != std::string::npos) { return false; }
  9142. // Port-specific entries (host:port) are not supported.
  9143. if (token.find(':') != std::string::npos) { return false; }
  9144. std::string hostname = case_ignore::to_lower(token);
  9145. while (!hostname.empty() && hostname.front() == '.') {
  9146. hostname.erase(hostname.begin());
  9147. }
  9148. while (!hostname.empty() && hostname.back() == '.') {
  9149. hostname.pop_back();
  9150. }
  9151. if (hostname.empty()) { return false; }
  9152. out.kind = NoProxyKind::HostnameSuffix;
  9153. out.hostname_pattern = std::move(hostname);
  9154. return true;
  9155. }
  9156. inline NormalizedTarget normalize_target(const std::string &host) {
  9157. NormalizedTarget t;
  9158. std::string h = host;
  9159. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9160. h = h.substr(1, h.size() - 2);
  9161. }
  9162. // Strip a single trailing dot so "example.com." canonicalizes to
  9163. // "example.com".
  9164. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9165. t.hostname = case_ignore::to_lower(h);
  9166. if (!t.hostname.empty()) {
  9167. struct in_addr v4;
  9168. struct in6_addr v6;
  9169. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9170. t.is_ipv4 = true;
  9171. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9172. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9173. t.is_ipv6 = true;
  9174. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9175. }
  9176. }
  9177. return t;
  9178. }
  9179. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9180. const std::vector<NoProxyEntry> &entries) {
  9181. if (target.hostname.empty()) { return false; }
  9182. for (const auto &e : entries) {
  9183. switch (e.kind) {
  9184. case NoProxyKind::Wildcard: return true;
  9185. case NoProxyKind::IPv4Cidr:
  9186. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9187. return true;
  9188. }
  9189. break;
  9190. case NoProxyKind::IPv6Cidr:
  9191. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9192. return true;
  9193. }
  9194. break;
  9195. case NoProxyKind::HostnameSuffix:
  9196. if (target.is_ipv4 || target.is_ipv6) { break; }
  9197. if (target.hostname == e.hostname_pattern) { return true; }
  9198. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9199. // an entry of "example.com".
  9200. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9201. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9202. if (target.hostname[offset - 1] == '.' &&
  9203. target.hostname.compare(offset, e.hostname_pattern.size(),
  9204. e.hostname_pattern) == 0) {
  9205. return true;
  9206. }
  9207. }
  9208. break;
  9209. }
  9210. }
  9211. return false;
  9212. }
  9213. template <typename T>
  9214. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9215. T header_writer, Error &error) {
  9216. for (const auto &h : headers) {
  9217. if (!detail::fields::is_field_name(h.first) ||
  9218. !detail::fields::is_field_value(h.second)) {
  9219. error = Error::InvalidHeaders;
  9220. return false;
  9221. }
  9222. }
  9223. if (header_writer(strm, headers) <= 0) {
  9224. error = Error::Write;
  9225. return false;
  9226. }
  9227. return true;
  9228. }
  9229. } // namespace detail
  9230. /*
  9231. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9232. */
  9233. #ifdef CPPHTTPLIB_SSL_ENABLED
  9234. namespace detail {
  9235. // SSL socket stream implementation
  9236. inline SSLSocketStream::SSLSocketStream(
  9237. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9238. time_t read_timeout_usec, time_t write_timeout_sec,
  9239. time_t write_timeout_usec, time_t max_timeout_msec,
  9240. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9241. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9242. read_timeout_usec_(read_timeout_usec),
  9243. write_timeout_sec_(write_timeout_sec),
  9244. write_timeout_usec_(write_timeout_usec),
  9245. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9246. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9247. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9248. // Note: create_session() also clears this, but SSLClient currently
  9249. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9250. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9251. // SSL session was created.
  9252. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9253. #endif
  9254. }
  9255. inline SSLSocketStream::~SSLSocketStream() = default;
  9256. inline bool SSLSocketStream::is_readable() const {
  9257. return tls::pending(session_) > 0;
  9258. }
  9259. inline bool SSLSocketStream::wait_readable() const {
  9260. if (max_timeout_msec_ <= 0) {
  9261. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9262. }
  9263. time_t read_timeout_sec;
  9264. time_t read_timeout_usec;
  9265. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9266. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9267. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9268. }
  9269. inline bool SSLSocketStream::wait_writable() const {
  9270. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9271. !tls::is_peer_closed(session_, sock_);
  9272. }
  9273. inline bool SSLSocketStream::is_peer_alive() const {
  9274. return !tls::is_peer_closed(session_, sock_);
  9275. }
  9276. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9277. if (tls::pending(session_) > 0) {
  9278. tls::TlsError err;
  9279. auto ret = tls::read(session_, ptr, size, err);
  9280. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9281. error_ = Error::ConnectionClosed;
  9282. }
  9283. return ret;
  9284. } else if (wait_readable()) {
  9285. tls::TlsError err;
  9286. auto ret = tls::read(session_, ptr, size, err);
  9287. if (ret < 0) {
  9288. auto n = 1000;
  9289. #ifdef _WIN32
  9290. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9291. (err.code == tls::ErrorCode::SyscallError &&
  9292. WSAGetLastError() == WSAETIMEDOUT))) {
  9293. #else
  9294. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9295. #endif
  9296. if (tls::pending(session_) > 0) {
  9297. return tls::read(session_, ptr, size, err);
  9298. } else if (wait_readable()) {
  9299. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9300. ret = tls::read(session_, ptr, size, err);
  9301. if (ret >= 0) { return ret; }
  9302. } else {
  9303. break;
  9304. }
  9305. }
  9306. assert(ret < 0);
  9307. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9308. error_ = Error::ConnectionClosed;
  9309. }
  9310. return ret;
  9311. } else {
  9312. error_ = Error::Timeout;
  9313. return -1;
  9314. }
  9315. }
  9316. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9317. if (wait_writable()) {
  9318. auto handle_size =
  9319. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9320. tls::TlsError err;
  9321. auto ret = tls::write(session_, ptr, handle_size, err);
  9322. if (ret < 0) {
  9323. auto n = 1000;
  9324. #ifdef _WIN32
  9325. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9326. (err.code == tls::ErrorCode::SyscallError &&
  9327. WSAGetLastError() == WSAETIMEDOUT))) {
  9328. #else
  9329. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9330. #endif
  9331. if (wait_writable()) {
  9332. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9333. ret = tls::write(session_, ptr, handle_size, err);
  9334. if (ret >= 0) { return ret; }
  9335. } else {
  9336. break;
  9337. }
  9338. }
  9339. assert(ret < 0);
  9340. }
  9341. return ret;
  9342. }
  9343. return -1;
  9344. }
  9345. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9346. int &port) const {
  9347. detail::get_remote_ip_and_port(sock_, ip, port);
  9348. }
  9349. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9350. int &port) const {
  9351. detail::get_local_ip_and_port(sock_, ip, port);
  9352. }
  9353. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9354. inline time_t SSLSocketStream::duration() const {
  9355. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9356. std::chrono::steady_clock::now() - start_time_)
  9357. .count();
  9358. }
  9359. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9360. read_timeout_sec_ = sec;
  9361. read_timeout_usec_ = usec;
  9362. }
  9363. } // namespace detail
  9364. #endif // CPPHTTPLIB_SSL_ENABLED
  9365. /*
  9366. * Group 4: Server implementation
  9367. */
  9368. // HTTP server implementation
  9369. inline Server::Server()
  9370. : new_task_queue([] {
  9371. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9372. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9373. }) {
  9374. #ifndef _WIN32
  9375. signal(SIGPIPE, SIG_IGN);
  9376. #endif
  9377. }
  9378. inline Server::~Server() = default;
  9379. inline std::unique_ptr<detail::MatcherBase>
  9380. Server::make_matcher(const std::string &pattern) {
  9381. if (pattern.find("/:") != std::string::npos) {
  9382. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9383. } else {
  9384. return detail::make_unique<detail::RegexMatcher>(pattern);
  9385. }
  9386. }
  9387. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9388. return add_handler(get_handlers_, pattern, std::move(handler));
  9389. }
  9390. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9391. return add_handler(post_handlers_, pattern, std::move(handler));
  9392. }
  9393. inline Server &Server::Post(const std::string &pattern,
  9394. HandlerWithContentReader handler) {
  9395. return add_handler(post_handlers_for_content_reader_, pattern,
  9396. std::move(handler));
  9397. }
  9398. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9399. return add_handler(put_handlers_, pattern, std::move(handler));
  9400. }
  9401. inline Server &Server::Put(const std::string &pattern,
  9402. HandlerWithContentReader handler) {
  9403. return add_handler(put_handlers_for_content_reader_, pattern,
  9404. std::move(handler));
  9405. }
  9406. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9407. return add_handler(patch_handlers_, pattern, std::move(handler));
  9408. }
  9409. inline Server &Server::Patch(const std::string &pattern,
  9410. HandlerWithContentReader handler) {
  9411. return add_handler(patch_handlers_for_content_reader_, pattern,
  9412. std::move(handler));
  9413. }
  9414. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9415. return add_handler(delete_handlers_, pattern, std::move(handler));
  9416. }
  9417. inline Server &Server::Delete(const std::string &pattern,
  9418. HandlerWithContentReader handler) {
  9419. return add_handler(delete_handlers_for_content_reader_, pattern,
  9420. std::move(handler));
  9421. }
  9422. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9423. return add_handler(options_handlers_, pattern, std::move(handler));
  9424. }
  9425. inline Server &Server::WebSocket(const std::string &pattern,
  9426. WebSocketHandler handler) {
  9427. websocket_handlers_.push_back(
  9428. {make_matcher(pattern), std::move(handler), nullptr});
  9429. return *this;
  9430. }
  9431. inline Server &Server::WebSocket(const std::string &pattern,
  9432. WebSocketHandler handler,
  9433. SubProtocolSelector sub_protocol_selector) {
  9434. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9435. std::move(sub_protocol_selector)});
  9436. return *this;
  9437. }
  9438. inline bool Server::set_base_dir(const std::string &dir,
  9439. const std::string &mount_point) {
  9440. return set_mount_point(mount_point, dir);
  9441. }
  9442. inline bool Server::set_mount_point(const std::string &mount_point,
  9443. const std::string &dir, Headers headers) {
  9444. detail::FileStat stat(dir);
  9445. if (stat.is_dir()) {
  9446. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9447. if (!mnt.empty() && mnt[0] == '/') {
  9448. std::string resolved_base;
  9449. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9450. #if defined(_WIN32)
  9451. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9452. resolved_base += '\\';
  9453. }
  9454. #else
  9455. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9456. #endif
  9457. }
  9458. base_dirs_.push_back(
  9459. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9460. return true;
  9461. }
  9462. }
  9463. return false;
  9464. }
  9465. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9466. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9467. if (it->mount_point == mount_point) {
  9468. base_dirs_.erase(it);
  9469. return true;
  9470. }
  9471. }
  9472. return false;
  9473. }
  9474. inline Server &
  9475. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9476. const std::string &mime) {
  9477. file_extension_and_mimetype_map_[ext] = mime;
  9478. return *this;
  9479. }
  9480. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9481. default_file_mimetype_ = mime;
  9482. return *this;
  9483. }
  9484. inline Server &Server::set_file_request_handler(Handler handler) {
  9485. file_request_handler_ = std::move(handler);
  9486. return *this;
  9487. }
  9488. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9489. std::true_type) {
  9490. error_handler_ = std::move(handler);
  9491. return *this;
  9492. }
  9493. inline Server &Server::set_error_handler_core(Handler handler,
  9494. std::false_type) {
  9495. error_handler_ = [handler](const Request &req, Response &res) {
  9496. handler(req, res);
  9497. return HandlerResponse::Handled;
  9498. };
  9499. return *this;
  9500. }
  9501. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9502. exception_handler_ = std::move(handler);
  9503. return *this;
  9504. }
  9505. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9506. pre_routing_handler_ = std::move(handler);
  9507. return *this;
  9508. }
  9509. inline Server &Server::set_post_routing_handler(Handler handler) {
  9510. post_routing_handler_ = std::move(handler);
  9511. return *this;
  9512. }
  9513. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9514. pre_request_handler_ = std::move(handler);
  9515. return *this;
  9516. }
  9517. inline Server &Server::set_logger(Logger logger) {
  9518. logger_ = std::move(logger);
  9519. return *this;
  9520. }
  9521. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9522. error_logger_ = std::move(error_logger);
  9523. return *this;
  9524. }
  9525. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9526. pre_compression_logger_ = std::move(logger);
  9527. return *this;
  9528. }
  9529. inline Server &
  9530. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9531. expect_100_continue_handler_ = std::move(handler);
  9532. return *this;
  9533. }
  9534. inline Server &Server::set_start_handler(StartHandler handler) {
  9535. start_handler_ = std::move(handler);
  9536. return *this;
  9537. }
  9538. inline Server &Server::set_address_family(int family) {
  9539. address_family_ = family;
  9540. return *this;
  9541. }
  9542. inline Server &Server::set_tcp_nodelay(bool on) {
  9543. tcp_nodelay_ = on;
  9544. return *this;
  9545. }
  9546. inline Server &Server::set_ipv6_v6only(bool on) {
  9547. ipv6_v6only_ = on;
  9548. return *this;
  9549. }
  9550. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9551. socket_options_ = std::move(socket_options);
  9552. return *this;
  9553. }
  9554. inline Server &Server::set_default_headers(Headers headers) {
  9555. default_headers_ = std::move(headers);
  9556. return *this;
  9557. }
  9558. inline Server &Server::set_header_writer(
  9559. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9560. header_writer_ = writer;
  9561. return *this;
  9562. }
  9563. inline Server &
  9564. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9565. trusted_proxies_ = proxies;
  9566. return *this;
  9567. }
  9568. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9569. keep_alive_max_count_ = count;
  9570. return *this;
  9571. }
  9572. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9573. keep_alive_timeout_sec_ = sec;
  9574. return *this;
  9575. }
  9576. template <class Rep, class Period>
  9577. inline Server &Server::set_keep_alive_timeout(
  9578. const std::chrono::duration<Rep, Period> &duration) {
  9579. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9580. set_keep_alive_timeout(sec);
  9581. });
  9582. return *this;
  9583. }
  9584. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9585. read_timeout_sec_ = sec;
  9586. read_timeout_usec_ = usec;
  9587. return *this;
  9588. }
  9589. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9590. write_timeout_sec_ = sec;
  9591. write_timeout_usec_ = usec;
  9592. return *this;
  9593. }
  9594. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9595. idle_interval_sec_ = sec;
  9596. idle_interval_usec_ = usec;
  9597. return *this;
  9598. }
  9599. inline Server &Server::set_payload_max_length(size_t length) {
  9600. payload_max_length_ = length;
  9601. return *this;
  9602. }
  9603. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9604. websocket_max_missed_pongs_ = count;
  9605. return *this;
  9606. }
  9607. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9608. websocket_ping_interval_sec_ = sec;
  9609. return *this;
  9610. }
  9611. template <class Rep, class Period>
  9612. inline Server &Server::set_websocket_ping_interval(
  9613. const std::chrono::duration<Rep, Period> &duration) {
  9614. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9615. set_websocket_ping_interval(sec);
  9616. });
  9617. return *this;
  9618. }
  9619. inline bool Server::bind_to_port(const std::string &host, int port,
  9620. int socket_flags) {
  9621. auto ret = bind_internal(host, port, socket_flags);
  9622. if (ret == -1) { is_decommissioned = true; }
  9623. return ret >= 0;
  9624. }
  9625. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9626. auto ret = bind_internal(host, 0, socket_flags);
  9627. if (ret == -1) { is_decommissioned = true; }
  9628. return ret;
  9629. }
  9630. inline bool Server::listen_after_bind() { return listen_internal(); }
  9631. inline bool Server::listen(const std::string &host, int port,
  9632. int socket_flags) {
  9633. return bind_to_port(host, port, socket_flags) && listen_internal();
  9634. }
  9635. inline bool Server::is_running() const { return is_running_; }
  9636. inline void Server::wait_until_ready() const {
  9637. while (!is_running_ && !is_decommissioned) {
  9638. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9639. }
  9640. }
  9641. inline void Server::stop() noexcept {
  9642. if (is_running_) {
  9643. assert(svr_sock_ != INVALID_SOCKET);
  9644. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9645. detail::shutdown_socket(sock);
  9646. detail::close_socket(sock);
  9647. }
  9648. is_decommissioned = false;
  9649. }
  9650. inline void Server::decommission() { is_decommissioned = true; }
  9651. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9652. auto len = strlen(s);
  9653. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9654. len -= 2;
  9655. {
  9656. size_t count = 0;
  9657. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9658. switch (count) {
  9659. case 0: req.method = std::string(b, e); break;
  9660. case 1: req.target = std::string(b, e); break;
  9661. case 2: req.version = std::string(b, e); break;
  9662. default: break;
  9663. }
  9664. count++;
  9665. });
  9666. if (count != 3) { return false; }
  9667. }
  9668. thread_local const std::set<std::string> methods{
  9669. "GET", "HEAD", "POST", "PUT", "DELETE",
  9670. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9671. if (methods.find(req.method) == methods.end()) {
  9672. output_error_log(Error::InvalidHTTPMethod, &req);
  9673. return false;
  9674. }
  9675. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9676. output_error_log(Error::InvalidHTTPVersion, &req);
  9677. return false;
  9678. }
  9679. {
  9680. // Skip URL fragment
  9681. for (size_t i = 0; i < req.target.size(); i++) {
  9682. if (req.target[i] == '#') {
  9683. req.target.erase(i);
  9684. break;
  9685. }
  9686. }
  9687. detail::divide(req.target, '?',
  9688. [&](const char *lhs_data, std::size_t lhs_size,
  9689. const char *rhs_data, std::size_t rhs_size) {
  9690. req.path =
  9691. decode_path_component(std::string(lhs_data, lhs_size));
  9692. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9693. });
  9694. }
  9695. return true;
  9696. }
  9697. inline bool Server::write_response(Stream &strm, bool close_connection,
  9698. Request &req, Response &res) {
  9699. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9700. // incorrectly to the error content.
  9701. req.ranges.clear();
  9702. return write_response_core(strm, close_connection, req, res, false);
  9703. }
  9704. inline bool Server::write_response_with_content(Stream &strm,
  9705. bool close_connection,
  9706. const Request &req,
  9707. Response &res) {
  9708. return write_response_core(strm, close_connection, req, res, true);
  9709. }
  9710. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9711. const Request &req, Response &res,
  9712. bool need_apply_ranges) {
  9713. assert(res.status != -1);
  9714. if (400 <= res.status && error_handler_ &&
  9715. error_handler_(req, res) == HandlerResponse::Handled) {
  9716. need_apply_ranges = true;
  9717. }
  9718. std::string content_type;
  9719. std::string boundary;
  9720. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9721. // Prepare additional headers
  9722. if (close_connection || req.get_header_value("Connection") == "close" ||
  9723. 400 <= res.status) { // Don't leave connections open after errors
  9724. res.set_header("Connection", "close");
  9725. } else {
  9726. std::string s = "timeout=";
  9727. s += std::to_string(keep_alive_timeout_sec_);
  9728. s += ", max=";
  9729. s += std::to_string(keep_alive_max_count_);
  9730. res.set_header("Keep-Alive", s);
  9731. }
  9732. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9733. !res.has_header("Content-Type")) {
  9734. res.set_header("Content-Type", "text/plain");
  9735. }
  9736. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9737. !res.has_header("Content-Length")) {
  9738. res.set_header("Content-Length", "0");
  9739. }
  9740. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9741. res.set_header("Accept-Ranges", "bytes");
  9742. }
  9743. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9744. // Response line and headers
  9745. detail::BufferStream bstrm;
  9746. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9747. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9748. // Combine small body with headers to reduce write syscalls
  9749. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9750. bstrm.write(res.body.data(), res.body.size());
  9751. }
  9752. // Log before writing to avoid race condition with client-side code that
  9753. // accesses logger-captured data immediately after receiving the response.
  9754. output_log(req, res);
  9755. // Flush buffer
  9756. auto &data = bstrm.get_buffer();
  9757. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9758. // Streaming body
  9759. auto ret = true;
  9760. if (req.method != "HEAD" && res.content_provider_) {
  9761. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9762. res.content_provider_success_ = true;
  9763. } else {
  9764. ret = false;
  9765. }
  9766. }
  9767. return ret;
  9768. }
  9769. inline bool
  9770. Server::write_content_with_provider(Stream &strm, const Request &req,
  9771. Response &res, const std::string &boundary,
  9772. const std::string &content_type) {
  9773. auto is_shutting_down = [this]() {
  9774. return this->svr_sock_ == INVALID_SOCKET;
  9775. };
  9776. if (res.content_length_ > 0) {
  9777. if (req.ranges.empty()) {
  9778. return detail::write_content(strm, res.content_provider_, 0,
  9779. res.content_length_, is_shutting_down);
  9780. } else if (req.ranges.size() == 1) {
  9781. auto offset_and_length = detail::get_range_offset_and_length(
  9782. req.ranges[0], res.content_length_);
  9783. return detail::write_content(strm, res.content_provider_,
  9784. offset_and_length.first,
  9785. offset_and_length.second, is_shutting_down);
  9786. } else {
  9787. return detail::write_multipart_ranges_data(
  9788. strm, req, res, boundary, content_type, res.content_length_,
  9789. is_shutting_down);
  9790. }
  9791. } else {
  9792. if (res.is_chunked_content_provider_) {
  9793. auto type = detail::encoding_type(req, res);
  9794. auto compressor = detail::make_compressor(type);
  9795. if (!compressor) {
  9796. compressor = detail::make_unique<detail::nocompressor>();
  9797. }
  9798. return detail::write_content_chunked(strm, res.content_provider_,
  9799. is_shutting_down, *compressor);
  9800. } else {
  9801. return detail::write_content_without_length(strm, res.content_provider_,
  9802. is_shutting_down);
  9803. }
  9804. }
  9805. }
  9806. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9807. FormFields::iterator cur_field;
  9808. FormFiles::iterator cur_file;
  9809. auto is_text_field = false;
  9810. size_t count = 0;
  9811. if (read_content_core(
  9812. strm, req, res,
  9813. // Regular
  9814. [&](const char *buf, size_t n) {
  9815. // Prevent arithmetic overflow when checking sizes.
  9816. // Avoid computing (req.body.size() + n) directly because
  9817. // adding two unsigned `size_t` values can wrap around and
  9818. // produce a small result instead of indicating overflow.
  9819. // Instead, check using subtraction: ensure `n` does not
  9820. // exceed the remaining capacity `max_size() - size()`.
  9821. if (req.body.size() >= req.body.max_size() ||
  9822. n > req.body.max_size() - req.body.size()) {
  9823. return false;
  9824. }
  9825. // Limit decompressed body size to payload_max_length_ to protect
  9826. // against "zip bomb" attacks where a small compressed payload
  9827. // decompresses to a massive size.
  9828. if (payload_max_length_ > 0 &&
  9829. (req.body.size() >= payload_max_length_ ||
  9830. n > payload_max_length_ - req.body.size())) {
  9831. return false;
  9832. }
  9833. req.body.append(buf, n);
  9834. return true;
  9835. },
  9836. // Multipart FormData
  9837. [&](const FormData &file) {
  9838. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9839. output_error_log(Error::TooManyFormDataFiles, &req);
  9840. return false;
  9841. }
  9842. if (file.filename.empty()) {
  9843. cur_field = req.form.fields.emplace(
  9844. file.name, FormField{file.name, file.content, file.headers});
  9845. is_text_field = true;
  9846. } else {
  9847. cur_file = req.form.files.emplace(file.name, file);
  9848. is_text_field = false;
  9849. }
  9850. return true;
  9851. },
  9852. [&](const char *buf, size_t n) {
  9853. if (is_text_field) {
  9854. auto &content = cur_field->second.content;
  9855. if (content.size() + n > content.max_size()) { return false; }
  9856. content.append(buf, n);
  9857. } else {
  9858. auto &content = cur_file->second.content;
  9859. if (content.size() + n > content.max_size()) { return false; }
  9860. content.append(buf, n);
  9861. }
  9862. return true;
  9863. })) {
  9864. const auto &content_type = req.get_header_value("Content-Type");
  9865. if (detail::extract_media_type(content_type) ==
  9866. "application/x-www-form-urlencoded") {
  9867. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9868. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9869. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9870. return false;
  9871. }
  9872. detail::parse_query_text(req.body, req.params);
  9873. }
  9874. return true;
  9875. }
  9876. return false;
  9877. }
  9878. inline bool Server::read_content_with_content_receiver(
  9879. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9880. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9881. return read_content_core(strm, req, res, std::move(receiver),
  9882. std::move(multipart_header),
  9883. std::move(multipart_receiver));
  9884. }
  9885. inline bool Server::read_content_core(
  9886. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9887. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9888. detail::FormDataParser multipart_form_data_parser;
  9889. ContentReceiverWithProgress out;
  9890. if (req.is_multipart_form_data()) {
  9891. const auto &content_type = req.get_header_value("Content-Type");
  9892. std::string boundary;
  9893. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9894. res.status = StatusCode::BadRequest_400;
  9895. output_error_log(Error::MultipartParsing, &req);
  9896. return false;
  9897. }
  9898. multipart_form_data_parser.set_boundary(std::move(boundary));
  9899. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9900. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9901. multipart_receiver);
  9902. };
  9903. } else {
  9904. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9905. size_t /*len*/) { return receiver(buf, n); };
  9906. }
  9907. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9908. // For non-SSL builds we still scan non-persistent connections for stray
  9909. // body bytes so the payload limit is enforced (413). On keep-alive,
  9910. // pending bytes may be the next request (issue #2450), so skip.
  9911. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9912. if (!req.has_header("Content-Length") &&
  9913. !detail::is_chunked_transfer_encoding(req.headers)) {
  9914. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9915. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9916. auto has_data = strm.is_readable();
  9917. if (!has_data) {
  9918. auto s = strm.socket();
  9919. if (s != INVALID_SOCKET) {
  9920. has_data = detail::select_read(s, 0, 0) > 0;
  9921. }
  9922. }
  9923. if (has_data) {
  9924. auto result =
  9925. detail::read_content_without_length(strm, payload_max_length_, out);
  9926. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9927. res.status = StatusCode::PayloadTooLarge_413;
  9928. return false;
  9929. } else if (result != detail::ReadContentResult::Success) {
  9930. return false;
  9931. }
  9932. return true;
  9933. }
  9934. }
  9935. return true;
  9936. }
  9937. #else
  9938. if (!req.has_header("Content-Length") &&
  9939. !detail::is_chunked_transfer_encoding(req.headers)) {
  9940. return true;
  9941. }
  9942. #endif
  9943. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9944. out, true)) {
  9945. return false;
  9946. }
  9947. req.body_consumed_ = true;
  9948. if (req.is_multipart_form_data()) {
  9949. if (!multipart_form_data_parser.is_valid()) {
  9950. res.status = StatusCode::BadRequest_400;
  9951. output_error_log(Error::MultipartParsing, &req);
  9952. return false;
  9953. }
  9954. }
  9955. return true;
  9956. }
  9957. inline bool Server::handle_file_request(Request &req, Response &res) {
  9958. for (const auto &entry : base_dirs_) {
  9959. // Prefix match
  9960. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9961. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9962. if (detail::is_valid_path(sub_path)) {
  9963. auto path = entry.base_dir + sub_path;
  9964. if (path.back() == '/') { path += "index.html"; }
  9965. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9966. // but symlinks/junctions can still escape the base directory.
  9967. if (!entry.resolved_base_dir.empty()) {
  9968. std::string resolved_path;
  9969. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9970. !detail::is_path_within_base(resolved_path,
  9971. entry.resolved_base_dir)) {
  9972. res.status = StatusCode::Forbidden_403;
  9973. return true;
  9974. }
  9975. }
  9976. detail::FileStat stat(path);
  9977. if (stat.is_dir()) {
  9978. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9979. return true;
  9980. }
  9981. if (stat.is_file()) {
  9982. for (const auto &kv : entry.headers) {
  9983. res.set_header(kv.first, kv.second);
  9984. }
  9985. auto etag = detail::compute_etag(stat);
  9986. if (!etag.empty()) { res.set_header("ETag", etag); }
  9987. auto mtime = stat.mtime();
  9988. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9989. if (!last_modified.empty()) {
  9990. res.set_header("Last-Modified", last_modified);
  9991. }
  9992. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9993. check_if_range(req, etag, mtime);
  9994. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9995. if (!mm->is_open()) {
  9996. output_error_log(Error::OpenFile, &req);
  9997. return false;
  9998. }
  9999. res.set_content_provider(
  10000. mm->size(),
  10001. detail::find_content_type(path, file_extension_and_mimetype_map_,
  10002. default_file_mimetype_),
  10003. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10004. sink.write(mm->data() + offset, length);
  10005. return true;
  10006. });
  10007. if (req.method != "HEAD" && file_request_handler_) {
  10008. file_request_handler_(req, res);
  10009. }
  10010. return true;
  10011. } else {
  10012. output_error_log(Error::OpenFile, &req);
  10013. }
  10014. }
  10015. }
  10016. }
  10017. return false;
  10018. }
  10019. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  10020. const std::string &etag,
  10021. time_t mtime) const {
  10022. // Handle conditional GET:
  10023. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  10024. // 2. If-Modified-Since is checked only when If-None-Match is absent
  10025. if (req.has_header("If-None-Match")) {
  10026. if (!etag.empty()) {
  10027. auto val = req.get_header_value("If-None-Match");
  10028. // NOTE: We use exact string matching here. This works correctly
  10029. // because our server always generates weak ETags (W/"..."), and
  10030. // clients typically send back the same ETag they received.
  10031. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  10032. // If-None-Match, where W/"x" and "x" would match, but this
  10033. // simplified implementation requires exact matches.
  10034. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  10035. [&](const char *b, const char *e) {
  10036. auto seg_len = static_cast<size_t>(e - b);
  10037. return (seg_len == 1 && *b == '*') ||
  10038. (seg_len == etag.size() &&
  10039. std::equal(b, e, etag.begin()));
  10040. });
  10041. if (ret) {
  10042. res.status = StatusCode::NotModified_304;
  10043. return true;
  10044. }
  10045. }
  10046. } else if (req.has_header("If-Modified-Since")) {
  10047. auto val = req.get_header_value("If-Modified-Since");
  10048. auto t = detail::parse_http_date(val);
  10049. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10050. res.status = StatusCode::NotModified_304;
  10051. return true;
  10052. }
  10053. }
  10054. return false;
  10055. }
  10056. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10057. time_t mtime) const {
  10058. // Handle If-Range for partial content requests (RFC 9110
  10059. // Section 13.1.5). If-Range is only evaluated when Range header is
  10060. // present. If the validator matches, serve partial content; otherwise
  10061. // serve full content.
  10062. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10063. auto val = req.get_header_value("If-Range");
  10064. auto is_valid_range = [&]() {
  10065. if (detail::is_strong_etag(val)) {
  10066. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10067. // comparison.
  10068. return (!etag.empty() && val == etag);
  10069. } else if (detail::is_weak_etag(val)) {
  10070. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10071. return false;
  10072. } else {
  10073. // HTTP-date comparison
  10074. auto t = detail::parse_http_date(val);
  10075. return (t != static_cast<time_t>(-1) && mtime <= t);
  10076. }
  10077. };
  10078. if (!is_valid_range()) {
  10079. // Validator doesn't match: ignore Range and serve full content
  10080. req.ranges.clear();
  10081. return false;
  10082. }
  10083. }
  10084. return true;
  10085. }
  10086. inline socket_t
  10087. Server::create_server_socket(const std::string &host, int port,
  10088. int socket_flags,
  10089. SocketOptions socket_options) const {
  10090. return detail::create_socket(
  10091. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10092. ipv6_v6only_, std::move(socket_options),
  10093. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10094. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10095. output_error_log(Error::BindIPAddress, nullptr);
  10096. return false;
  10097. }
  10098. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10099. output_error_log(Error::Listen, nullptr);
  10100. return false;
  10101. }
  10102. return true;
  10103. });
  10104. }
  10105. inline int Server::bind_internal(const std::string &host, int port,
  10106. int socket_flags) {
  10107. if (is_decommissioned) { return -1; }
  10108. if (!is_valid()) { return -1; }
  10109. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10110. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10111. if (port == 0) {
  10112. struct sockaddr_storage addr;
  10113. socklen_t addr_len = sizeof(addr);
  10114. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10115. &addr_len) == -1) {
  10116. output_error_log(Error::GetSockName, nullptr);
  10117. return -1;
  10118. }
  10119. if (addr.ss_family == AF_INET) {
  10120. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10121. } else if (addr.ss_family == AF_INET6) {
  10122. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10123. } else {
  10124. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10125. return -1;
  10126. }
  10127. } else {
  10128. return port;
  10129. }
  10130. }
  10131. inline bool Server::listen_internal() {
  10132. if (is_decommissioned) { return false; }
  10133. auto ret = true;
  10134. is_running_ = true;
  10135. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10136. if (start_handler_) { start_handler_(); }
  10137. {
  10138. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10139. while (svr_sock_ != INVALID_SOCKET) {
  10140. #ifndef _WIN32
  10141. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10142. #endif
  10143. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10144. idle_interval_usec_);
  10145. if (val == 0) { // Timeout
  10146. task_queue->on_idle();
  10147. continue;
  10148. }
  10149. #ifndef _WIN32
  10150. }
  10151. #endif
  10152. #if defined _WIN32
  10153. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10154. // OVERLAPPED
  10155. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10156. #elif defined SOCK_CLOEXEC
  10157. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10158. #else
  10159. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10160. #endif
  10161. if (sock == INVALID_SOCKET) {
  10162. if (errno == EMFILE) {
  10163. // The per-process limit of open file descriptors has been reached.
  10164. // Try to accept new connections after a short sleep.
  10165. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10166. continue;
  10167. } else if (errno == EINTR || errno == EAGAIN) {
  10168. continue;
  10169. }
  10170. if (svr_sock_ != INVALID_SOCKET) {
  10171. detail::close_socket(svr_sock_);
  10172. ret = false;
  10173. output_error_log(Error::Connection, nullptr);
  10174. } else {
  10175. ; // The server socket was closed by user.
  10176. }
  10177. break;
  10178. }
  10179. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10180. read_timeout_sec_, read_timeout_usec_);
  10181. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10182. write_timeout_sec_, write_timeout_usec_);
  10183. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10184. if (!task_queue->enqueue(
  10185. [this, sock]() { process_and_close_socket(sock); })) {
  10186. output_error_log(Error::ResourceExhaustion, nullptr);
  10187. detail::shutdown_socket(sock);
  10188. detail::close_socket(sock);
  10189. }
  10190. }
  10191. task_queue->shutdown();
  10192. }
  10193. is_decommissioned = !ret;
  10194. return ret;
  10195. }
  10196. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10197. if (pre_routing_handler_ &&
  10198. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10199. return true;
  10200. }
  10201. // File handler
  10202. if ((req.method == "GET" || req.method == "HEAD") &&
  10203. handle_file_request(req, res)) {
  10204. return true;
  10205. }
  10206. if (detail::expect_content(req)) {
  10207. // Content reader handler
  10208. {
  10209. // Track whether the ContentReader was aborted due to the decompressed
  10210. // payload exceeding `payload_max_length_`.
  10211. // The user handler runs after the lambda returns, so we must restore the
  10212. // 413 status if the handler overwrites it.
  10213. bool content_reader_payload_too_large = false;
  10214. ContentReader reader(
  10215. [&](ContentReceiver receiver) {
  10216. auto result = read_content_with_content_receiver(
  10217. strm, req, res, std::move(receiver), nullptr, nullptr);
  10218. if (!result) {
  10219. output_error_log(Error::Read, &req);
  10220. if (res.status == StatusCode::PayloadTooLarge_413) {
  10221. content_reader_payload_too_large = true;
  10222. }
  10223. }
  10224. return result;
  10225. },
  10226. [&](FormDataHeader header, ContentReceiver receiver) {
  10227. auto result = read_content_with_content_receiver(
  10228. strm, req, res, nullptr, std::move(header),
  10229. std::move(receiver));
  10230. if (!result) {
  10231. output_error_log(Error::Read, &req);
  10232. if (res.status == StatusCode::PayloadTooLarge_413) {
  10233. content_reader_payload_too_large = true;
  10234. }
  10235. }
  10236. return result;
  10237. });
  10238. bool dispatched = false;
  10239. if (req.method == "POST") {
  10240. dispatched = dispatch_request_for_content_reader(
  10241. req, res, std::move(reader), post_handlers_for_content_reader_);
  10242. } else if (req.method == "PUT") {
  10243. dispatched = dispatch_request_for_content_reader(
  10244. req, res, std::move(reader), put_handlers_for_content_reader_);
  10245. } else if (req.method == "PATCH") {
  10246. dispatched = dispatch_request_for_content_reader(
  10247. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10248. } else if (req.method == "DELETE") {
  10249. dispatched = dispatch_request_for_content_reader(
  10250. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10251. }
  10252. if (dispatched) {
  10253. if (content_reader_payload_too_large) {
  10254. // Enforce the limit: override any status the handler may have set
  10255. // and return false so the error path sends a plain 413 response.
  10256. res.status = StatusCode::PayloadTooLarge_413;
  10257. res.body.clear();
  10258. res.content_length_ = 0;
  10259. res.content_provider_ = nullptr;
  10260. return false;
  10261. }
  10262. return true;
  10263. }
  10264. }
  10265. // NOTE: `req.body` is not read here. For a regular handler the body is
  10266. // read inside dispatch_request(), after the route has matched and the
  10267. // pre-request handler has approved the request, so that a rejected
  10268. // request (e.g. failed authentication) never forces us to buffer a
  10269. // potentially large body.
  10270. }
  10271. // Regular handler
  10272. if (req.method == "GET" || req.method == "HEAD") {
  10273. return dispatch_request(req, res, get_handlers_, strm);
  10274. } else if (req.method == "POST") {
  10275. return dispatch_request(req, res, post_handlers_, strm);
  10276. } else if (req.method == "PUT") {
  10277. return dispatch_request(req, res, put_handlers_, strm);
  10278. } else if (req.method == "DELETE") {
  10279. return dispatch_request(req, res, delete_handlers_, strm);
  10280. } else if (req.method == "OPTIONS") {
  10281. return dispatch_request(req, res, options_handlers_, strm);
  10282. } else if (req.method == "PATCH") {
  10283. return dispatch_request(req, res, patch_handlers_, strm);
  10284. }
  10285. res.status = StatusCode::BadRequest_400;
  10286. return false;
  10287. }
  10288. inline bool Server::dispatch_request(Request &req, Response &res,
  10289. const Handlers &handlers, Stream &strm) {
  10290. for (const auto &x : handlers) {
  10291. const auto &matcher = x.first;
  10292. const auto &handler = x.second;
  10293. if (matcher->match(req)) {
  10294. req.matched_route = matcher->pattern();
  10295. // Run the pre-request handler before reading the body so a rejected
  10296. // request (e.g. failed authentication) never forces us to buffer a
  10297. // potentially large body. `req.matched_route` is available here.
  10298. if (pre_request_handler_ &&
  10299. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10300. return true;
  10301. }
  10302. // The route matched and the request was approved; read the body now.
  10303. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10304. output_error_log(Error::Read, &req);
  10305. return false;
  10306. }
  10307. handler(req, res);
  10308. return true;
  10309. }
  10310. }
  10311. return false;
  10312. }
  10313. inline void Server::apply_ranges(const Request &req, Response &res,
  10314. std::string &content_type,
  10315. std::string &boundary) const {
  10316. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10317. auto it = res.headers.find("Content-Type");
  10318. if (it != res.headers.end()) {
  10319. content_type = it->second;
  10320. res.headers.erase(it);
  10321. }
  10322. boundary = detail::make_multipart_data_boundary();
  10323. res.set_header("Content-Type",
  10324. "multipart/byteranges; boundary=" + boundary);
  10325. }
  10326. auto type = detail::encoding_type(req, res);
  10327. if (res.body.empty()) {
  10328. if (res.content_length_ > 0) {
  10329. size_t length = 0;
  10330. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10331. length = res.content_length_;
  10332. } else if (req.ranges.size() == 1) {
  10333. auto offset_and_length = detail::get_range_offset_and_length(
  10334. req.ranges[0], res.content_length_);
  10335. length = offset_and_length.second;
  10336. auto content_range = detail::make_content_range_header_field(
  10337. offset_and_length, res.content_length_);
  10338. res.set_header("Content-Range", content_range);
  10339. } else {
  10340. length = detail::get_multipart_ranges_data_length(
  10341. req, boundary, content_type, res.content_length_);
  10342. }
  10343. res.set_header("Content-Length", std::to_string(length));
  10344. } else {
  10345. if (res.content_provider_) {
  10346. if (res.is_chunked_content_provider_) {
  10347. res.set_header("Transfer-Encoding", "chunked");
  10348. if (type != detail::EncodingType::None) {
  10349. res.set_header("Content-Encoding", detail::encoding_name(type));
  10350. res.set_header("Vary", "Accept-Encoding");
  10351. }
  10352. }
  10353. }
  10354. }
  10355. } else {
  10356. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10357. ;
  10358. } else if (req.ranges.size() == 1) {
  10359. auto offset_and_length =
  10360. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10361. auto offset = offset_and_length.first;
  10362. auto length = offset_and_length.second;
  10363. auto content_range = detail::make_content_range_header_field(
  10364. offset_and_length, res.body.size());
  10365. res.set_header("Content-Range", content_range);
  10366. assert(offset + length <= res.body.size());
  10367. res.body = res.body.substr(offset, length);
  10368. } else {
  10369. std::string data;
  10370. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10371. res.body.size(), data);
  10372. res.body.swap(data);
  10373. }
  10374. if (type != detail::EncodingType::None) {
  10375. output_pre_compression_log(req, res);
  10376. if (auto compressor = detail::make_compressor(type)) {
  10377. std::string compressed;
  10378. if (compressor->compress(res.body.data(), res.body.size(), true,
  10379. [&](const char *data, size_t data_len) {
  10380. compressed.append(data, data_len);
  10381. return true;
  10382. })) {
  10383. res.body.swap(compressed);
  10384. res.set_header("Content-Encoding", detail::encoding_name(type));
  10385. res.set_header("Vary", "Accept-Encoding");
  10386. }
  10387. }
  10388. }
  10389. res.content_length_ = res.body.size();
  10390. res.set_header("Content-Length", std::to_string(res.content_length_));
  10391. }
  10392. }
  10393. inline bool Server::dispatch_request_for_content_reader(
  10394. Request &req, Response &res, ContentReader content_reader,
  10395. const HandlersForContentReader &handlers) const {
  10396. for (const auto &x : handlers) {
  10397. const auto &matcher = x.first;
  10398. const auto &handler = x.second;
  10399. if (matcher->match(req)) {
  10400. req.matched_route = matcher->pattern();
  10401. if (!pre_request_handler_ ||
  10402. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10403. handler(req, res, content_reader);
  10404. }
  10405. return true;
  10406. }
  10407. }
  10408. return false;
  10409. }
  10410. inline std::string
  10411. get_client_ip(const std::string &x_forwarded_for,
  10412. const std::vector<std::string> &trusted_proxies) {
  10413. // X-Forwarded-For is a comma-separated list per RFC 7239
  10414. std::vector<std::string> ip_list;
  10415. detail::split(x_forwarded_for.data(),
  10416. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10417. [&](const char *b, const char *e) {
  10418. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10419. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10420. });
  10421. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10422. // no segments. Signal "no client IP derived" with an empty string so the
  10423. // caller can fall back to the connection-level remote address.
  10424. if (ip_list.empty()) { return std::string(); }
  10425. for (size_t i = 0; i < ip_list.size(); ++i) {
  10426. auto ip = ip_list[i];
  10427. auto is_trusted_proxy =
  10428. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10429. [&](const std::string &proxy) { return ip == proxy; });
  10430. if (is_trusted_proxy) {
  10431. if (i == 0) {
  10432. // If the trusted proxy is the first IP, there's no preceding client IP
  10433. return ip;
  10434. } else {
  10435. // Return the IP immediately before the trusted proxy
  10436. return ip_list[i - 1];
  10437. }
  10438. }
  10439. }
  10440. // If no trusted proxy is found, return the first IP in the list
  10441. return ip_list.front();
  10442. }
  10443. inline bool
  10444. Server::process_request(Stream &strm, const std::string &remote_addr,
  10445. int remote_port, const std::string &local_addr,
  10446. int local_port, bool close_connection,
  10447. bool &connection_closed,
  10448. const std::function<void(Request &)> &setup_request,
  10449. bool *websocket_upgraded) {
  10450. std::array<char, 2048> buf{};
  10451. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10452. // Connection has been closed on client
  10453. if (!line_reader.getline()) { return false; }
  10454. Request req;
  10455. req.start_time_ = std::chrono::steady_clock::now();
  10456. req.remote_addr = remote_addr;
  10457. req.remote_port = remote_port;
  10458. req.local_addr = local_addr;
  10459. req.local_port = local_port;
  10460. Response res;
  10461. res.version = "HTTP/1.1";
  10462. res.headers = default_headers_;
  10463. // Request line and headers
  10464. if (!parse_request_line(line_reader.ptr(), req)) {
  10465. res.status = StatusCode::BadRequest_400;
  10466. output_error_log(Error::InvalidRequestLine, &req);
  10467. return write_response(strm, close_connection, req, res);
  10468. }
  10469. // Request headers
  10470. if (!detail::read_headers(strm, req.headers)) {
  10471. res.status = StatusCode::BadRequest_400;
  10472. output_error_log(Error::InvalidHeaders, &req);
  10473. return write_response(strm, close_connection, req, res);
  10474. }
  10475. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10476. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10477. // tolerated for compatibility with existing clients.
  10478. if (req.get_header_value_u64("Content-Length") > 0 &&
  10479. req.has_header("Transfer-Encoding")) {
  10480. connection_closed = true;
  10481. res.status = StatusCode::BadRequest_400;
  10482. return write_response(strm, close_connection, req, res);
  10483. }
  10484. // Check if the request URI doesn't exceed the limit
  10485. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10486. connection_closed = true;
  10487. res.status = StatusCode::UriTooLong_414;
  10488. output_error_log(Error::ExceedUriMaxLength, &req);
  10489. return write_response(strm, close_connection, req, res);
  10490. }
  10491. if (req.get_header_value("Connection") == "close") {
  10492. connection_closed = true;
  10493. }
  10494. if (req.version == "HTTP/1.0" &&
  10495. req.get_header_value("Connection") != "Keep-Alive") {
  10496. connection_closed = true;
  10497. }
  10498. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10499. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10500. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10501. req.remote_addr = derived.empty() ? remote_addr : derived;
  10502. } else {
  10503. req.remote_addr = remote_addr;
  10504. }
  10505. req.remote_port = remote_port;
  10506. req.local_addr = local_addr;
  10507. req.local_port = local_port;
  10508. if (req.has_header("Accept")) {
  10509. const auto &accept_header = req.get_header_value("Accept");
  10510. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10511. connection_closed = true;
  10512. res.status = StatusCode::BadRequest_400;
  10513. output_error_log(Error::HTTPParsing, &req);
  10514. return write_response(strm, close_connection, req, res);
  10515. }
  10516. }
  10517. if (req.has_header("Range")) {
  10518. const auto &range_header_value = req.get_header_value("Range");
  10519. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10520. connection_closed = true;
  10521. res.status = StatusCode::RangeNotSatisfiable_416;
  10522. output_error_log(Error::InvalidRangeHeader, &req);
  10523. return write_response(strm, close_connection, req, res);
  10524. }
  10525. }
  10526. if (setup_request) { setup_request(req); }
  10527. if (req.get_header_value("Expect") == "100-continue") {
  10528. int status = StatusCode::Continue_100;
  10529. if (expect_100_continue_handler_) {
  10530. status = expect_100_continue_handler_(req, res);
  10531. }
  10532. switch (status) {
  10533. case StatusCode::Continue_100:
  10534. case StatusCode::ExpectationFailed_417:
  10535. detail::write_response_line(strm, status);
  10536. strm.write("\r\n");
  10537. break;
  10538. default:
  10539. connection_closed = true;
  10540. return write_response(strm, true, req, res);
  10541. }
  10542. }
  10543. // Setup `is_connection_closed` method
  10544. auto sock = strm.socket();
  10545. req.is_connection_closed = [sock]() {
  10546. return !detail::is_socket_alive(sock);
  10547. };
  10548. // WebSocket upgrade
  10549. // Check pre_routing_handler_ before upgrading so that authentication
  10550. // and other middleware can reject the request with an HTTP response
  10551. // (e.g., 401) before the protocol switches.
  10552. if (detail::is_websocket_upgrade(req)) {
  10553. if (pre_routing_handler_ &&
  10554. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10555. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10556. return write_response(strm, close_connection, req, res);
  10557. }
  10558. // Find matching WebSocket handler
  10559. for (const auto &entry : websocket_handlers_) {
  10560. if (entry.matcher->match(req)) {
  10561. // Compute accept key
  10562. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10563. auto accept_key = detail::websocket_accept_key(client_key);
  10564. // Negotiate subprotocol
  10565. std::string selected_subprotocol;
  10566. if (entry.sub_protocol_selector) {
  10567. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10568. if (!protocol_header.empty()) {
  10569. std::vector<std::string> protocols;
  10570. std::istringstream iss(protocol_header);
  10571. std::string token;
  10572. while (std::getline(iss, token, ',')) {
  10573. // Trim whitespace
  10574. auto start = token.find_first_not_of(' ');
  10575. auto end = token.find_last_not_of(' ');
  10576. if (start != std::string::npos) {
  10577. protocols.push_back(token.substr(start, end - start + 1));
  10578. }
  10579. }
  10580. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10581. }
  10582. }
  10583. // Send 101 Switching Protocols
  10584. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10585. "Upgrade: websocket\r\n"
  10586. "Connection: Upgrade\r\n"
  10587. "Sec-WebSocket-Accept: " +
  10588. accept_key + "\r\n";
  10589. if (!selected_subprotocol.empty()) {
  10590. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10591. return false;
  10592. }
  10593. handshake_response +=
  10594. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10595. }
  10596. handshake_response += "\r\n";
  10597. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10598. 0) {
  10599. return false;
  10600. }
  10601. connection_closed = true;
  10602. if (websocket_upgraded) { *websocket_upgraded = true; }
  10603. {
  10604. // Use WebSocket-specific read timeout instead of HTTP timeout
  10605. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10606. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10607. websocket_max_missed_pongs_);
  10608. entry.handler(req, ws);
  10609. }
  10610. return true;
  10611. }
  10612. }
  10613. // No matching handler - fall through to 404
  10614. }
  10615. // Routing
  10616. auto routed = false;
  10617. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10618. routed = routing(req, res, strm);
  10619. #else
  10620. try {
  10621. routed = routing(req, res, strm);
  10622. } catch (std::exception &) {
  10623. if (exception_handler_) {
  10624. auto ep = std::current_exception();
  10625. exception_handler_(req, res, ep);
  10626. routed = true;
  10627. } else {
  10628. res.status = StatusCode::InternalServerError_500;
  10629. }
  10630. } catch (...) {
  10631. if (exception_handler_) {
  10632. auto ep = std::current_exception();
  10633. exception_handler_(req, res, ep);
  10634. routed = true;
  10635. } else {
  10636. res.status = StatusCode::InternalServerError_500;
  10637. }
  10638. }
  10639. #endif
  10640. auto ret = false;
  10641. if (routed) {
  10642. if (res.status == -1) {
  10643. res.status = req.ranges.empty() ? StatusCode::OK_200
  10644. : StatusCode::PartialContent_206;
  10645. }
  10646. // Serve file content by using a content provider
  10647. auto file_open_error = false;
  10648. if (!res.file_content_path_.empty()) {
  10649. const auto &path = res.file_content_path_;
  10650. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10651. if (!mm->is_open()) {
  10652. res.body.clear();
  10653. res.content_length_ = 0;
  10654. res.content_provider_ = nullptr;
  10655. res.status = StatusCode::NotFound_404;
  10656. output_error_log(Error::OpenFile, &req);
  10657. file_open_error = true;
  10658. } else {
  10659. auto content_type = res.file_content_content_type_;
  10660. if (content_type.empty()) {
  10661. content_type = detail::find_content_type(
  10662. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10663. }
  10664. res.set_content_provider(
  10665. mm->size(), content_type,
  10666. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10667. sink.write(mm->data() + offset, length);
  10668. return true;
  10669. });
  10670. }
  10671. }
  10672. if (file_open_error) {
  10673. ret = write_response(strm, close_connection, req, res);
  10674. } else if (detail::range_error(req, res)) {
  10675. res.body.clear();
  10676. res.content_length_ = 0;
  10677. res.content_provider_ = nullptr;
  10678. res.status = StatusCode::RangeNotSatisfiable_416;
  10679. ret = write_response(strm, close_connection, req, res);
  10680. } else {
  10681. ret = write_response_with_content(strm, close_connection, req, res);
  10682. }
  10683. } else {
  10684. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10685. ret = write_response(strm, close_connection, req, res);
  10686. }
  10687. // Drain any unconsumed framed body to prevent request smuggling on
  10688. // keep-alive. Without framing there is no body to drain — reading would
  10689. // consume the next request (issue #2450).
  10690. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10691. int dummy_status;
  10692. if (!detail::read_content(
  10693. strm, req, payload_max_length_, dummy_status, nullptr,
  10694. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10695. connection_closed = true;
  10696. }
  10697. }
  10698. return ret;
  10699. }
  10700. inline bool Server::is_valid() const { return true; }
  10701. inline bool Server::process_and_close_socket(socket_t sock) {
  10702. std::string remote_addr;
  10703. int remote_port = 0;
  10704. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10705. std::string local_addr;
  10706. int local_port = 0;
  10707. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10708. bool websocket_upgraded = false;
  10709. auto ret = detail::process_server_socket(
  10710. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10711. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10712. write_timeout_usec_,
  10713. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10714. return process_request(strm, remote_addr, remote_port, local_addr,
  10715. local_port, close_connection, connection_closed,
  10716. nullptr, &websocket_upgraded);
  10717. });
  10718. detail::shutdown_socket(sock);
  10719. detail::close_socket(sock);
  10720. return ret;
  10721. }
  10722. inline void Server::output_log(const Request &req, const Response &res) const {
  10723. if (logger_) {
  10724. std::lock_guard<std::mutex> guard(logger_mutex_);
  10725. logger_(req, res);
  10726. }
  10727. }
  10728. inline void Server::output_pre_compression_log(const Request &req,
  10729. const Response &res) const {
  10730. if (pre_compression_logger_) {
  10731. std::lock_guard<std::mutex> guard(logger_mutex_);
  10732. pre_compression_logger_(req, res);
  10733. }
  10734. }
  10735. inline void Server::output_error_log(const Error &err,
  10736. const Request *req) const {
  10737. if (error_logger_) {
  10738. std::lock_guard<std::mutex> guard(logger_mutex_);
  10739. error_logger_(err, req);
  10740. }
  10741. }
  10742. /*
  10743. * Group 5: ClientImpl and Client (Universal) implementation
  10744. */
  10745. // HTTP client implementation
  10746. inline ClientImpl::ClientImpl(const std::string &host)
  10747. : ClientImpl(host, 80, std::string(), std::string()) {}
  10748. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10749. : ClientImpl(host, port, std::string(), std::string()) {}
  10750. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10751. const std::string &client_cert_path,
  10752. const std::string &client_key_path)
  10753. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10754. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10755. inline ClientImpl::~ClientImpl() {
  10756. // Wait until all the requests in flight are handled.
  10757. size_t retry_count = 10;
  10758. while (retry_count-- > 0) {
  10759. {
  10760. std::lock_guard<std::mutex> guard(socket_mutex_);
  10761. if (socket_requests_in_flight_ == 0) { break; }
  10762. }
  10763. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10764. }
  10765. std::lock_guard<std::mutex> guard(socket_mutex_);
  10766. shutdown_socket(socket_);
  10767. close_socket(socket_);
  10768. }
  10769. inline bool ClientImpl::is_valid() const { return true; }
  10770. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10771. client_cert_path_ = rhs.client_cert_path_;
  10772. client_key_path_ = rhs.client_key_path_;
  10773. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10774. read_timeout_sec_ = rhs.read_timeout_sec_;
  10775. read_timeout_usec_ = rhs.read_timeout_usec_;
  10776. write_timeout_sec_ = rhs.write_timeout_sec_;
  10777. write_timeout_usec_ = rhs.write_timeout_usec_;
  10778. max_timeout_msec_ = rhs.max_timeout_msec_;
  10779. basic_auth_username_ = rhs.basic_auth_username_;
  10780. basic_auth_password_ = rhs.basic_auth_password_;
  10781. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10782. keep_alive_ = rhs.keep_alive_;
  10783. follow_location_ = rhs.follow_location_;
  10784. path_encode_ = rhs.path_encode_;
  10785. address_family_ = rhs.address_family_;
  10786. tcp_nodelay_ = rhs.tcp_nodelay_;
  10787. ipv6_v6only_ = rhs.ipv6_v6only_;
  10788. socket_options_ = rhs.socket_options_;
  10789. compress_ = rhs.compress_;
  10790. decompress_ = rhs.decompress_;
  10791. payload_max_length_ = rhs.payload_max_length_;
  10792. has_payload_max_length_ = rhs.has_payload_max_length_;
  10793. interface_ = rhs.interface_;
  10794. proxy_host_ = rhs.proxy_host_;
  10795. proxy_port_ = rhs.proxy_port_;
  10796. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10797. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10798. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10799. no_proxy_entries_ = rhs.no_proxy_entries_;
  10800. logger_ = rhs.logger_;
  10801. error_logger_ = rhs.error_logger_;
  10802. #ifdef CPPHTTPLIB_SSL_ENABLED
  10803. digest_auth_username_ = rhs.digest_auth_username_;
  10804. digest_auth_password_ = rhs.digest_auth_password_;
  10805. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10806. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10807. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10808. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10809. server_certificate_verification_ = rhs.server_certificate_verification_;
  10810. server_hostname_verification_ = rhs.server_hostname_verification_;
  10811. system_ca_mode_ = rhs.system_ca_mode_;
  10812. #endif
  10813. }
  10814. inline bool
  10815. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10816. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10817. if (no_proxy_entries_.empty()) { return true; }
  10818. // host_ is const so its normalized form is invariant; cache it. The
  10819. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10820. if (host == host_) {
  10821. if (!host_normalized_valid_) {
  10822. host_normalized_ = detail::normalize_target(host_);
  10823. host_normalized_valid_ = true;
  10824. }
  10825. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10826. }
  10827. auto target = detail::normalize_target(host);
  10828. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10829. }
  10830. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10831. if (is_proxy_enabled_for_host(host_)) {
  10832. return detail::create_client_socket(
  10833. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10834. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10835. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10836. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10837. }
  10838. // Check is custom IP specified for host_
  10839. std::string ip;
  10840. auto it = addr_map_.find(host_);
  10841. if (it != addr_map_.end()) { ip = it->second; }
  10842. return detail::create_client_socket(
  10843. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10844. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10845. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10846. write_timeout_usec_, interface_, error);
  10847. }
  10848. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10849. Error &error) {
  10850. auto sock = create_client_socket(error);
  10851. if (sock == INVALID_SOCKET) { return false; }
  10852. socket.sock = sock;
  10853. return true;
  10854. }
  10855. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10856. return create_and_connect_socket(socket, error);
  10857. }
  10858. inline bool ClientImpl::setup_proxy_connection(
  10859. Socket & /*socket*/,
  10860. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10861. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10862. return true;
  10863. }
  10864. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10865. bool /*shutdown_gracefully*/) {
  10866. // If there are any requests in flight from threads other than us, then it's
  10867. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10868. assert(socket_requests_in_flight_ == 0 ||
  10869. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10870. }
  10871. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10872. if (socket.sock == INVALID_SOCKET) { return; }
  10873. detail::shutdown_socket(socket.sock);
  10874. }
  10875. inline void ClientImpl::close_socket(Socket &socket) {
  10876. // If there are requests in flight in another thread, usually closing
  10877. // the socket will be fine and they will simply receive an error when
  10878. // using the closed socket, but it is still a bug since rarely the OS
  10879. // may reassign the socket id to be used for a new socket, and then
  10880. // suddenly they will be operating on a live socket that is different
  10881. // than the one they intended!
  10882. assert(socket_requests_in_flight_ == 0 ||
  10883. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10884. // It is also a bug if this happens while SSL is still active
  10885. #ifdef CPPHTTPLIB_SSL_ENABLED
  10886. assert(socket.ssl == nullptr);
  10887. #endif
  10888. if (socket.sock == INVALID_SOCKET) { return; }
  10889. detail::close_socket(socket.sock);
  10890. socket.sock = INVALID_SOCKET;
  10891. }
  10892. inline void ClientImpl::disconnect(bool gracefully) {
  10893. shutdown_ssl(socket_, gracefully);
  10894. shutdown_socket(socket_);
  10895. close_socket(socket_);
  10896. }
  10897. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10898. Response &res,
  10899. bool skip_100_continue) const {
  10900. std::array<char, 2048> buf{};
  10901. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10902. if (!line_reader.getline()) { return false; }
  10903. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10904. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10905. #else
  10906. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10907. #endif
  10908. std::cmatch m;
  10909. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10910. return req.method == "CONNECT";
  10911. }
  10912. res.version = std::string(m[1]);
  10913. res.status = std::stoi(std::string(m[2]));
  10914. res.reason = std::string(m[3]);
  10915. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10916. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10917. if (!line_reader.getline()) { return false; } // CRLF
  10918. if (!line_reader.getline()) { return false; } // next response line
  10919. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10920. res.version = std::string(m[1]);
  10921. res.status = std::stoi(std::string(m[2]));
  10922. res.reason = std::string(m[3]);
  10923. }
  10924. return true;
  10925. }
  10926. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10927. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10928. auto ret = send_(req, res, error);
  10929. if (error == Error::SSLPeerCouldBeClosed_) {
  10930. assert(!ret);
  10931. ret = send_(req, res, error);
  10932. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10933. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10934. }
  10935. return ret;
  10936. }
  10937. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10938. {
  10939. std::lock_guard<std::mutex> guard(socket_mutex_);
  10940. // Set this to false immediately - if it ever gets set to true by the end
  10941. // of the request, we know another thread instructed us to close the
  10942. // socket.
  10943. socket_should_be_closed_when_request_is_done_ = false;
  10944. auto is_alive = false;
  10945. if (socket_.is_open()) {
  10946. is_alive = detail::is_socket_alive(socket_.sock);
  10947. #ifdef CPPHTTPLIB_SSL_ENABLED
  10948. if (is_alive && is_ssl()) {
  10949. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10950. is_alive = false;
  10951. }
  10952. }
  10953. #endif
  10954. if (!is_alive) {
  10955. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10956. disconnect(/*gracefully=*/false);
  10957. }
  10958. }
  10959. if (!is_alive) {
  10960. if (!ensure_socket_connection(socket_, error)) {
  10961. output_error_log(error, &req);
  10962. return false;
  10963. }
  10964. {
  10965. auto success = true;
  10966. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10967. error)) {
  10968. if (!success) { output_error_log(error, &req); }
  10969. return success;
  10970. }
  10971. }
  10972. }
  10973. // Mark the current socket as being in use so that it cannot be closed by
  10974. // anyone else while this request is ongoing, even though we will be
  10975. // releasing the mutex.
  10976. if (socket_requests_in_flight_ > 1) {
  10977. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10978. }
  10979. socket_requests_in_flight_ += 1;
  10980. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10981. }
  10982. for (const auto &header : default_headers_) {
  10983. if (req.headers.find(header.first) == req.headers.end()) {
  10984. req.headers.insert(header);
  10985. }
  10986. }
  10987. auto ret = false;
  10988. auto close_connection = !keep_alive_;
  10989. auto se = detail::scope_exit([&]() {
  10990. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10991. std::lock_guard<std::mutex> guard(socket_mutex_);
  10992. socket_requests_in_flight_ -= 1;
  10993. if (socket_requests_in_flight_ <= 0) {
  10994. assert(socket_requests_in_flight_ == 0);
  10995. socket_requests_are_from_thread_ = std::thread::id();
  10996. }
  10997. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10998. !ret) {
  10999. disconnect(/*gracefully=*/true);
  11000. }
  11001. });
  11002. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  11003. return handle_request(strm, req, res, close_connection, error);
  11004. });
  11005. if (!ret) {
  11006. if (error == Error::Success) {
  11007. error = Error::Unknown;
  11008. output_error_log(error, &req);
  11009. }
  11010. }
  11011. return ret;
  11012. }
  11013. inline Result ClientImpl::send(const Request &req) {
  11014. auto req2 = req;
  11015. return send_(std::move(req2));
  11016. }
  11017. inline Result ClientImpl::send_(Request &&req) {
  11018. auto res = detail::make_unique<Response>();
  11019. auto error = Error::Success;
  11020. auto ret = send(req, *res, error);
  11021. #ifdef CPPHTTPLIB_SSL_ENABLED
  11022. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  11023. last_ssl_error_, last_backend_error_};
  11024. #else
  11025. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  11026. #endif
  11027. }
  11028. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  11029. const std::string &ct) {
  11030. (void)for_stream;
  11031. for (const auto &header : default_headers_) {
  11032. if (!r.has_header(header.first)) { r.headers.insert(header); }
  11033. }
  11034. if (!r.has_header("Host")) {
  11035. if (address_family_ == AF_UNIX) {
  11036. r.headers.emplace("Host", "localhost");
  11037. } else {
  11038. r.headers.emplace(
  11039. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  11040. }
  11041. }
  11042. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  11043. if (!r.content_receiver) {
  11044. if (!r.has_header("Accept-Encoding")) {
  11045. std::string accept_encoding;
  11046. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11047. accept_encoding = "br";
  11048. #endif
  11049. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11050. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11051. accept_encoding += "gzip, deflate";
  11052. #endif
  11053. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11054. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11055. accept_encoding += "zstd";
  11056. #endif
  11057. r.set_header("Accept-Encoding", accept_encoding);
  11058. }
  11059. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11060. if (!r.has_header("User-Agent")) {
  11061. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11062. r.set_header("User-Agent", agent);
  11063. }
  11064. #endif
  11065. }
  11066. if (!r.body.empty()) {
  11067. if (!ct.empty() && !r.has_header("Content-Type")) {
  11068. r.headers.emplace("Content-Type", ct);
  11069. }
  11070. if (!r.has_header("Content-Length")) {
  11071. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11072. }
  11073. }
  11074. }
  11075. inline ClientImpl::StreamHandle
  11076. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11077. const Params &params, const Headers &headers,
  11078. const std::string &body,
  11079. const std::string &content_type) {
  11080. StreamHandle handle;
  11081. handle.response = detail::make_unique<Response>();
  11082. handle.error = Error::Success;
  11083. auto query_path = params.empty() ? path : append_query_params(path, params);
  11084. handle.connection_ = detail::make_unique<ClientConnection>();
  11085. {
  11086. std::lock_guard<std::mutex> guard(socket_mutex_);
  11087. auto is_alive = false;
  11088. if (socket_.is_open()) {
  11089. is_alive = detail::is_socket_alive(socket_.sock);
  11090. #ifdef CPPHTTPLIB_SSL_ENABLED
  11091. if (is_alive && is_ssl()) {
  11092. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11093. is_alive = false;
  11094. }
  11095. }
  11096. #endif
  11097. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11098. }
  11099. if (!is_alive) {
  11100. if (!ensure_socket_connection(socket_, handle.error)) {
  11101. handle.response.reset();
  11102. return handle;
  11103. }
  11104. {
  11105. auto success = true;
  11106. auto start_time = std::chrono::steady_clock::now();
  11107. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11108. success, handle.error)) {
  11109. if (!success) { handle.response.reset(); }
  11110. return handle;
  11111. }
  11112. }
  11113. }
  11114. transfer_socket_ownership_to_handle(handle);
  11115. }
  11116. #ifdef CPPHTTPLIB_SSL_ENABLED
  11117. if (is_ssl() && handle.connection_->session) {
  11118. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11119. handle.connection_->sock, handle.connection_->session,
  11120. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11121. write_timeout_usec_);
  11122. } else {
  11123. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11124. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11125. write_timeout_sec_, write_timeout_usec_);
  11126. }
  11127. #else
  11128. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11129. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11130. write_timeout_sec_, write_timeout_usec_);
  11131. #endif
  11132. handle.stream_ = handle.socket_stream_.get();
  11133. Request req;
  11134. req.method = method;
  11135. req.path = query_path;
  11136. req.headers = headers;
  11137. req.body = body;
  11138. prepare_default_headers(req, true, content_type);
  11139. auto &strm = *handle.stream_;
  11140. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11141. handle.error = Error::Write;
  11142. handle.response.reset();
  11143. return handle;
  11144. }
  11145. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11146. handle.error)) {
  11147. handle.response.reset();
  11148. return handle;
  11149. }
  11150. if (!body.empty()) {
  11151. if (strm.write(body.data(), body.size()) < 0) {
  11152. handle.error = Error::Write;
  11153. handle.response.reset();
  11154. return handle;
  11155. }
  11156. }
  11157. if (!read_response_line(strm, req, *handle.response) ||
  11158. !detail::read_headers(strm, handle.response->headers)) {
  11159. handle.error = Error::Read;
  11160. handle.response.reset();
  11161. return handle;
  11162. }
  11163. handle.body_reader_.stream = handle.stream_;
  11164. handle.body_reader_.payload_max_length = payload_max_length_;
  11165. if (handle.response->has_header("Content-Length")) {
  11166. bool is_invalid = false;
  11167. auto content_length = detail::get_header_value_u64(
  11168. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11169. if (is_invalid) {
  11170. handle.error = Error::Read;
  11171. handle.response.reset();
  11172. return handle;
  11173. }
  11174. handle.body_reader_.has_content_length = true;
  11175. handle.body_reader_.content_length = content_length;
  11176. }
  11177. handle.body_reader_.chunked =
  11178. detail::is_chunked_transfer_encoding(handle.response->headers);
  11179. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11180. if (!content_encoding.empty()) {
  11181. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11182. }
  11183. return handle;
  11184. }
  11185. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11186. if (!is_valid() || !response) { return -1; }
  11187. if (decompressor_) { return read_with_decompression(buf, len); }
  11188. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11189. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11190. trailers_parsed_ = true;
  11191. if (body_reader_.chunked_decoder) {
  11192. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11193. response->trailers, response->headers)) {
  11194. return n;
  11195. }
  11196. } else {
  11197. detail::ChunkedDecoder dec(*stream_);
  11198. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11199. return n;
  11200. }
  11201. }
  11202. }
  11203. return n;
  11204. }
  11205. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11206. size_t len) {
  11207. if (decompress_offset_ < decompress_buffer_.size()) {
  11208. auto available = decompress_buffer_.size() - decompress_offset_;
  11209. auto to_copy = (std::min)(len, available);
  11210. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11211. decompress_offset_ += to_copy;
  11212. decompressed_bytes_read_ += to_copy;
  11213. return static_cast<ssize_t>(to_copy);
  11214. }
  11215. decompress_buffer_.clear();
  11216. decompress_offset_ = 0;
  11217. constexpr size_t kDecompressionBufferSize = 8192;
  11218. char compressed_buf[kDecompressionBufferSize];
  11219. while (true) {
  11220. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11221. sizeof(compressed_buf));
  11222. if (n <= 0) { return n; }
  11223. bool decompress_ok = decompressor_->decompress(
  11224. compressed_buf, static_cast<size_t>(n),
  11225. [this](const char *data, size_t data_len) {
  11226. decompress_buffer_.append(data, data_len);
  11227. auto limit = body_reader_.payload_max_length;
  11228. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11229. return false;
  11230. }
  11231. return true;
  11232. });
  11233. if (!decompress_ok) {
  11234. body_reader_.last_error = Error::Read;
  11235. return -1;
  11236. }
  11237. if (!decompress_buffer_.empty()) { break; }
  11238. }
  11239. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11240. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11241. decompress_offset_ = to_copy;
  11242. decompressed_bytes_read_ += to_copy;
  11243. return static_cast<ssize_t>(to_copy);
  11244. }
  11245. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11246. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11247. return;
  11248. }
  11249. trailers_parsed_ = true;
  11250. const auto bufsiz = 128;
  11251. char line_buf[bufsiz];
  11252. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11253. if (!line_reader.getline()) { return; }
  11254. if (!detail::parse_trailers(line_reader, response->trailers,
  11255. response->headers)) {
  11256. return;
  11257. }
  11258. }
  11259. namespace detail {
  11260. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11261. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11262. size_t &out_chunk_offset,
  11263. size_t &out_chunk_total) {
  11264. if (finished) { return 0; }
  11265. if (chunk_remaining == 0) {
  11266. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11267. if (!lr.getline()) { return -1; }
  11268. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11269. const char *p = lr.ptr();
  11270. int v = 0;
  11271. if (!is_hex(*p, v)) { return -1; }
  11272. size_t chunk_len = 0;
  11273. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11274. for (; is_hex(*p, v); ++p) {
  11275. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11276. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11277. }
  11278. while (is_space_or_tab(*p)) {
  11279. ++p;
  11280. }
  11281. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11282. if (chunk_len == 0) {
  11283. chunk_remaining = 0;
  11284. finished = true;
  11285. out_chunk_offset = 0;
  11286. out_chunk_total = 0;
  11287. return 0;
  11288. }
  11289. chunk_remaining = chunk_len;
  11290. last_chunk_total = chunk_remaining;
  11291. last_chunk_offset = 0;
  11292. }
  11293. auto to_read = (std::min)(chunk_remaining, len);
  11294. auto n = strm.read(buf, to_read);
  11295. if (n <= 0) { return -1; }
  11296. auto offset_before = last_chunk_offset;
  11297. last_chunk_offset += static_cast<size_t>(n);
  11298. chunk_remaining -= static_cast<size_t>(n);
  11299. out_chunk_offset = offset_before;
  11300. out_chunk_total = last_chunk_total;
  11301. if (chunk_remaining == 0) {
  11302. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11303. if (!lr.getline()) { return -1; }
  11304. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11305. }
  11306. return n;
  11307. }
  11308. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11309. const Headers &src_headers) {
  11310. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11311. if (!lr.getline()) { return false; }
  11312. return parse_trailers(lr, dest, src_headers);
  11313. }
  11314. } // namespace detail
  11315. inline void
  11316. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11317. handle.connection_->sock = socket_.sock;
  11318. #ifdef CPPHTTPLIB_SSL_ENABLED
  11319. handle.connection_->session = socket_.ssl;
  11320. socket_.ssl = nullptr;
  11321. #endif
  11322. socket_.sock = INVALID_SOCKET;
  11323. }
  11324. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11325. Response &res, bool close_connection,
  11326. Error &error) {
  11327. if (req.path.empty()) {
  11328. error = Error::Connection;
  11329. output_error_log(error, &req);
  11330. return false;
  11331. }
  11332. auto req_save = req;
  11333. bool ret;
  11334. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11335. auto req2 = req;
  11336. req2.path = "http://" +
  11337. detail::make_host_and_port_string(host_, port_, false) +
  11338. req.path;
  11339. ret = process_request(strm, req2, res, close_connection, error);
  11340. req = std::move(req2);
  11341. req.path = req_save.path;
  11342. } else {
  11343. ret = process_request(strm, req, res, close_connection, error);
  11344. }
  11345. if (!ret) { return false; }
  11346. if (res.get_header_value("Connection") == "close" ||
  11347. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11348. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11349. // for this to be safe.
  11350. // This is safe to call because handle_request is only called by send_
  11351. // which locks the request mutex during the process. It would be a bug
  11352. // to call it from a different thread since it's a thread-safety issue
  11353. // to do these things to the socket if another thread is using the socket.
  11354. std::lock_guard<std::mutex> guard(socket_mutex_);
  11355. disconnect(/*gracefully=*/true);
  11356. }
  11357. if (300 < res.status && res.status < 400 && follow_location_) {
  11358. req = std::move(req_save);
  11359. ret = redirect(req, res, error);
  11360. }
  11361. #ifdef CPPHTTPLIB_SSL_ENABLED
  11362. if ((res.status == StatusCode::Unauthorized_401 ||
  11363. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11364. req.authorization_count_ < 5) {
  11365. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11366. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11367. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11368. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11369. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11370. return ret;
  11371. }
  11372. const auto &username =
  11373. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11374. const auto &password =
  11375. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11376. if (!username.empty() && !password.empty()) {
  11377. std::map<std::string, std::string> auth;
  11378. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11379. Request new_req = req;
  11380. new_req.authorization_count_ += 1;
  11381. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11382. : "Authorization");
  11383. new_req.headers.insert(detail::make_digest_authentication_header(
  11384. req, auth, new_req.authorization_count_, detail::random_string(10),
  11385. username, password, is_proxy));
  11386. Response new_res;
  11387. ret = send(new_req, new_res, error);
  11388. if (ret) { res = std::move(new_res); }
  11389. }
  11390. }
  11391. }
  11392. #endif
  11393. return ret;
  11394. }
  11395. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11396. if (req.redirect_count_ == 0) {
  11397. error = Error::ExceedRedirectCount;
  11398. output_error_log(error, &req);
  11399. return false;
  11400. }
  11401. auto location = res.get_header_value("location");
  11402. if (location.empty()) { return false; }
  11403. detail::UrlComponents uc;
  11404. if (!detail::parse_url(location, uc)) { return false; }
  11405. // Only follow http/https redirects
  11406. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11407. return false;
  11408. }
  11409. auto scheme = is_ssl() ? "https" : "http";
  11410. auto next_scheme = std::move(uc.scheme);
  11411. auto next_host = std::move(uc.host);
  11412. auto port_str = std::move(uc.port);
  11413. auto next_path = std::move(uc.path);
  11414. auto next_query = std::move(uc.query);
  11415. auto next_port = port_;
  11416. if (!port_str.empty()) {
  11417. if (!detail::parse_port(port_str, next_port)) { return false; }
  11418. } else if (!next_scheme.empty()) {
  11419. next_port = next_scheme == "https" ? 443 : 80;
  11420. }
  11421. if (next_scheme.empty()) { next_scheme = scheme; }
  11422. if (next_host.empty()) { next_host = host_; }
  11423. if (next_path.empty()) { next_path = "/"; }
  11424. auto path = decode_path_component(next_path) + next_query;
  11425. // Same host redirect - use current client
  11426. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11427. return detail::redirect(*this, req, res, path, location, error);
  11428. }
  11429. // Cross-host/scheme redirect - create new client with robust setup
  11430. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11431. path, location, error);
  11432. }
  11433. // New method for robust redirect client creation
  11434. inline bool ClientImpl::create_redirect_client(
  11435. const std::string &scheme, const std::string &host, int port, Request &req,
  11436. Response &res, const std::string &path, const std::string &location,
  11437. Error &error) {
  11438. // Determine if we need SSL
  11439. auto need_ssl = (scheme == "https");
  11440. // Clean up request headers that are host/client specific
  11441. // Remove headers that should not be carried over to new host
  11442. auto headers_to_remove = std::vector<std::string>{
  11443. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  11444. for (const auto &header_name : headers_to_remove) {
  11445. auto it = req.headers.find(header_name);
  11446. while (it != req.headers.end()) {
  11447. it = req.headers.erase(it);
  11448. it = req.headers.find(header_name);
  11449. }
  11450. }
  11451. // Create appropriate client type and handle redirect
  11452. if (need_ssl) {
  11453. #ifdef CPPHTTPLIB_SSL_ENABLED
  11454. // Create SSL client for HTTPS redirect
  11455. SSLClient redirect_client(host, port);
  11456. // Setup basic client configuration first
  11457. setup_redirect_client(redirect_client);
  11458. redirect_client.enable_server_certificate_verification(
  11459. server_certificate_verification_);
  11460. redirect_client.enable_server_hostname_verification(
  11461. server_hostname_verification_);
  11462. redirect_client.system_ca_mode_ = system_ca_mode_;
  11463. // Transfer CA certificate to redirect client
  11464. if (!ca_cert_pem_.empty()) {
  11465. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11466. ca_cert_pem_.size());
  11467. }
  11468. if (!ca_cert_file_path_.empty()) {
  11469. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11470. }
  11471. // Client certificates are set through constructor for SSLClient
  11472. // NOTE: SSLClient constructor already takes client_cert_path and
  11473. // client_key_path so we need to create it properly if client certs are
  11474. // needed
  11475. // Execute the redirect
  11476. return detail::redirect(redirect_client, req, res, path, location, error);
  11477. #else
  11478. // SSL not supported - set appropriate error
  11479. error = Error::SSLConnection;
  11480. output_error_log(error, &req);
  11481. return false;
  11482. #endif
  11483. } else {
  11484. // HTTP redirect
  11485. ClientImpl redirect_client(host, port);
  11486. // Setup client with robust configuration
  11487. setup_redirect_client(redirect_client);
  11488. // Execute the redirect
  11489. return detail::redirect(redirect_client, req, res, path, location, error);
  11490. }
  11491. }
  11492. // New method for robust client setup (based on basic_manual_redirect.cpp
  11493. // logic)
  11494. template <typename ClientType>
  11495. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11496. // Copy basic settings first
  11497. client.set_connection_timeout(connection_timeout_sec_);
  11498. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11499. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11500. client.set_keep_alive(keep_alive_);
  11501. client.set_follow_location(
  11502. true); // Enable redirects to handle multi-step redirects
  11503. client.set_path_encode(path_encode_);
  11504. client.set_compress(compress_);
  11505. client.set_decompress(decompress_);
  11506. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11507. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11508. // 15.4, credentials must not be forwarded when redirecting to a different
  11509. // host. This function is only called for cross-host redirects; same-host
  11510. // redirects are handled directly in ClientImpl::redirect().
  11511. // Copy the proxy configuration unconditionally; the per-target bypass is
  11512. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11513. // still use the proxy.
  11514. client.no_proxy_entries_ = no_proxy_entries_;
  11515. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11516. client.set_proxy(proxy_host_, proxy_port_);
  11517. if (!proxy_basic_auth_username_.empty()) {
  11518. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11519. proxy_basic_auth_password_);
  11520. }
  11521. if (!proxy_bearer_token_auth_token_.empty()) {
  11522. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11523. }
  11524. #ifdef CPPHTTPLIB_SSL_ENABLED
  11525. if (!proxy_digest_auth_username_.empty()) {
  11526. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11527. proxy_digest_auth_password_);
  11528. }
  11529. #endif
  11530. }
  11531. // Copy network and socket settings
  11532. client.set_address_family(address_family_);
  11533. client.set_tcp_nodelay(tcp_nodelay_);
  11534. client.set_ipv6_v6only(ipv6_v6only_);
  11535. if (socket_options_) { client.set_socket_options(socket_options_); }
  11536. if (!interface_.empty()) { client.set_interface(interface_); }
  11537. // Copy logging and headers
  11538. if (logger_) { client.set_logger(logger_); }
  11539. if (error_logger_) { client.set_error_logger(error_logger_); }
  11540. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11541. // Each new client should generate its own headers based on its target host
  11542. }
  11543. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11544. const Request &req,
  11545. Error &error) const {
  11546. auto is_shutting_down = []() { return false; };
  11547. if (req.is_chunked_content_provider_) {
  11548. auto compressor = compress_ ? detail::create_compressor().first
  11549. : std::unique_ptr<detail::compressor>();
  11550. if (!compressor) {
  11551. compressor = detail::make_unique<detail::nocompressor>();
  11552. }
  11553. return detail::write_content_chunked(strm, req.content_provider_,
  11554. is_shutting_down, *compressor, error);
  11555. } else {
  11556. return detail::write_content_with_progress(
  11557. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11558. req.upload_progress, error);
  11559. }
  11560. }
  11561. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11562. bool close_connection, Error &error,
  11563. bool skip_body) {
  11564. // Prepare additional headers
  11565. if (close_connection) {
  11566. if (!req.has_header("Connection")) {
  11567. req.set_header("Connection", "close");
  11568. }
  11569. }
  11570. std::string ct_for_defaults;
  11571. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11572. ct_for_defaults = "text/plain";
  11573. }
  11574. prepare_default_headers(req, false, ct_for_defaults);
  11575. if (req.body.empty()) {
  11576. if (req.content_provider_) {
  11577. if (!req.is_chunked_content_provider_) {
  11578. if (!req.has_header("Content-Length")) {
  11579. auto length = std::to_string(req.content_length_);
  11580. req.set_header("Content-Length", length);
  11581. }
  11582. }
  11583. } else {
  11584. if (req.method == "POST" || req.method == "PUT" ||
  11585. req.method == "PATCH") {
  11586. req.set_header("Content-Length", "0");
  11587. }
  11588. }
  11589. }
  11590. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11591. if (!req.has_header("Authorization")) {
  11592. req.headers.insert(make_basic_authentication_header(
  11593. basic_auth_username_, basic_auth_password_, false));
  11594. }
  11595. }
  11596. if (!bearer_token_auth_token_.empty()) {
  11597. if (!req.has_header("Authorization")) {
  11598. req.headers.insert(make_bearer_token_authentication_header(
  11599. bearer_token_auth_token_, false));
  11600. }
  11601. }
  11602. // Proxy-Authorization is only sent when the proxy is actually used for
  11603. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11604. // credentials directly to the destination server.
  11605. if (is_proxy_enabled_for_host(host_)) {
  11606. if (!proxy_basic_auth_username_.empty() &&
  11607. !proxy_basic_auth_password_.empty() &&
  11608. !req.has_header("Proxy-Authorization")) {
  11609. req.headers.insert(make_basic_authentication_header(
  11610. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11611. }
  11612. if (!proxy_bearer_token_auth_token_.empty() &&
  11613. !req.has_header("Proxy-Authorization")) {
  11614. req.headers.insert(make_bearer_token_authentication_header(
  11615. proxy_bearer_token_auth_token_, true));
  11616. }
  11617. }
  11618. // Request line and headers
  11619. {
  11620. detail::BufferStream bstrm;
  11621. // Extract path and query from req.path
  11622. std::string path_part, query_part;
  11623. auto query_pos = req.path.find('?');
  11624. if (query_pos != std::string::npos) {
  11625. path_part = req.path.substr(0, query_pos);
  11626. query_part = req.path.substr(query_pos + 1);
  11627. } else {
  11628. path_part = req.path;
  11629. query_part = "";
  11630. }
  11631. // Encode path part. If the original `req.path` already contained a
  11632. // query component, preserve its raw query string (including parameter
  11633. // order) instead of reparsing and reassembling it which may reorder
  11634. // parameters due to container ordering (e.g. `Params` uses
  11635. // `std::multimap`). When there is no query in `req.path`, fall back to
  11636. // building a query from `req.params` so existing callers that pass
  11637. // `Params` continue to work.
  11638. auto path_with_query =
  11639. path_encode_ ? detail::encode_path(path_part) : path_part;
  11640. if (!query_part.empty()) {
  11641. // Normalize the query string (decode then re-encode) while preserving
  11642. // the original parameter order. When path encoding is disabled the
  11643. // caller has supplied an already-encoded target and expects the exact
  11644. // bytes to be sent on the wire, so skip normalization for the query
  11645. // too. Normalizing here would decode-then-re-encode the query and
  11646. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11647. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11648. if (path_encode_) {
  11649. auto normalized = detail::normalize_query_string(query_part);
  11650. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11651. } else {
  11652. path_with_query += '?' + query_part;
  11653. }
  11654. // Still populate req.params for handlers/users who read them.
  11655. detail::parse_query_text(query_part, req.params);
  11656. } else {
  11657. // No query in path; parse any query_part (empty) and append params
  11658. // from `req.params` when present (preserves prior behavior for
  11659. // callers who provide Params separately).
  11660. detail::parse_query_text(query_part, req.params);
  11661. if (!req.params.empty()) {
  11662. path_with_query = append_query_params(path_with_query, req.params);
  11663. }
  11664. }
  11665. // Write request line and headers
  11666. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  11667. // A rejected target (e.g. CR/LF smuggled in via a decoded redirect
  11668. // Location under set_path_encode(false)) must fail the request cleanly
  11669. // instead of emitting a request-line-less, header-injecting request.
  11670. error = Error::Write;
  11671. output_error_log(error, &req);
  11672. return false;
  11673. }
  11674. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11675. error)) {
  11676. output_error_log(error, &req);
  11677. return false;
  11678. }
  11679. // Flush buffer
  11680. auto &data = bstrm.get_buffer();
  11681. if (!detail::write_data(strm, data.data(), data.size())) {
  11682. error = Error::Write;
  11683. output_error_log(error, &req);
  11684. return false;
  11685. }
  11686. }
  11687. // After sending request line and headers, wait briefly for an early server
  11688. // response (e.g. 4xx) and avoid sending a potentially large request body
  11689. // unnecessarily. This workaround is only enabled on Windows because Unix
  11690. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11691. // buffering can accept large writes even when the peer already responded.
  11692. // Check the stream first (which covers SSL via `is_readable()`), then
  11693. // fall back to select on the socket. Only perform the wait for very large
  11694. // request bodies to avoid interfering with normal small requests and
  11695. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11696. // response. Skip this check when using Expect: 100-continue, as the protocol
  11697. // handles early responses properly.
  11698. #if defined(_WIN32)
  11699. if (!skip_body &&
  11700. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11701. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11702. auto start = std::chrono::high_resolution_clock::now();
  11703. for (;;) {
  11704. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11705. // from SSL internals. If the underlying socket is readable, assume an
  11706. // early response may be present.
  11707. auto sock = strm.socket();
  11708. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11709. return false;
  11710. }
  11711. // Fallback to stream-level check for non-socket streams or when the
  11712. // socket isn't reporting readable. Avoid using `is_readable()` for
  11713. // SSL, since `SSL_pending()` may report buffered records that do not
  11714. // indicate a complete application-level response yet.
  11715. if (!is_ssl() && strm.is_readable()) { return false; }
  11716. auto now = std::chrono::high_resolution_clock::now();
  11717. auto elapsed =
  11718. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11719. .count();
  11720. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11721. break;
  11722. }
  11723. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11724. }
  11725. }
  11726. #endif
  11727. // Body
  11728. if (skip_body) { return true; }
  11729. return write_request_body(strm, req, error);
  11730. }
  11731. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11732. Error &error) {
  11733. if (req.body.empty()) {
  11734. return write_content_with_provider(strm, req, error);
  11735. }
  11736. if (req.upload_progress) {
  11737. auto body_size = req.body.size();
  11738. size_t written = 0;
  11739. auto data = req.body.data();
  11740. while (written < body_size) {
  11741. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11742. if (!detail::write_data(strm, data + written, to_write)) {
  11743. error = Error::Write;
  11744. output_error_log(error, &req);
  11745. return false;
  11746. }
  11747. written += to_write;
  11748. if (!req.upload_progress(written, body_size)) {
  11749. error = Error::Canceled;
  11750. output_error_log(error, &req);
  11751. return false;
  11752. }
  11753. }
  11754. } else {
  11755. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11756. error = Error::Write;
  11757. output_error_log(error, &req);
  11758. return false;
  11759. }
  11760. }
  11761. return true;
  11762. }
  11763. inline std::unique_ptr<Response>
  11764. ClientImpl::send_with_content_provider_and_receiver(
  11765. Request &req, const char *body, size_t content_length,
  11766. ContentProvider content_provider,
  11767. ContentProviderWithoutLength content_provider_without_length,
  11768. const std::string &content_type, ContentReceiver content_receiver,
  11769. Error &error) {
  11770. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11771. auto enc = compress_
  11772. ? detail::create_compressor()
  11773. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11774. nullptr, nullptr);
  11775. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11776. if (enc.first && !content_provider_without_length) {
  11777. auto &compressor = enc.first;
  11778. if (content_provider) {
  11779. auto ok = true;
  11780. size_t offset = 0;
  11781. DataSink data_sink;
  11782. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11783. if (ok) {
  11784. auto last = offset + data_len == content_length;
  11785. auto ret = compressor->compress(
  11786. data, data_len, last,
  11787. [&](const char *compressed_data, size_t compressed_data_len) {
  11788. req.body.append(compressed_data, compressed_data_len);
  11789. return true;
  11790. });
  11791. if (ret) {
  11792. offset += data_len;
  11793. } else {
  11794. ok = false;
  11795. }
  11796. }
  11797. return ok;
  11798. };
  11799. while (ok && offset < content_length) {
  11800. if (!content_provider(offset, content_length - offset, data_sink)) {
  11801. error = Error::Canceled;
  11802. output_error_log(error, &req);
  11803. return nullptr;
  11804. }
  11805. }
  11806. } else {
  11807. if (!compressor->compress(body, content_length, true,
  11808. [&](const char *data, size_t data_len) {
  11809. req.body.append(data, data_len);
  11810. return true;
  11811. })) {
  11812. error = Error::Compression;
  11813. output_error_log(error, &req);
  11814. return nullptr;
  11815. }
  11816. }
  11817. } else {
  11818. if (content_provider) {
  11819. req.content_length_ = content_length;
  11820. req.content_provider_ = std::move(content_provider);
  11821. req.is_chunked_content_provider_ = false;
  11822. } else if (content_provider_without_length) {
  11823. req.content_length_ = 0;
  11824. req.content_provider_ = detail::ContentProviderAdapter(
  11825. std::move(content_provider_without_length));
  11826. req.is_chunked_content_provider_ = true;
  11827. req.set_header("Transfer-Encoding", "chunked");
  11828. } else {
  11829. req.body.assign(body, content_length);
  11830. }
  11831. }
  11832. if (content_receiver) {
  11833. req.content_receiver =
  11834. [content_receiver](const char *data, size_t data_length,
  11835. size_t /*offset*/, size_t /*total_length*/) {
  11836. return content_receiver(data, data_length);
  11837. };
  11838. }
  11839. auto res = detail::make_unique<Response>();
  11840. return send(req, *res, error) ? std::move(res) : nullptr;
  11841. }
  11842. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11843. const std::string &method, const std::string &path, const Headers &headers,
  11844. const char *body, size_t content_length, ContentProvider content_provider,
  11845. ContentProviderWithoutLength content_provider_without_length,
  11846. const std::string &content_type, ContentReceiver content_receiver,
  11847. UploadProgress progress) {
  11848. Request req;
  11849. req.method = method;
  11850. req.headers = headers;
  11851. req.path = path;
  11852. req.upload_progress = std::move(progress);
  11853. if (max_timeout_msec_ > 0) {
  11854. req.start_time_ = std::chrono::steady_clock::now();
  11855. }
  11856. auto error = Error::Success;
  11857. auto res = send_with_content_provider_and_receiver(
  11858. req, body, content_length, std::move(content_provider),
  11859. std::move(content_provider_without_length), content_type,
  11860. std::move(content_receiver), error);
  11861. #ifdef CPPHTTPLIB_SSL_ENABLED
  11862. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11863. last_backend_error_};
  11864. #else
  11865. return Result{std::move(res), error, std::move(req.headers)};
  11866. #endif
  11867. }
  11868. inline void ClientImpl::output_log(const Request &req,
  11869. const Response &res) const {
  11870. if (logger_) {
  11871. std::lock_guard<std::mutex> guard(logger_mutex_);
  11872. logger_(req, res);
  11873. }
  11874. }
  11875. inline void ClientImpl::output_error_log(const Error &err,
  11876. const Request *req) const {
  11877. if (error_logger_) {
  11878. std::lock_guard<std::mutex> guard(logger_mutex_);
  11879. error_logger_(err, req);
  11880. }
  11881. }
  11882. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11883. Response &res, bool close_connection,
  11884. Error &error) {
  11885. // Auto-add Expect: 100-continue for large bodies
  11886. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11887. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11888. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11889. req.set_header("Expect", "100-continue");
  11890. }
  11891. }
  11892. // Check for Expect: 100-continue
  11893. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11894. // Send request (skip body if using Expect: 100-continue)
  11895. auto write_request_success =
  11896. write_request(strm, req, close_connection, error, expect_100_continue);
  11897. #ifdef CPPHTTPLIB_SSL_ENABLED
  11898. if (is_ssl() && !expect_100_continue) {
  11899. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11900. if (!is_proxy_enabled) {
  11901. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11902. error = Error::SSLPeerCouldBeClosed_;
  11903. output_error_log(error, &req);
  11904. return false;
  11905. }
  11906. }
  11907. }
  11908. #endif
  11909. // Handle Expect: 100-continue.
  11910. //
  11911. // Wait for an interim/early response by attempting to read the status line
  11912. // under a short timeout, instead of trusting raw socket readability. Over
  11913. // TLS, post-handshake records (e.g. session tickets) make the socket
  11914. // readable without any HTTP response being available; relying on
  11915. // `select_read` there caused the body to be withheld forever and the
  11916. // request to fail with `Read` (#2458). If no status line arrives within the
  11917. // timeout, send the body anyway (matching curl's behavior).
  11918. auto status_line_read = false;
  11919. if (expect_100_continue && write_request_success) {
  11920. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11921. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11922. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11923. strm.set_read_timeout(sec, usec);
  11924. status_line_read = read_response_line(strm, req, res, false);
  11925. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11926. }
  11927. if (!status_line_read) {
  11928. // No interim response within the timeout: send the body and handle the
  11929. // response as usual.
  11930. if (!write_request_body(strm, req, error)) { return false; }
  11931. expect_100_continue = false; // Switch to normal response handling
  11932. }
  11933. }
  11934. // Receive response and headers
  11935. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11936. if ((!status_line_read &&
  11937. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11938. !detail::read_headers(strm, res.headers)) {
  11939. if (write_request_success) { error = Error::Read; }
  11940. output_error_log(error, &req);
  11941. return false;
  11942. }
  11943. if (!write_request_success) { return false; }
  11944. // Handle Expect: 100-continue response
  11945. if (expect_100_continue) {
  11946. if (res.status == StatusCode::Continue_100) {
  11947. // Server accepted, send the body
  11948. if (!write_request_body(strm, req, error)) { return false; }
  11949. // Read the actual response
  11950. res.headers.clear();
  11951. res.body.clear();
  11952. if (!read_response_line(strm, req, res) ||
  11953. !detail::read_headers(strm, res.headers)) {
  11954. error = Error::Read;
  11955. output_error_log(error, &req);
  11956. return false;
  11957. }
  11958. }
  11959. // If not 100 Continue, server returned an error; proceed with that response
  11960. }
  11961. // Body
  11962. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11963. req.method != "CONNECT") {
  11964. auto redirect = 300 < res.status && res.status < 400 &&
  11965. res.status != StatusCode::NotModified_304 &&
  11966. follow_location_;
  11967. if (req.response_handler && !redirect) {
  11968. if (!req.response_handler(res)) {
  11969. error = Error::Canceled;
  11970. output_error_log(error, &req);
  11971. return false;
  11972. }
  11973. }
  11974. auto out =
  11975. req.content_receiver
  11976. ? static_cast<ContentReceiverWithProgress>(
  11977. [&](const char *buf, size_t n, size_t off, size_t len) {
  11978. if (redirect) { return true; }
  11979. auto ret = req.content_receiver(buf, n, off, len);
  11980. if (!ret) {
  11981. error = Error::Canceled;
  11982. output_error_log(error, &req);
  11983. }
  11984. return ret;
  11985. })
  11986. : static_cast<ContentReceiverWithProgress>(
  11987. [&](const char *buf, size_t n, size_t /*off*/,
  11988. size_t /*len*/) {
  11989. assert(res.body.size() + n <= res.body.max_size());
  11990. if (payload_max_length_ > 0 &&
  11991. (res.body.size() >= payload_max_length_ ||
  11992. n > payload_max_length_ - res.body.size())) {
  11993. return false;
  11994. }
  11995. res.body.append(buf, n);
  11996. return true;
  11997. });
  11998. auto progress = [&](size_t current, size_t total) {
  11999. if (!req.download_progress || redirect) { return true; }
  12000. auto ret = req.download_progress(current, total);
  12001. if (!ret) {
  12002. error = Error::Canceled;
  12003. output_error_log(error, &req);
  12004. }
  12005. return ret;
  12006. };
  12007. if (res.has_header("Content-Length")) {
  12008. if (!req.content_receiver) {
  12009. auto len = res.get_header_value_u64("Content-Length");
  12010. if (len > res.body.max_size()) {
  12011. error = Error::Read;
  12012. output_error_log(error, &req);
  12013. return false;
  12014. }
  12015. // Cap the reservation by payload_max_length_ to avoid OOM when a
  12016. // hostile or malformed server sends an enormous Content-Length.
  12017. // The actual body read below is bounded by payload_max_length_,
  12018. // so reserving more than that is never useful.
  12019. auto reserve_len = static_cast<size_t>(len);
  12020. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  12021. reserve_len = payload_max_length_;
  12022. }
  12023. res.body.reserve(reserve_len);
  12024. }
  12025. }
  12026. if (res.status != StatusCode::NotModified_304) {
  12027. int dummy_status;
  12028. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  12029. ? (std::numeric_limits<size_t>::max)()
  12030. : payload_max_length_;
  12031. if (!detail::read_content(strm, res, max_length, dummy_status,
  12032. std::move(progress), std::move(out),
  12033. decompress_)) {
  12034. if (error != Error::Canceled) { error = Error::Read; }
  12035. output_error_log(error, &req);
  12036. return false;
  12037. }
  12038. }
  12039. }
  12040. // Log
  12041. output_log(req, res);
  12042. return true;
  12043. }
  12044. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  12045. const std::string &boundary, const UploadFormDataItems &items,
  12046. const FormDataProviderItems &provider_items) const {
  12047. size_t cur_item = 0;
  12048. size_t cur_start = 0;
  12049. // cur_item and cur_start are copied to within the std::function and
  12050. // maintain state between successive calls
  12051. return [&, cur_item, cur_start](size_t offset,
  12052. DataSink &sink) mutable -> bool {
  12053. if (!offset && !items.empty()) {
  12054. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12055. return true;
  12056. } else if (cur_item < provider_items.size()) {
  12057. if (!cur_start) {
  12058. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12059. provider_items[cur_item], boundary);
  12060. offset += begin.size();
  12061. cur_start = offset;
  12062. sink.os << begin;
  12063. }
  12064. DataSink cur_sink;
  12065. auto has_data = true;
  12066. cur_sink.write = sink.write;
  12067. cur_sink.done = [&]() { has_data = false; };
  12068. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12069. return false;
  12070. }
  12071. if (!has_data) {
  12072. sink.os << detail::serialize_multipart_formdata_item_end();
  12073. cur_item++;
  12074. cur_start = 0;
  12075. }
  12076. return true;
  12077. } else {
  12078. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12079. sink.done();
  12080. return true;
  12081. }
  12082. };
  12083. }
  12084. inline bool ClientImpl::process_socket(
  12085. const Socket &socket,
  12086. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12087. std::function<bool(Stream &strm)> callback) {
  12088. return detail::process_client_socket(
  12089. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12090. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12091. }
  12092. inline bool ClientImpl::is_ssl() const { return false; }
  12093. inline Result ClientImpl::Get(const std::string &path,
  12094. DownloadProgress progress) {
  12095. return Get(path, Headers(), std::move(progress));
  12096. }
  12097. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12098. DownloadProgress progress) {
  12099. return Get(path, params, Headers(), std::move(progress));
  12100. }
  12101. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12102. const Headers &headers,
  12103. DownloadProgress progress) {
  12104. if (params.empty()) { return Get(path, headers); }
  12105. std::string path_with_query = append_query_params(path, params);
  12106. return Get(path_with_query, headers, std::move(progress));
  12107. }
  12108. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12109. DownloadProgress progress) {
  12110. Request req;
  12111. req.method = "GET";
  12112. req.path = path;
  12113. req.headers = headers;
  12114. req.download_progress = std::move(progress);
  12115. if (max_timeout_msec_ > 0) {
  12116. req.start_time_ = std::chrono::steady_clock::now();
  12117. }
  12118. return send_(std::move(req));
  12119. }
  12120. inline Result ClientImpl::Get(const std::string &path,
  12121. ContentReceiver content_receiver,
  12122. DownloadProgress progress) {
  12123. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12124. std::move(progress));
  12125. }
  12126. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12127. ContentReceiver content_receiver,
  12128. DownloadProgress progress) {
  12129. return Get(path, headers, nullptr, std::move(content_receiver),
  12130. std::move(progress));
  12131. }
  12132. inline Result ClientImpl::Get(const std::string &path,
  12133. ResponseHandler response_handler,
  12134. ContentReceiver content_receiver,
  12135. DownloadProgress progress) {
  12136. return Get(path, Headers(), std::move(response_handler),
  12137. std::move(content_receiver), std::move(progress));
  12138. }
  12139. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12140. ResponseHandler response_handler,
  12141. ContentReceiver content_receiver,
  12142. DownloadProgress progress) {
  12143. Request req;
  12144. req.method = "GET";
  12145. req.path = path;
  12146. req.headers = headers;
  12147. req.response_handler = std::move(response_handler);
  12148. req.content_receiver =
  12149. [content_receiver](const char *data, size_t data_length,
  12150. size_t /*offset*/, size_t /*total_length*/) {
  12151. return content_receiver(data, data_length);
  12152. };
  12153. req.download_progress = std::move(progress);
  12154. if (max_timeout_msec_ > 0) {
  12155. req.start_time_ = std::chrono::steady_clock::now();
  12156. }
  12157. return send_(std::move(req));
  12158. }
  12159. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12160. const Headers &headers,
  12161. ContentReceiver content_receiver,
  12162. DownloadProgress progress) {
  12163. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12164. std::move(progress));
  12165. }
  12166. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12167. const Headers &headers,
  12168. ResponseHandler response_handler,
  12169. ContentReceiver content_receiver,
  12170. DownloadProgress progress) {
  12171. if (params.empty()) {
  12172. return Get(path, headers, std::move(response_handler),
  12173. std::move(content_receiver), std::move(progress));
  12174. }
  12175. std::string path_with_query = append_query_params(path, params);
  12176. return Get(path_with_query, headers, std::move(response_handler),
  12177. std::move(content_receiver), std::move(progress));
  12178. }
  12179. inline Result ClientImpl::Head(const std::string &path) {
  12180. return Head(path, Headers());
  12181. }
  12182. inline Result ClientImpl::Head(const std::string &path,
  12183. const Headers &headers) {
  12184. Request req;
  12185. req.method = "HEAD";
  12186. req.headers = headers;
  12187. req.path = path;
  12188. if (max_timeout_msec_ > 0) {
  12189. req.start_time_ = std::chrono::steady_clock::now();
  12190. }
  12191. return send_(std::move(req));
  12192. }
  12193. inline Result ClientImpl::Post(const std::string &path) {
  12194. return Post(path, std::string(), std::string());
  12195. }
  12196. inline Result ClientImpl::Post(const std::string &path,
  12197. const Headers &headers) {
  12198. return Post(path, headers, nullptr, 0, std::string());
  12199. }
  12200. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12201. size_t content_length,
  12202. const std::string &content_type,
  12203. UploadProgress progress) {
  12204. return Post(path, Headers(), body, content_length, content_type, progress);
  12205. }
  12206. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12207. const std::string &content_type,
  12208. UploadProgress progress) {
  12209. return Post(path, Headers(), body, content_type, progress);
  12210. }
  12211. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12212. return Post(path, Headers(), params);
  12213. }
  12214. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12215. ContentProvider content_provider,
  12216. const std::string &content_type,
  12217. UploadProgress progress) {
  12218. return Post(path, Headers(), content_length, std::move(content_provider),
  12219. content_type, progress);
  12220. }
  12221. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12222. ContentProvider content_provider,
  12223. const std::string &content_type,
  12224. ContentReceiver content_receiver,
  12225. UploadProgress progress) {
  12226. return Post(path, Headers(), content_length, std::move(content_provider),
  12227. content_type, std::move(content_receiver), progress);
  12228. }
  12229. inline Result ClientImpl::Post(const std::string &path,
  12230. ContentProviderWithoutLength content_provider,
  12231. const std::string &content_type,
  12232. UploadProgress progress) {
  12233. return Post(path, Headers(), std::move(content_provider), content_type,
  12234. progress);
  12235. }
  12236. inline Result ClientImpl::Post(const std::string &path,
  12237. ContentProviderWithoutLength content_provider,
  12238. const std::string &content_type,
  12239. ContentReceiver content_receiver,
  12240. UploadProgress progress) {
  12241. return Post(path, Headers(), std::move(content_provider), content_type,
  12242. std::move(content_receiver), progress);
  12243. }
  12244. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12245. const Params &params) {
  12246. auto query = detail::params_to_query_str(params);
  12247. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12248. }
  12249. inline Result ClientImpl::Post(const std::string &path,
  12250. const UploadFormDataItems &items,
  12251. UploadProgress progress) {
  12252. return Post(path, Headers(), items, progress);
  12253. }
  12254. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12255. const UploadFormDataItems &items,
  12256. UploadProgress progress) {
  12257. const auto &boundary = detail::make_multipart_data_boundary();
  12258. const auto &content_type =
  12259. detail::serialize_multipart_formdata_get_content_type(boundary);
  12260. auto content_length = detail::get_multipart_content_length(items, boundary);
  12261. return Post(path, headers, content_length,
  12262. detail::make_multipart_content_provider(items, boundary),
  12263. content_type, progress);
  12264. }
  12265. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12266. const UploadFormDataItems &items,
  12267. const std::string &boundary,
  12268. UploadProgress progress) {
  12269. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12270. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12271. }
  12272. const auto &content_type =
  12273. detail::serialize_multipart_formdata_get_content_type(boundary);
  12274. auto content_length = detail::get_multipart_content_length(items, boundary);
  12275. return Post(path, headers, content_length,
  12276. detail::make_multipart_content_provider(items, boundary),
  12277. content_type, progress);
  12278. }
  12279. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12280. const char *body, size_t content_length,
  12281. const std::string &content_type,
  12282. UploadProgress progress) {
  12283. return send_with_content_provider_and_receiver(
  12284. "POST", path, headers, body, content_length, nullptr, nullptr,
  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. UploadProgress progress) {
  12291. return send_with_content_provider_and_receiver(
  12292. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12293. content_type, nullptr, progress);
  12294. }
  12295. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12296. size_t content_length,
  12297. ContentProvider content_provider,
  12298. const std::string &content_type,
  12299. UploadProgress progress) {
  12300. return send_with_content_provider_and_receiver(
  12301. "POST", path, headers, nullptr, content_length,
  12302. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12303. }
  12304. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12305. size_t content_length,
  12306. ContentProvider content_provider,
  12307. const std::string &content_type,
  12308. ContentReceiver content_receiver,
  12309. DownloadProgress progress) {
  12310. return send_with_content_provider_and_receiver(
  12311. "POST", path, headers, nullptr, content_length,
  12312. std::move(content_provider), nullptr, content_type,
  12313. std::move(content_receiver), std::move(progress));
  12314. }
  12315. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12316. ContentProviderWithoutLength content_provider,
  12317. const std::string &content_type,
  12318. UploadProgress progress) {
  12319. return send_with_content_provider_and_receiver(
  12320. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12321. content_type, nullptr, progress);
  12322. }
  12323. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12324. ContentProviderWithoutLength content_provider,
  12325. const std::string &content_type,
  12326. ContentReceiver content_receiver,
  12327. DownloadProgress progress) {
  12328. return send_with_content_provider_and_receiver(
  12329. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12330. content_type, std::move(content_receiver), std::move(progress));
  12331. }
  12332. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12333. const UploadFormDataItems &items,
  12334. const FormDataProviderItems &provider_items,
  12335. UploadProgress progress) {
  12336. const auto &boundary = detail::make_multipart_data_boundary();
  12337. const auto &content_type =
  12338. detail::serialize_multipart_formdata_get_content_type(boundary);
  12339. return send_with_content_provider_and_receiver(
  12340. "POST", path, headers, nullptr, 0, nullptr,
  12341. get_multipart_content_provider(boundary, items, provider_items),
  12342. content_type, nullptr, progress);
  12343. }
  12344. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12345. const std::string &body,
  12346. const std::string &content_type,
  12347. ContentReceiver content_receiver,
  12348. DownloadProgress progress) {
  12349. Request req;
  12350. req.method = "POST";
  12351. req.path = path;
  12352. req.headers = headers;
  12353. req.body = body;
  12354. req.content_receiver =
  12355. [content_receiver](const char *data, size_t data_length,
  12356. size_t /*offset*/, size_t /*total_length*/) {
  12357. return content_receiver(data, data_length);
  12358. };
  12359. req.download_progress = std::move(progress);
  12360. if (max_timeout_msec_ > 0) {
  12361. req.start_time_ = std::chrono::steady_clock::now();
  12362. }
  12363. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12364. return send_(std::move(req));
  12365. }
  12366. inline Result ClientImpl::Put(const std::string &path) {
  12367. return Put(path, std::string(), std::string());
  12368. }
  12369. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12370. return Put(path, headers, nullptr, 0, std::string());
  12371. }
  12372. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12373. size_t content_length,
  12374. const std::string &content_type,
  12375. UploadProgress progress) {
  12376. return Put(path, Headers(), body, content_length, content_type, progress);
  12377. }
  12378. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12379. const std::string &content_type,
  12380. UploadProgress progress) {
  12381. return Put(path, Headers(), body, content_type, progress);
  12382. }
  12383. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12384. return Put(path, Headers(), params);
  12385. }
  12386. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12387. ContentProvider content_provider,
  12388. const std::string &content_type,
  12389. UploadProgress progress) {
  12390. return Put(path, Headers(), content_length, std::move(content_provider),
  12391. content_type, progress);
  12392. }
  12393. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12394. ContentProvider content_provider,
  12395. const std::string &content_type,
  12396. ContentReceiver content_receiver,
  12397. UploadProgress progress) {
  12398. return Put(path, Headers(), content_length, std::move(content_provider),
  12399. content_type, std::move(content_receiver), progress);
  12400. }
  12401. inline Result ClientImpl::Put(const std::string &path,
  12402. ContentProviderWithoutLength content_provider,
  12403. const std::string &content_type,
  12404. UploadProgress progress) {
  12405. return Put(path, Headers(), std::move(content_provider), content_type,
  12406. progress);
  12407. }
  12408. inline Result ClientImpl::Put(const std::string &path,
  12409. ContentProviderWithoutLength content_provider,
  12410. const std::string &content_type,
  12411. ContentReceiver content_receiver,
  12412. UploadProgress progress) {
  12413. return Put(path, Headers(), std::move(content_provider), content_type,
  12414. std::move(content_receiver), progress);
  12415. }
  12416. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12417. const Params &params) {
  12418. auto query = detail::params_to_query_str(params);
  12419. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12420. }
  12421. inline Result ClientImpl::Put(const std::string &path,
  12422. const UploadFormDataItems &items,
  12423. UploadProgress progress) {
  12424. return Put(path, Headers(), items, progress);
  12425. }
  12426. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12427. const UploadFormDataItems &items,
  12428. UploadProgress progress) {
  12429. const auto &boundary = detail::make_multipart_data_boundary();
  12430. const auto &content_type =
  12431. detail::serialize_multipart_formdata_get_content_type(boundary);
  12432. auto content_length = detail::get_multipart_content_length(items, boundary);
  12433. return Put(path, headers, content_length,
  12434. detail::make_multipart_content_provider(items, boundary),
  12435. content_type, progress);
  12436. }
  12437. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12438. const UploadFormDataItems &items,
  12439. const std::string &boundary,
  12440. UploadProgress progress) {
  12441. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12442. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12443. }
  12444. const auto &content_type =
  12445. detail::serialize_multipart_formdata_get_content_type(boundary);
  12446. auto content_length = detail::get_multipart_content_length(items, boundary);
  12447. return Put(path, headers, content_length,
  12448. detail::make_multipart_content_provider(items, boundary),
  12449. content_type, progress);
  12450. }
  12451. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12452. const char *body, size_t content_length,
  12453. const std::string &content_type,
  12454. UploadProgress progress) {
  12455. return send_with_content_provider_and_receiver(
  12456. "PUT", path, headers, body, content_length, nullptr, nullptr,
  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. UploadProgress progress) {
  12463. return send_with_content_provider_and_receiver(
  12464. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12465. content_type, nullptr, progress);
  12466. }
  12467. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12468. size_t content_length,
  12469. ContentProvider content_provider,
  12470. const std::string &content_type,
  12471. UploadProgress progress) {
  12472. return send_with_content_provider_and_receiver(
  12473. "PUT", path, headers, nullptr, content_length,
  12474. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12475. }
  12476. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12477. size_t content_length,
  12478. ContentProvider content_provider,
  12479. const std::string &content_type,
  12480. ContentReceiver content_receiver,
  12481. UploadProgress progress) {
  12482. return send_with_content_provider_and_receiver(
  12483. "PUT", path, headers, nullptr, content_length,
  12484. std::move(content_provider), nullptr, content_type,
  12485. std::move(content_receiver), progress);
  12486. }
  12487. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12488. ContentProviderWithoutLength content_provider,
  12489. const std::string &content_type,
  12490. UploadProgress progress) {
  12491. return send_with_content_provider_and_receiver(
  12492. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12493. content_type, nullptr, progress);
  12494. }
  12495. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12496. ContentProviderWithoutLength content_provider,
  12497. const std::string &content_type,
  12498. ContentReceiver content_receiver,
  12499. UploadProgress progress) {
  12500. return send_with_content_provider_and_receiver(
  12501. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12502. content_type, std::move(content_receiver), progress);
  12503. }
  12504. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12505. const UploadFormDataItems &items,
  12506. const FormDataProviderItems &provider_items,
  12507. UploadProgress progress) {
  12508. const auto &boundary = detail::make_multipart_data_boundary();
  12509. const auto &content_type =
  12510. detail::serialize_multipart_formdata_get_content_type(boundary);
  12511. return send_with_content_provider_and_receiver(
  12512. "PUT", path, headers, nullptr, 0, nullptr,
  12513. get_multipart_content_provider(boundary, items, provider_items),
  12514. content_type, nullptr, progress);
  12515. }
  12516. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12517. const std::string &body,
  12518. const std::string &content_type,
  12519. ContentReceiver content_receiver,
  12520. DownloadProgress progress) {
  12521. Request req;
  12522. req.method = "PUT";
  12523. req.path = path;
  12524. req.headers = headers;
  12525. req.body = body;
  12526. req.content_receiver =
  12527. [content_receiver](const char *data, size_t data_length,
  12528. size_t /*offset*/, size_t /*total_length*/) {
  12529. return content_receiver(data, data_length);
  12530. };
  12531. req.download_progress = std::move(progress);
  12532. if (max_timeout_msec_ > 0) {
  12533. req.start_time_ = std::chrono::steady_clock::now();
  12534. }
  12535. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12536. return send_(std::move(req));
  12537. }
  12538. inline Result ClientImpl::Patch(const std::string &path) {
  12539. return Patch(path, std::string(), std::string());
  12540. }
  12541. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12542. UploadProgress progress) {
  12543. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12544. }
  12545. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12546. size_t content_length,
  12547. const std::string &content_type,
  12548. UploadProgress progress) {
  12549. return Patch(path, Headers(), body, content_length, content_type, progress);
  12550. }
  12551. inline Result ClientImpl::Patch(const std::string &path,
  12552. const std::string &body,
  12553. const std::string &content_type,
  12554. UploadProgress progress) {
  12555. return Patch(path, Headers(), body, content_type, progress);
  12556. }
  12557. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12558. return Patch(path, Headers(), params);
  12559. }
  12560. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12561. ContentProvider content_provider,
  12562. const std::string &content_type,
  12563. UploadProgress progress) {
  12564. return Patch(path, Headers(), content_length, std::move(content_provider),
  12565. content_type, progress);
  12566. }
  12567. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12568. ContentProvider content_provider,
  12569. const std::string &content_type,
  12570. ContentReceiver content_receiver,
  12571. UploadProgress progress) {
  12572. return Patch(path, Headers(), content_length, std::move(content_provider),
  12573. content_type, std::move(content_receiver), progress);
  12574. }
  12575. inline Result ClientImpl::Patch(const std::string &path,
  12576. ContentProviderWithoutLength content_provider,
  12577. const std::string &content_type,
  12578. UploadProgress progress) {
  12579. return Patch(path, Headers(), std::move(content_provider), content_type,
  12580. progress);
  12581. }
  12582. inline Result ClientImpl::Patch(const std::string &path,
  12583. ContentProviderWithoutLength content_provider,
  12584. const std::string &content_type,
  12585. ContentReceiver content_receiver,
  12586. UploadProgress progress) {
  12587. return Patch(path, Headers(), std::move(content_provider), content_type,
  12588. std::move(content_receiver), progress);
  12589. }
  12590. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12591. const Params &params) {
  12592. auto query = detail::params_to_query_str(params);
  12593. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12594. }
  12595. inline Result ClientImpl::Patch(const std::string &path,
  12596. const UploadFormDataItems &items,
  12597. UploadProgress progress) {
  12598. return Patch(path, Headers(), items, progress);
  12599. }
  12600. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12601. const UploadFormDataItems &items,
  12602. UploadProgress progress) {
  12603. const auto &boundary = detail::make_multipart_data_boundary();
  12604. const auto &content_type =
  12605. detail::serialize_multipart_formdata_get_content_type(boundary);
  12606. auto content_length = detail::get_multipart_content_length(items, boundary);
  12607. return Patch(path, headers, content_length,
  12608. detail::make_multipart_content_provider(items, boundary),
  12609. content_type, progress);
  12610. }
  12611. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12612. const UploadFormDataItems &items,
  12613. const std::string &boundary,
  12614. UploadProgress progress) {
  12615. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12616. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12617. }
  12618. const auto &content_type =
  12619. detail::serialize_multipart_formdata_get_content_type(boundary);
  12620. auto content_length = detail::get_multipart_content_length(items, boundary);
  12621. return Patch(path, headers, content_length,
  12622. detail::make_multipart_content_provider(items, boundary),
  12623. content_type, progress);
  12624. }
  12625. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12626. const char *body, size_t content_length,
  12627. const std::string &content_type,
  12628. UploadProgress progress) {
  12629. return send_with_content_provider_and_receiver(
  12630. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  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. UploadProgress progress) {
  12637. return send_with_content_provider_and_receiver(
  12638. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12639. content_type, nullptr, progress);
  12640. }
  12641. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12642. size_t content_length,
  12643. ContentProvider content_provider,
  12644. const std::string &content_type,
  12645. UploadProgress progress) {
  12646. return send_with_content_provider_and_receiver(
  12647. "PATCH", path, headers, nullptr, content_length,
  12648. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12649. }
  12650. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12651. size_t content_length,
  12652. ContentProvider content_provider,
  12653. const std::string &content_type,
  12654. ContentReceiver content_receiver,
  12655. UploadProgress progress) {
  12656. return send_with_content_provider_and_receiver(
  12657. "PATCH", path, headers, nullptr, content_length,
  12658. std::move(content_provider), nullptr, content_type,
  12659. std::move(content_receiver), progress);
  12660. }
  12661. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12662. ContentProviderWithoutLength content_provider,
  12663. const std::string &content_type,
  12664. UploadProgress progress) {
  12665. return send_with_content_provider_and_receiver(
  12666. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12667. content_type, nullptr, progress);
  12668. }
  12669. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12670. ContentProviderWithoutLength content_provider,
  12671. const std::string &content_type,
  12672. ContentReceiver content_receiver,
  12673. UploadProgress progress) {
  12674. return send_with_content_provider_and_receiver(
  12675. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12676. content_type, std::move(content_receiver), progress);
  12677. }
  12678. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12679. const UploadFormDataItems &items,
  12680. const FormDataProviderItems &provider_items,
  12681. UploadProgress progress) {
  12682. const auto &boundary = detail::make_multipart_data_boundary();
  12683. const auto &content_type =
  12684. detail::serialize_multipart_formdata_get_content_type(boundary);
  12685. return send_with_content_provider_and_receiver(
  12686. "PATCH", path, headers, nullptr, 0, nullptr,
  12687. get_multipart_content_provider(boundary, items, provider_items),
  12688. content_type, nullptr, progress);
  12689. }
  12690. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12691. const std::string &body,
  12692. const std::string &content_type,
  12693. ContentReceiver content_receiver,
  12694. DownloadProgress progress) {
  12695. Request req;
  12696. req.method = "PATCH";
  12697. req.path = path;
  12698. req.headers = headers;
  12699. req.body = body;
  12700. req.content_receiver =
  12701. [content_receiver](const char *data, size_t data_length,
  12702. size_t /*offset*/, size_t /*total_length*/) {
  12703. return content_receiver(data, data_length);
  12704. };
  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. return send_(std::move(req));
  12711. }
  12712. inline Result ClientImpl::Delete(const std::string &path,
  12713. DownloadProgress progress) {
  12714. return Delete(path, Headers(), std::string(), std::string(), progress);
  12715. }
  12716. inline Result ClientImpl::Delete(const std::string &path,
  12717. const Headers &headers,
  12718. DownloadProgress progress) {
  12719. return Delete(path, headers, std::string(), std::string(), progress);
  12720. }
  12721. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12722. size_t content_length,
  12723. const std::string &content_type,
  12724. DownloadProgress progress) {
  12725. return Delete(path, Headers(), body, content_length, content_type, progress);
  12726. }
  12727. inline Result ClientImpl::Delete(const std::string &path,
  12728. const std::string &body,
  12729. const std::string &content_type,
  12730. DownloadProgress progress) {
  12731. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12732. progress);
  12733. }
  12734. inline Result ClientImpl::Delete(const std::string &path,
  12735. const Headers &headers,
  12736. const std::string &body,
  12737. const std::string &content_type,
  12738. DownloadProgress progress) {
  12739. return Delete(path, headers, body.data(), body.size(), content_type,
  12740. progress);
  12741. }
  12742. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12743. DownloadProgress progress) {
  12744. return Delete(path, Headers(), params, progress);
  12745. }
  12746. inline Result ClientImpl::Delete(const std::string &path,
  12747. const Headers &headers, const Params &params,
  12748. DownloadProgress progress) {
  12749. auto query = detail::params_to_query_str(params);
  12750. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12751. progress);
  12752. }
  12753. inline Result ClientImpl::Delete(const std::string &path,
  12754. const Headers &headers, const char *body,
  12755. size_t content_length,
  12756. const std::string &content_type,
  12757. DownloadProgress progress) {
  12758. Request req;
  12759. req.method = "DELETE";
  12760. req.headers = headers;
  12761. req.path = path;
  12762. req.download_progress = std::move(progress);
  12763. if (max_timeout_msec_ > 0) {
  12764. req.start_time_ = std::chrono::steady_clock::now();
  12765. }
  12766. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12767. req.body.assign(body, content_length);
  12768. return send_(std::move(req));
  12769. }
  12770. inline Result ClientImpl::Options(const std::string &path) {
  12771. return Options(path, Headers());
  12772. }
  12773. inline Result ClientImpl::Options(const std::string &path,
  12774. const Headers &headers) {
  12775. Request req;
  12776. req.method = "OPTIONS";
  12777. req.headers = headers;
  12778. req.path = path;
  12779. if (max_timeout_msec_ > 0) {
  12780. req.start_time_ = std::chrono::steady_clock::now();
  12781. }
  12782. return send_(std::move(req));
  12783. }
  12784. inline void ClientImpl::stop() {
  12785. std::lock_guard<std::mutex> guard(socket_mutex_);
  12786. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12787. // do is to shutdown_socket, so that threads using this socket suddenly
  12788. // discover they can't read/write any more and error out. Everything else
  12789. // (closing the socket, shutting ssl down) is unsafe because these actions
  12790. // are not thread-safe.
  12791. if (socket_requests_in_flight_ > 0) {
  12792. shutdown_socket(socket_);
  12793. // Aside from that, we set a flag for the socket to be closed when we're
  12794. // done.
  12795. socket_should_be_closed_when_request_is_done_ = true;
  12796. return;
  12797. }
  12798. disconnect(/*gracefully=*/true);
  12799. }
  12800. inline std::string ClientImpl::host() const { return host_; }
  12801. inline int ClientImpl::port() const { return port_; }
  12802. inline size_t ClientImpl::is_socket_open() const {
  12803. std::lock_guard<std::mutex> guard(socket_mutex_);
  12804. return socket_.is_open();
  12805. }
  12806. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12807. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12808. connection_timeout_sec_ = sec;
  12809. connection_timeout_usec_ = usec;
  12810. }
  12811. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12812. read_timeout_sec_ = sec;
  12813. read_timeout_usec_ = usec;
  12814. }
  12815. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12816. write_timeout_sec_ = sec;
  12817. write_timeout_usec_ = usec;
  12818. }
  12819. inline void ClientImpl::set_max_timeout(time_t msec) {
  12820. max_timeout_msec_ = msec;
  12821. }
  12822. inline void ClientImpl::set_basic_auth(const std::string &username,
  12823. const std::string &password) {
  12824. basic_auth_username_ = username;
  12825. basic_auth_password_ = password;
  12826. }
  12827. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12828. bearer_token_auth_token_ = token;
  12829. }
  12830. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12831. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12832. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12833. inline void
  12834. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12835. addr_map_ = std::move(addr_map);
  12836. }
  12837. inline void ClientImpl::set_default_headers(Headers headers) {
  12838. default_headers_ = std::move(headers);
  12839. }
  12840. inline void ClientImpl::set_header_writer(
  12841. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12842. header_writer_ = writer;
  12843. }
  12844. inline void ClientImpl::set_address_family(int family) {
  12845. address_family_ = family;
  12846. }
  12847. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12848. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12849. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12850. socket_options_ = std::move(socket_options);
  12851. }
  12852. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12853. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12854. inline void ClientImpl::set_payload_max_length(size_t length) {
  12855. payload_max_length_ = length;
  12856. has_payload_max_length_ = true;
  12857. }
  12858. inline void ClientImpl::set_interface(const std::string &intf) {
  12859. interface_ = intf;
  12860. }
  12861. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12862. proxy_host_ = host;
  12863. proxy_port_ = port;
  12864. std::lock_guard<std::mutex> guard(socket_mutex_);
  12865. disconnect(/*gracefully=*/true);
  12866. }
  12867. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12868. const std::string &password) {
  12869. proxy_basic_auth_username_ = username;
  12870. proxy_basic_auth_password_ = password;
  12871. }
  12872. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12873. proxy_bearer_token_auth_token_ = token;
  12874. }
  12875. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12876. std::vector<detail::NoProxyEntry> parsed;
  12877. parsed.reserve(patterns.size());
  12878. for (const auto &p : patterns) {
  12879. auto trimmed = detail::trim_copy(p);
  12880. if (trimmed.empty()) { continue; }
  12881. detail::NoProxyEntry entry;
  12882. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12883. parsed.push_back(std::move(entry));
  12884. }
  12885. }
  12886. no_proxy_entries_ = std::move(parsed);
  12887. std::lock_guard<std::mutex> guard(socket_mutex_);
  12888. disconnect(/*gracefully=*/true);
  12889. }
  12890. #ifdef CPPHTTPLIB_SSL_ENABLED
  12891. inline void ClientImpl::set_digest_auth(const std::string &username,
  12892. const std::string &password) {
  12893. digest_auth_username_ = username;
  12894. digest_auth_password_ = password;
  12895. }
  12896. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12897. const std::string &ca_cert_dir_path) {
  12898. ca_cert_file_path_ = ca_cert_file_path;
  12899. ca_cert_dir_path_ = ca_cert_dir_path;
  12900. }
  12901. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12902. const std::string &password) {
  12903. proxy_digest_auth_username_ = username;
  12904. proxy_digest_auth_password_ = password;
  12905. }
  12906. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12907. server_certificate_verification_ = enabled;
  12908. }
  12909. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12910. server_hostname_verification_ = enabled;
  12911. }
  12912. inline void ClientImpl::enable_system_ca(bool enabled) {
  12913. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12914. }
  12915. #endif
  12916. inline void ClientImpl::set_logger(Logger logger) {
  12917. logger_ = std::move(logger);
  12918. }
  12919. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12920. error_logger_ = std::move(error_logger);
  12921. }
  12922. /*
  12923. * SSL/TLS Common Implementation
  12924. */
  12925. inline ClientConnection::~ClientConnection() {
  12926. #ifdef CPPHTTPLIB_SSL_ENABLED
  12927. if (session) {
  12928. tls::shutdown(session, true);
  12929. tls::free_session(session);
  12930. session = nullptr;
  12931. }
  12932. #endif
  12933. if (sock != INVALID_SOCKET) {
  12934. detail::close_socket(sock);
  12935. sock = INVALID_SOCKET;
  12936. }
  12937. }
  12938. // Universal client implementation
  12939. inline Client::Client(const std::string &scheme_host_port)
  12940. : Client(scheme_host_port, std::string(), std::string()) {}
  12941. inline Client::Client(const std::string &scheme_host_port,
  12942. const std::string &client_cert_path,
  12943. const std::string &client_key_path) {
  12944. detail::UrlComponents uc;
  12945. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12946. auto &scheme = uc.scheme;
  12947. #ifdef CPPHTTPLIB_SSL_ENABLED
  12948. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12949. #else
  12950. if (!scheme.empty() && scheme != "http") {
  12951. #endif
  12952. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12953. std::string msg = "'" + scheme + "' scheme is not supported.";
  12954. throw std::invalid_argument(msg);
  12955. #endif
  12956. return;
  12957. }
  12958. auto is_ssl = scheme == "https";
  12959. auto host = std::move(uc.host);
  12960. auto port = is_ssl ? 443 : 80;
  12961. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12962. if (is_ssl) {
  12963. #ifdef CPPHTTPLIB_SSL_ENABLED
  12964. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12965. client_key_path);
  12966. is_ssl_ = is_ssl;
  12967. #endif
  12968. } else {
  12969. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12970. client_key_path);
  12971. }
  12972. } else {
  12973. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12974. // if port param below changes.
  12975. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12976. client_cert_path, client_key_path);
  12977. }
  12978. }
  12979. inline Client::Client(const std::string &host, int port)
  12980. : Client(host, port, std::string(), std::string()) {}
  12981. inline Client::Client(const std::string &host, int port,
  12982. const std::string &client_cert_path,
  12983. const std::string &client_key_path)
  12984. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12985. client_key_path)) {}
  12986. inline Client::~Client() = default;
  12987. inline bool Client::is_valid() const {
  12988. return cli_ != nullptr && cli_->is_valid();
  12989. }
  12990. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12991. return cli_->Get(path, std::move(progress));
  12992. }
  12993. inline Result Client::Get(const std::string &path, const Headers &headers,
  12994. DownloadProgress progress) {
  12995. return cli_->Get(path, headers, std::move(progress));
  12996. }
  12997. inline Result Client::Get(const std::string &path,
  12998. ContentReceiver content_receiver,
  12999. DownloadProgress progress) {
  13000. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13001. }
  13002. inline Result Client::Get(const std::string &path, const Headers &headers,
  13003. ContentReceiver content_receiver,
  13004. DownloadProgress progress) {
  13005. return cli_->Get(path, headers, std::move(content_receiver),
  13006. std::move(progress));
  13007. }
  13008. inline Result Client::Get(const std::string &path,
  13009. ResponseHandler response_handler,
  13010. ContentReceiver content_receiver,
  13011. DownloadProgress progress) {
  13012. return cli_->Get(path, std::move(response_handler),
  13013. std::move(content_receiver), std::move(progress));
  13014. }
  13015. inline Result Client::Get(const std::string &path, const Headers &headers,
  13016. ResponseHandler response_handler,
  13017. ContentReceiver content_receiver,
  13018. DownloadProgress progress) {
  13019. return cli_->Get(path, headers, std::move(response_handler),
  13020. std::move(content_receiver), std::move(progress));
  13021. }
  13022. inline Result Client::Get(const std::string &path, const Params &params,
  13023. DownloadProgress progress) {
  13024. return cli_->Get(path, params, std::move(progress));
  13025. }
  13026. inline Result Client::Get(const std::string &path, const Params &params,
  13027. const Headers &headers, DownloadProgress progress) {
  13028. return cli_->Get(path, params, headers, std::move(progress));
  13029. }
  13030. inline Result Client::Get(const std::string &path, const Params &params,
  13031. const Headers &headers,
  13032. ContentReceiver content_receiver,
  13033. DownloadProgress progress) {
  13034. return cli_->Get(path, params, headers, std::move(content_receiver),
  13035. std::move(progress));
  13036. }
  13037. inline Result Client::Get(const std::string &path, const Params &params,
  13038. const Headers &headers,
  13039. ResponseHandler response_handler,
  13040. ContentReceiver content_receiver,
  13041. DownloadProgress progress) {
  13042. return cli_->Get(path, params, headers, std::move(response_handler),
  13043. std::move(content_receiver), std::move(progress));
  13044. }
  13045. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13046. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13047. return cli_->Head(path, headers);
  13048. }
  13049. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13050. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13051. return cli_->Post(path, headers);
  13052. }
  13053. inline Result Client::Post(const std::string &path, const char *body,
  13054. size_t content_length,
  13055. const std::string &content_type,
  13056. UploadProgress progress) {
  13057. return cli_->Post(path, body, content_length, content_type, progress);
  13058. }
  13059. inline Result Client::Post(const std::string &path, const Headers &headers,
  13060. const char *body, size_t content_length,
  13061. const std::string &content_type,
  13062. UploadProgress progress) {
  13063. return cli_->Post(path, headers, body, content_length, content_type,
  13064. progress);
  13065. }
  13066. inline Result Client::Post(const std::string &path, const std::string &body,
  13067. const std::string &content_type,
  13068. UploadProgress progress) {
  13069. return cli_->Post(path, body, content_type, progress);
  13070. }
  13071. inline Result Client::Post(const std::string &path, const Headers &headers,
  13072. const std::string &body,
  13073. const std::string &content_type,
  13074. UploadProgress progress) {
  13075. return cli_->Post(path, headers, body, content_type, progress);
  13076. }
  13077. inline Result Client::Post(const std::string &path, size_t content_length,
  13078. ContentProvider content_provider,
  13079. const std::string &content_type,
  13080. UploadProgress progress) {
  13081. return cli_->Post(path, content_length, std::move(content_provider),
  13082. content_type, progress);
  13083. }
  13084. inline Result Client::Post(const std::string &path, size_t content_length,
  13085. ContentProvider content_provider,
  13086. const std::string &content_type,
  13087. ContentReceiver content_receiver,
  13088. UploadProgress progress) {
  13089. return cli_->Post(path, content_length, std::move(content_provider),
  13090. content_type, std::move(content_receiver), progress);
  13091. }
  13092. inline Result Client::Post(const std::string &path,
  13093. ContentProviderWithoutLength content_provider,
  13094. const std::string &content_type,
  13095. UploadProgress progress) {
  13096. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13097. }
  13098. inline Result Client::Post(const std::string &path,
  13099. ContentProviderWithoutLength content_provider,
  13100. const std::string &content_type,
  13101. ContentReceiver content_receiver,
  13102. UploadProgress progress) {
  13103. return cli_->Post(path, std::move(content_provider), content_type,
  13104. std::move(content_receiver), progress);
  13105. }
  13106. inline Result Client::Post(const std::string &path, const Headers &headers,
  13107. size_t content_length,
  13108. ContentProvider content_provider,
  13109. const std::string &content_type,
  13110. UploadProgress progress) {
  13111. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13112. content_type, progress);
  13113. }
  13114. inline Result Client::Post(const std::string &path, const Headers &headers,
  13115. size_t content_length,
  13116. ContentProvider content_provider,
  13117. const std::string &content_type,
  13118. ContentReceiver content_receiver,
  13119. DownloadProgress progress) {
  13120. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13121. content_type, std::move(content_receiver), progress);
  13122. }
  13123. inline Result Client::Post(const std::string &path, const Headers &headers,
  13124. ContentProviderWithoutLength content_provider,
  13125. const std::string &content_type,
  13126. UploadProgress progress) {
  13127. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13128. progress);
  13129. }
  13130. inline Result Client::Post(const std::string &path, const Headers &headers,
  13131. ContentProviderWithoutLength content_provider,
  13132. const std::string &content_type,
  13133. ContentReceiver content_receiver,
  13134. DownloadProgress progress) {
  13135. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13136. std::move(content_receiver), progress);
  13137. }
  13138. inline Result Client::Post(const std::string &path, const Params &params) {
  13139. return cli_->Post(path, params);
  13140. }
  13141. inline Result Client::Post(const std::string &path, const Headers &headers,
  13142. const Params &params) {
  13143. return cli_->Post(path, headers, params);
  13144. }
  13145. inline Result Client::Post(const std::string &path,
  13146. const UploadFormDataItems &items,
  13147. UploadProgress progress) {
  13148. return cli_->Post(path, items, progress);
  13149. }
  13150. inline Result Client::Post(const std::string &path, const Headers &headers,
  13151. const UploadFormDataItems &items,
  13152. UploadProgress progress) {
  13153. return cli_->Post(path, headers, items, progress);
  13154. }
  13155. inline Result Client::Post(const std::string &path, const Headers &headers,
  13156. const UploadFormDataItems &items,
  13157. const std::string &boundary,
  13158. UploadProgress progress) {
  13159. return cli_->Post(path, headers, items, boundary, progress);
  13160. }
  13161. inline Result Client::Post(const std::string &path, const Headers &headers,
  13162. const UploadFormDataItems &items,
  13163. const FormDataProviderItems &provider_items,
  13164. UploadProgress progress) {
  13165. return cli_->Post(path, headers, items, provider_items, progress);
  13166. }
  13167. inline Result Client::Post(const std::string &path, const Headers &headers,
  13168. const std::string &body,
  13169. const std::string &content_type,
  13170. ContentReceiver content_receiver,
  13171. DownloadProgress progress) {
  13172. return cli_->Post(path, headers, body, content_type,
  13173. std::move(content_receiver), progress);
  13174. }
  13175. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13176. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13177. return cli_->Put(path, headers);
  13178. }
  13179. inline Result Client::Put(const std::string &path, const char *body,
  13180. size_t content_length,
  13181. const std::string &content_type,
  13182. UploadProgress progress) {
  13183. return cli_->Put(path, body, content_length, content_type, progress);
  13184. }
  13185. inline Result Client::Put(const std::string &path, const Headers &headers,
  13186. const char *body, size_t content_length,
  13187. const std::string &content_type,
  13188. UploadProgress progress) {
  13189. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13190. }
  13191. inline Result Client::Put(const std::string &path, const std::string &body,
  13192. const std::string &content_type,
  13193. UploadProgress progress) {
  13194. return cli_->Put(path, body, content_type, progress);
  13195. }
  13196. inline Result Client::Put(const std::string &path, const Headers &headers,
  13197. const std::string &body,
  13198. const std::string &content_type,
  13199. UploadProgress progress) {
  13200. return cli_->Put(path, headers, body, content_type, progress);
  13201. }
  13202. inline Result Client::Put(const std::string &path, size_t content_length,
  13203. ContentProvider content_provider,
  13204. const std::string &content_type,
  13205. UploadProgress progress) {
  13206. return cli_->Put(path, content_length, std::move(content_provider),
  13207. content_type, progress);
  13208. }
  13209. inline Result Client::Put(const std::string &path, size_t content_length,
  13210. ContentProvider content_provider,
  13211. const std::string &content_type,
  13212. ContentReceiver content_receiver,
  13213. UploadProgress progress) {
  13214. return cli_->Put(path, content_length, std::move(content_provider),
  13215. content_type, std::move(content_receiver), progress);
  13216. }
  13217. inline Result Client::Put(const std::string &path,
  13218. ContentProviderWithoutLength content_provider,
  13219. const std::string &content_type,
  13220. UploadProgress progress) {
  13221. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13222. }
  13223. inline Result Client::Put(const std::string &path,
  13224. ContentProviderWithoutLength content_provider,
  13225. const std::string &content_type,
  13226. ContentReceiver content_receiver,
  13227. UploadProgress progress) {
  13228. return cli_->Put(path, std::move(content_provider), content_type,
  13229. std::move(content_receiver), progress);
  13230. }
  13231. inline Result Client::Put(const std::string &path, const Headers &headers,
  13232. size_t content_length,
  13233. ContentProvider content_provider,
  13234. const std::string &content_type,
  13235. UploadProgress progress) {
  13236. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13237. content_type, progress);
  13238. }
  13239. inline Result Client::Put(const std::string &path, const Headers &headers,
  13240. size_t content_length,
  13241. ContentProvider content_provider,
  13242. const std::string &content_type,
  13243. ContentReceiver content_receiver,
  13244. UploadProgress progress) {
  13245. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13246. content_type, std::move(content_receiver), progress);
  13247. }
  13248. inline Result Client::Put(const std::string &path, const Headers &headers,
  13249. ContentProviderWithoutLength content_provider,
  13250. const std::string &content_type,
  13251. UploadProgress progress) {
  13252. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13253. progress);
  13254. }
  13255. inline Result Client::Put(const std::string &path, const Headers &headers,
  13256. ContentProviderWithoutLength content_provider,
  13257. const std::string &content_type,
  13258. ContentReceiver content_receiver,
  13259. UploadProgress progress) {
  13260. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13261. std::move(content_receiver), progress);
  13262. }
  13263. inline Result Client::Put(const std::string &path, const Params &params) {
  13264. return cli_->Put(path, params);
  13265. }
  13266. inline Result Client::Put(const std::string &path, const Headers &headers,
  13267. const Params &params) {
  13268. return cli_->Put(path, headers, params);
  13269. }
  13270. inline Result Client::Put(const std::string &path,
  13271. const UploadFormDataItems &items,
  13272. UploadProgress progress) {
  13273. return cli_->Put(path, items, progress);
  13274. }
  13275. inline Result Client::Put(const std::string &path, const Headers &headers,
  13276. const UploadFormDataItems &items,
  13277. UploadProgress progress) {
  13278. return cli_->Put(path, headers, items, progress);
  13279. }
  13280. inline Result Client::Put(const std::string &path, const Headers &headers,
  13281. const UploadFormDataItems &items,
  13282. const std::string &boundary,
  13283. UploadProgress progress) {
  13284. return cli_->Put(path, headers, items, boundary, progress);
  13285. }
  13286. inline Result Client::Put(const std::string &path, const Headers &headers,
  13287. const UploadFormDataItems &items,
  13288. const FormDataProviderItems &provider_items,
  13289. UploadProgress progress) {
  13290. return cli_->Put(path, headers, items, provider_items, progress);
  13291. }
  13292. inline Result Client::Put(const std::string &path, const Headers &headers,
  13293. const std::string &body,
  13294. const std::string &content_type,
  13295. ContentReceiver content_receiver,
  13296. DownloadProgress progress) {
  13297. return cli_->Put(path, headers, body, content_type, content_receiver,
  13298. progress);
  13299. }
  13300. inline Result Client::Patch(const std::string &path) {
  13301. return cli_->Patch(path);
  13302. }
  13303. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13304. return cli_->Patch(path, headers);
  13305. }
  13306. inline Result Client::Patch(const std::string &path, const char *body,
  13307. size_t content_length,
  13308. const std::string &content_type,
  13309. UploadProgress progress) {
  13310. return cli_->Patch(path, body, content_length, content_type, progress);
  13311. }
  13312. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13313. const char *body, size_t content_length,
  13314. const std::string &content_type,
  13315. UploadProgress progress) {
  13316. return cli_->Patch(path, headers, body, content_length, content_type,
  13317. progress);
  13318. }
  13319. inline Result Client::Patch(const std::string &path, const std::string &body,
  13320. const std::string &content_type,
  13321. UploadProgress progress) {
  13322. return cli_->Patch(path, body, content_type, progress);
  13323. }
  13324. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13325. const std::string &body,
  13326. const std::string &content_type,
  13327. UploadProgress progress) {
  13328. return cli_->Patch(path, headers, body, content_type, progress);
  13329. }
  13330. inline Result Client::Patch(const std::string &path, size_t content_length,
  13331. ContentProvider content_provider,
  13332. const std::string &content_type,
  13333. UploadProgress progress) {
  13334. return cli_->Patch(path, content_length, std::move(content_provider),
  13335. content_type, progress);
  13336. }
  13337. inline Result Client::Patch(const std::string &path, size_t content_length,
  13338. ContentProvider content_provider,
  13339. const std::string &content_type,
  13340. ContentReceiver content_receiver,
  13341. UploadProgress progress) {
  13342. return cli_->Patch(path, content_length, std::move(content_provider),
  13343. content_type, std::move(content_receiver), progress);
  13344. }
  13345. inline Result Client::Patch(const std::string &path,
  13346. ContentProviderWithoutLength content_provider,
  13347. const std::string &content_type,
  13348. UploadProgress progress) {
  13349. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13350. }
  13351. inline Result Client::Patch(const std::string &path,
  13352. ContentProviderWithoutLength content_provider,
  13353. const std::string &content_type,
  13354. ContentReceiver content_receiver,
  13355. UploadProgress progress) {
  13356. return cli_->Patch(path, std::move(content_provider), content_type,
  13357. std::move(content_receiver), progress);
  13358. }
  13359. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13360. size_t content_length,
  13361. ContentProvider content_provider,
  13362. const std::string &content_type,
  13363. UploadProgress progress) {
  13364. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13365. content_type, progress);
  13366. }
  13367. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13368. size_t content_length,
  13369. ContentProvider content_provider,
  13370. const std::string &content_type,
  13371. ContentReceiver content_receiver,
  13372. UploadProgress progress) {
  13373. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13374. content_type, std::move(content_receiver), progress);
  13375. }
  13376. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13377. ContentProviderWithoutLength content_provider,
  13378. const std::string &content_type,
  13379. UploadProgress progress) {
  13380. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13381. progress);
  13382. }
  13383. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13384. ContentProviderWithoutLength content_provider,
  13385. const std::string &content_type,
  13386. ContentReceiver content_receiver,
  13387. UploadProgress progress) {
  13388. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13389. std::move(content_receiver), progress);
  13390. }
  13391. inline Result Client::Patch(const std::string &path, const Params &params) {
  13392. return cli_->Patch(path, params);
  13393. }
  13394. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13395. const Params &params) {
  13396. return cli_->Patch(path, headers, params);
  13397. }
  13398. inline Result Client::Patch(const std::string &path,
  13399. const UploadFormDataItems &items,
  13400. UploadProgress progress) {
  13401. return cli_->Patch(path, items, progress);
  13402. }
  13403. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13404. const UploadFormDataItems &items,
  13405. UploadProgress progress) {
  13406. return cli_->Patch(path, headers, items, progress);
  13407. }
  13408. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13409. const UploadFormDataItems &items,
  13410. const std::string &boundary,
  13411. UploadProgress progress) {
  13412. return cli_->Patch(path, headers, items, boundary, progress);
  13413. }
  13414. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13415. const UploadFormDataItems &items,
  13416. const FormDataProviderItems &provider_items,
  13417. UploadProgress progress) {
  13418. return cli_->Patch(path, headers, items, provider_items, progress);
  13419. }
  13420. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13421. const std::string &body,
  13422. const std::string &content_type,
  13423. ContentReceiver content_receiver,
  13424. DownloadProgress progress) {
  13425. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13426. progress);
  13427. }
  13428. inline Result Client::Delete(const std::string &path,
  13429. DownloadProgress progress) {
  13430. return cli_->Delete(path, progress);
  13431. }
  13432. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13433. DownloadProgress progress) {
  13434. return cli_->Delete(path, headers, progress);
  13435. }
  13436. inline Result Client::Delete(const std::string &path, const char *body,
  13437. size_t content_length,
  13438. const std::string &content_type,
  13439. DownloadProgress progress) {
  13440. return cli_->Delete(path, body, content_length, content_type, progress);
  13441. }
  13442. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13443. const char *body, size_t content_length,
  13444. const std::string &content_type,
  13445. DownloadProgress progress) {
  13446. return cli_->Delete(path, headers, body, content_length, content_type,
  13447. progress);
  13448. }
  13449. inline Result Client::Delete(const std::string &path, const std::string &body,
  13450. const std::string &content_type,
  13451. DownloadProgress progress) {
  13452. return cli_->Delete(path, body, content_type, progress);
  13453. }
  13454. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13455. const std::string &body,
  13456. const std::string &content_type,
  13457. DownloadProgress progress) {
  13458. return cli_->Delete(path, headers, body, content_type, progress);
  13459. }
  13460. inline Result Client::Delete(const std::string &path, const Params &params,
  13461. DownloadProgress progress) {
  13462. return cli_->Delete(path, params, progress);
  13463. }
  13464. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13465. const Params &params, DownloadProgress progress) {
  13466. return cli_->Delete(path, headers, params, progress);
  13467. }
  13468. inline Result Client::Options(const std::string &path) {
  13469. return cli_->Options(path);
  13470. }
  13471. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13472. return cli_->Options(path, headers);
  13473. }
  13474. inline ClientImpl::StreamHandle
  13475. Client::open_stream(const std::string &method, const std::string &path,
  13476. const Params &params, const Headers &headers,
  13477. const std::string &body, const std::string &content_type) {
  13478. return cli_->open_stream(method, path, params, headers, body, content_type);
  13479. }
  13480. inline bool Client::send(Request &req, Response &res, Error &error) {
  13481. return cli_->send(req, res, error);
  13482. }
  13483. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13484. inline void Client::stop() { cli_->stop(); }
  13485. inline std::string Client::host() const { return cli_->host(); }
  13486. inline int Client::port() const { return cli_->port(); }
  13487. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13488. inline socket_t Client::socket() const { return cli_->socket(); }
  13489. inline void
  13490. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13491. cli_->set_hostname_addr_map(std::move(addr_map));
  13492. }
  13493. inline void Client::set_default_headers(Headers headers) {
  13494. cli_->set_default_headers(std::move(headers));
  13495. }
  13496. inline void Client::set_header_writer(
  13497. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13498. cli_->set_header_writer(writer);
  13499. }
  13500. inline void Client::set_address_family(int family) {
  13501. cli_->set_address_family(family);
  13502. }
  13503. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13504. inline void Client::set_socket_options(SocketOptions socket_options) {
  13505. cli_->set_socket_options(std::move(socket_options));
  13506. }
  13507. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13508. cli_->set_connection_timeout(sec, usec);
  13509. }
  13510. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13511. cli_->set_read_timeout(sec, usec);
  13512. }
  13513. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13514. cli_->set_write_timeout(sec, usec);
  13515. }
  13516. inline void Client::set_basic_auth(const std::string &username,
  13517. const std::string &password) {
  13518. cli_->set_basic_auth(username, password);
  13519. }
  13520. inline void Client::set_bearer_token_auth(const std::string &token) {
  13521. cli_->set_bearer_token_auth(token);
  13522. }
  13523. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13524. inline void Client::set_follow_location(bool on) {
  13525. cli_->set_follow_location(on);
  13526. }
  13527. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13528. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13529. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13530. inline void Client::set_payload_max_length(size_t length) {
  13531. cli_->set_payload_max_length(length);
  13532. }
  13533. inline void Client::set_interface(const std::string &intf) {
  13534. cli_->set_interface(intf);
  13535. }
  13536. inline void Client::set_proxy(const std::string &host, int port) {
  13537. cli_->set_proxy(host, port);
  13538. }
  13539. inline void Client::set_proxy_basic_auth(const std::string &username,
  13540. const std::string &password) {
  13541. cli_->set_proxy_basic_auth(username, password);
  13542. }
  13543. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13544. cli_->set_proxy_bearer_token_auth(token);
  13545. }
  13546. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13547. cli_->set_no_proxy(patterns);
  13548. }
  13549. inline void Client::set_logger(Logger logger) {
  13550. cli_->set_logger(std::move(logger));
  13551. }
  13552. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13553. cli_->set_error_logger(std::move(error_logger));
  13554. }
  13555. /*
  13556. * Group 6: SSL Server and Client implementation
  13557. */
  13558. #ifdef CPPHTTPLIB_SSL_ENABLED
  13559. // SSL HTTP server implementation
  13560. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13561. const char *client_ca_cert_file_path,
  13562. const char *client_ca_cert_dir_path,
  13563. const char *private_key_password) {
  13564. using namespace tls;
  13565. ctx_ = create_server_context();
  13566. if (!ctx_) { return; }
  13567. // Load server certificate and private key
  13568. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13569. private_key_password)) {
  13570. last_ssl_error_ = static_cast<int>(get_error());
  13571. free_context(ctx_);
  13572. ctx_ = nullptr;
  13573. return;
  13574. }
  13575. // Load client CA certificates for client authentication
  13576. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13577. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13578. client_ca_cert_dir_path)) {
  13579. last_ssl_error_ = static_cast<int>(get_error());
  13580. free_context(ctx_);
  13581. ctx_ = nullptr;
  13582. return;
  13583. }
  13584. // Enable client certificate verification
  13585. set_verify_client(ctx_, true);
  13586. }
  13587. }
  13588. inline SSLServer::SSLServer(const PemMemory &pem) {
  13589. using namespace tls;
  13590. ctx_ = create_server_context();
  13591. if (ctx_) {
  13592. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13593. pem.private_key_password)) {
  13594. last_ssl_error_ = static_cast<int>(get_error());
  13595. free_context(ctx_);
  13596. ctx_ = nullptr;
  13597. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13598. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13599. last_ssl_error_ = static_cast<int>(get_error());
  13600. free_context(ctx_);
  13601. ctx_ = nullptr;
  13602. } else {
  13603. set_verify_client(ctx_, true);
  13604. }
  13605. }
  13606. }
  13607. }
  13608. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13609. using namespace tls;
  13610. ctx_ = create_server_context();
  13611. if (ctx_) {
  13612. if (!setup_callback(ctx_)) {
  13613. free_context(ctx_);
  13614. ctx_ = nullptr;
  13615. }
  13616. }
  13617. }
  13618. inline SSLServer::~SSLServer() {
  13619. if (ctx_) { tls::free_context(ctx_); }
  13620. }
  13621. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13622. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13623. using namespace tls;
  13624. // Create TLS session with mutex protection
  13625. session_t session = nullptr;
  13626. {
  13627. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13628. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13629. }
  13630. if (!session) {
  13631. last_ssl_error_ = static_cast<int>(get_error());
  13632. detail::shutdown_socket(sock);
  13633. detail::close_socket(sock);
  13634. return false;
  13635. }
  13636. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13637. bool handshake_done = false;
  13638. bool ret = false;
  13639. bool websocket_upgraded = false;
  13640. auto cleanup = detail::scope_exit([&] {
  13641. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13642. free_session(session);
  13643. detail::shutdown_socket(sock);
  13644. detail::close_socket(sock);
  13645. });
  13646. // Perform TLS accept handshake with timeout
  13647. TlsError tls_err;
  13648. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13649. &tls_err)) {
  13650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13651. // Map TlsError to legacy ssl_error for backward compatibility
  13652. if (tls_err.code == ErrorCode::WantRead) {
  13653. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13654. } else if (tls_err.code == ErrorCode::WantWrite) {
  13655. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13656. } else {
  13657. last_ssl_error_ = SSL_ERROR_SSL;
  13658. }
  13659. #else
  13660. last_ssl_error_ = static_cast<int>(get_error());
  13661. #endif
  13662. return false;
  13663. }
  13664. handshake_done = true;
  13665. std::string remote_addr;
  13666. int remote_port = 0;
  13667. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13668. std::string local_addr;
  13669. int local_port = 0;
  13670. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13671. ret = detail::process_server_socket_ssl(
  13672. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13673. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13674. write_timeout_usec_,
  13675. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13676. return process_request(
  13677. strm, remote_addr, remote_port, local_addr, local_port,
  13678. close_connection, connection_closed,
  13679. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13680. });
  13681. return ret;
  13682. }
  13683. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13684. const char *key_pem,
  13685. const char *client_ca_pem,
  13686. const char *password) {
  13687. if (!ctx_) { return false; }
  13688. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13689. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13690. return false;
  13691. }
  13692. if (client_ca_pem) {
  13693. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13694. }
  13695. return true;
  13696. }
  13697. // SSL HTTP client implementation
  13698. inline SSLClient::~SSLClient() {
  13699. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13700. // base function rather than the derived function once we get to the
  13701. // base class destructor, and won't free the SSL (causing a leak).
  13702. // This must happen before the context is freed below: some backends
  13703. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  13704. // context, so freeing the context first leaves close_notify reading
  13705. // freed memory.
  13706. shutdown_ssl_impl(socket_, true);
  13707. if (ctx_) {
  13708. tls::free_context(ctx_);
  13709. ctx_ = nullptr;
  13710. }
  13711. }
  13712. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13713. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13714. shutdown_ssl_impl(socket, shutdown_gracefully);
  13715. }
  13716. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13717. bool shutdown_gracefully) {
  13718. if (socket.sock == INVALID_SOCKET) {
  13719. assert(socket.ssl == nullptr);
  13720. return;
  13721. }
  13722. if (socket.ssl) {
  13723. tls::shutdown(socket.ssl, shutdown_gracefully);
  13724. {
  13725. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13726. tls::free_session(socket.ssl);
  13727. }
  13728. socket.ssl = nullptr;
  13729. }
  13730. assert(socket.ssl == nullptr);
  13731. }
  13732. inline bool SSLClient::process_socket(
  13733. const Socket &socket,
  13734. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13735. std::function<bool(Stream &strm)> callback) {
  13736. assert(socket.ssl);
  13737. return detail::process_client_socket_ssl(
  13738. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13739. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13740. std::move(callback));
  13741. }
  13742. inline bool SSLClient::is_ssl() const { return true; }
  13743. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13744. if (!is_valid()) {
  13745. error = Error::SSLConnection;
  13746. return false;
  13747. }
  13748. return ClientImpl::create_and_connect_socket(socket, error);
  13749. }
  13750. inline bool SSLClient::setup_proxy_connection(
  13751. Socket &socket,
  13752. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13753. Response &res, bool &success, Error &error) {
  13754. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13755. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13756. return false;
  13757. }
  13758. if (!initialize_ssl(socket, error)) {
  13759. success = false;
  13760. return false;
  13761. }
  13762. return true;
  13763. }
  13764. // Assumes that socket_mutex_ is locked and that there are no requests in
  13765. // flight
  13766. inline bool SSLClient::connect_with_proxy(
  13767. Socket &socket,
  13768. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13769. Response &res, bool &success, Error &error) {
  13770. success = true;
  13771. Response proxy_res;
  13772. if (!detail::process_client_socket(
  13773. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13774. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13775. start_time, [&](Stream &strm) {
  13776. Request req2;
  13777. req2.method = "CONNECT";
  13778. req2.path =
  13779. detail::make_host_and_port_string_always_port(host_, port_);
  13780. if (max_timeout_msec_ > 0) {
  13781. req2.start_time_ = std::chrono::steady_clock::now();
  13782. }
  13783. return process_request(strm, req2, proxy_res, false, error);
  13784. })) {
  13785. // Thread-safe to close everything because we are assuming there are no
  13786. // requests in flight
  13787. shutdown_ssl(socket, true);
  13788. shutdown_socket(socket);
  13789. close_socket(socket);
  13790. success = false;
  13791. return false;
  13792. }
  13793. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13794. if (!proxy_digest_auth_username_.empty() &&
  13795. !proxy_digest_auth_password_.empty()) {
  13796. std::map<std::string, std::string> auth;
  13797. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13798. // Close the current socket and create a new one for the authenticated
  13799. // request
  13800. shutdown_ssl(socket, true);
  13801. shutdown_socket(socket);
  13802. close_socket(socket);
  13803. // Create a new socket for the authenticated CONNECT request
  13804. if (!ensure_socket_connection(socket, error)) {
  13805. success = false;
  13806. output_error_log(error, nullptr);
  13807. return false;
  13808. }
  13809. proxy_res = Response();
  13810. if (!detail::process_client_socket(
  13811. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13812. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13813. start_time, [&](Stream &strm) {
  13814. Request req3;
  13815. req3.method = "CONNECT";
  13816. req3.path = detail::make_host_and_port_string_always_port(
  13817. host_, port_);
  13818. req3.headers.insert(detail::make_digest_authentication_header(
  13819. req3, auth, 1, detail::random_string(10),
  13820. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13821. true));
  13822. if (max_timeout_msec_ > 0) {
  13823. req3.start_time_ = std::chrono::steady_clock::now();
  13824. }
  13825. return process_request(strm, req3, proxy_res, false, error);
  13826. })) {
  13827. // Thread-safe to close everything because we are assuming there are
  13828. // no requests in flight
  13829. shutdown_ssl(socket, true);
  13830. shutdown_socket(socket);
  13831. close_socket(socket);
  13832. success = false;
  13833. return false;
  13834. }
  13835. }
  13836. }
  13837. }
  13838. // If status code is not 200, proxy request is failed.
  13839. // Set error to ProxyConnection and return proxy response
  13840. // as the response of the request
  13841. if (proxy_res.status != StatusCode::OK_200) {
  13842. error = Error::ProxyConnection;
  13843. output_error_log(error, nullptr);
  13844. res = std::move(proxy_res);
  13845. // Thread-safe to close everything because we are assuming there are
  13846. // no requests in flight
  13847. shutdown_ssl(socket, true);
  13848. shutdown_socket(socket);
  13849. close_socket(socket);
  13850. return false;
  13851. }
  13852. return true;
  13853. }
  13854. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13855. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13856. if (is_proxy_enabled_for_host(host_)) { return true; }
  13857. if (!initialize_ssl(socket, error)) {
  13858. shutdown_socket(socket);
  13859. close_socket(socket);
  13860. return false;
  13861. }
  13862. return true;
  13863. }
  13864. // SSL HTTP client implementation
  13865. inline SSLClient::SSLClient(const std::string &host)
  13866. : SSLClient(host, 443, std::string(), std::string()) {}
  13867. inline SSLClient::SSLClient(const std::string &host, int port)
  13868. : SSLClient(host, port, std::string(), std::string()) {}
  13869. inline void SSLClient::init_ctx() {
  13870. ctx_ = tls::create_client_context();
  13871. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13872. }
  13873. inline void SSLClient::reset_ctx_on_error() {
  13874. last_backend_error_ = tls::get_error();
  13875. tls::free_context(ctx_);
  13876. ctx_ = nullptr;
  13877. }
  13878. inline SSLClient::SSLClient(const std::string &host, int port,
  13879. const std::string &client_cert_path,
  13880. const std::string &client_key_path,
  13881. const std::string &private_key_password)
  13882. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13883. init_ctx();
  13884. if (!ctx_) { return; }
  13885. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13886. const char *password =
  13887. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13888. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13889. client_key_path.c_str(), password)) {
  13890. reset_ctx_on_error();
  13891. }
  13892. }
  13893. }
  13894. inline SSLClient::SSLClient(const std::string &host, int port,
  13895. const PemMemory &pem)
  13896. : ClientImpl(host, port) {
  13897. init_ctx();
  13898. if (!ctx_) { return; }
  13899. if (pem.cert_pem && pem.key_pem) {
  13900. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13901. pem.private_key_password)) {
  13902. reset_ctx_on_error();
  13903. }
  13904. }
  13905. }
  13906. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13907. if (ca_cert_store && ctx_) {
  13908. // set_ca_store takes ownership of ca_cert_store
  13909. tls::set_ca_store(ctx_, ca_cert_store);
  13910. ca_cert_store_set_ = true;
  13911. } else if (ca_cert_store) {
  13912. tls::free_ca_store(ca_cert_store);
  13913. }
  13914. }
  13915. inline void
  13916. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13917. if (!ctx_) { return; }
  13918. tls::set_verify_callback(ctx_, verifier);
  13919. }
  13920. inline void SSLClient::set_session_verifier(
  13921. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13922. session_verifier_ = std::move(verifier);
  13923. }
  13924. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13925. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13926. enable_windows_cert_verification_ = enabled;
  13927. }
  13928. #endif
  13929. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13930. std::size_t size) {
  13931. if (ctx_ && ca_cert && size > 0) {
  13932. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13933. tls::load_ca_pem(ctx_, ca_cert, size);
  13934. }
  13935. }
  13936. inline bool SSLClient::load_certs() {
  13937. auto ret = true;
  13938. std::call_once(initialize_cert_, [&]() {
  13939. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13940. ret = detail::load_client_ca_config(
  13941. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13942. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13943. last_backend_error_);
  13944. });
  13945. return ret;
  13946. }
  13947. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13948. using namespace tls;
  13949. // Load CA certificates if server verification is enabled
  13950. if (server_certificate_verification_) {
  13951. if (!load_certs()) {
  13952. error = Error::SSLLoadingCerts;
  13953. output_error_log(error, nullptr);
  13954. return false;
  13955. }
  13956. }
  13957. bool is_ip = detail::is_ip_address(host_);
  13958. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13959. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13960. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13961. // Chain verification happens during the handshake even for IP hosts; the
  13962. // certificate identity is verified post-handshake via verify_hostname().
  13963. set_verify_client(ctx_, server_certificate_verification_);
  13964. #endif
  13965. // Create TLS session
  13966. session_t session = nullptr;
  13967. {
  13968. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13969. session = create_session(ctx_, socket.sock);
  13970. }
  13971. if (!session) {
  13972. error = Error::SSLConnection;
  13973. last_backend_error_ = get_error();
  13974. return false;
  13975. }
  13976. // Use scope_exit to ensure session is freed on error paths
  13977. bool success = false;
  13978. auto session_guard = detail::scope_exit([&] {
  13979. if (!success) { free_session(session); }
  13980. });
  13981. // Set SNI extension (skip for IP addresses per RFC 6066).
  13982. // On MbedTLS, set_sni also enables hostname verification internally.
  13983. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13984. if (!is_ip) {
  13985. if (!set_sni(session, host_.c_str())) {
  13986. error = Error::SSLConnection;
  13987. last_backend_error_ = get_error();
  13988. return false;
  13989. }
  13990. }
  13991. // Perform non-blocking TLS handshake with timeout
  13992. TlsError tls_err;
  13993. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13994. connection_timeout_usec_, &tls_err)) {
  13995. last_ssl_error_ = static_cast<int>(tls_err.code);
  13996. last_backend_error_ = tls_err.backend_code;
  13997. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13998. error = Error::SSLServerVerification;
  13999. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  14000. error = Error::SSLServerHostnameVerification;
  14001. } else {
  14002. error = Error::SSLConnection;
  14003. }
  14004. output_error_log(error, nullptr);
  14005. return false;
  14006. }
  14007. // Post-handshake session verifier callback
  14008. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  14009. if (session_verifier_) { verification_status = session_verifier_(session); }
  14010. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  14011. last_backend_error_ = get_error();
  14012. error = Error::SSLServerVerification;
  14013. output_error_log(error, nullptr);
  14014. return false;
  14015. }
  14016. // Default server certificate verification
  14017. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  14018. server_certificate_verification_) {
  14019. verify_result_ = tls::get_verify_result(session);
  14020. if (verify_result_ != 0) {
  14021. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  14022. error = Error::SSLServerVerification;
  14023. output_error_log(error, nullptr);
  14024. return false;
  14025. }
  14026. auto server_cert = get_peer_cert(session);
  14027. if (!server_cert) {
  14028. last_backend_error_ = get_error();
  14029. error = Error::SSLServerVerification;
  14030. output_error_log(error, nullptr);
  14031. return false;
  14032. }
  14033. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  14034. // Hostname verification (post-handshake for all cases).
  14035. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  14036. // On MbedTLS, set_sni already enabled hostname verification during
  14037. // handshake for non-IP hosts, but this check is still needed for IP
  14038. // addresses where SNI is not set.
  14039. if (server_hostname_verification_) {
  14040. if (!verify_hostname(server_cert, host_.c_str())) {
  14041. last_backend_error_ = hostname_mismatch_code();
  14042. error = Error::SSLServerHostnameVerification;
  14043. output_error_log(error, nullptr);
  14044. return false;
  14045. }
  14046. }
  14047. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14048. // Additional Windows Schannel verification.
  14049. // This provides real-time certificate validation with Windows Update
  14050. // integration, working with both OpenSSL and MbedTLS backends.
  14051. // Skip when a custom CA cert is specified, as the Windows certificate
  14052. // store would not know about user-provided CA certificates. Also skip
  14053. // when system CA trust is explicitly disabled.
  14054. if (enable_windows_cert_verification_ &&
  14055. system_ca_mode_ != SystemCAMode::Disabled &&
  14056. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  14057. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14058. std::vector<unsigned char> der;
  14059. if (get_cert_der(server_cert, der)) {
  14060. uint64_t wincrypt_error = 0;
  14061. if (!detail::verify_cert_with_windows_schannel(
  14062. der, host_, server_hostname_verification_, wincrypt_error)) {
  14063. last_backend_error_ = wincrypt_error;
  14064. error = Error::SSLServerVerification;
  14065. output_error_log(error, nullptr);
  14066. return false;
  14067. }
  14068. }
  14069. }
  14070. #endif
  14071. }
  14072. success = true;
  14073. socket.ssl = session;
  14074. return true;
  14075. }
  14076. inline void Client::set_digest_auth(const std::string &username,
  14077. const std::string &password) {
  14078. cli_->set_digest_auth(username, password);
  14079. }
  14080. inline void Client::set_proxy_digest_auth(const std::string &username,
  14081. const std::string &password) {
  14082. cli_->set_proxy_digest_auth(username, password);
  14083. }
  14084. inline void Client::enable_server_certificate_verification(bool enabled) {
  14085. cli_->enable_server_certificate_verification(enabled);
  14086. }
  14087. inline void Client::enable_server_hostname_verification(bool enabled) {
  14088. cli_->enable_server_hostname_verification(enabled);
  14089. }
  14090. inline void Client::enable_system_ca(bool enabled) {
  14091. cli_->enable_system_ca(enabled);
  14092. }
  14093. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14094. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14095. if (is_ssl_) {
  14096. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14097. enabled);
  14098. }
  14099. }
  14100. #endif
  14101. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14102. const std::string &ca_cert_dir_path) {
  14103. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14104. }
  14105. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14106. if (is_ssl_) {
  14107. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14108. } else if (ca_cert_store) {
  14109. tls::free_ca_store(ca_cert_store);
  14110. }
  14111. }
  14112. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14113. if (is_ssl_) {
  14114. // Use the PEM-based path so the CA data is retained for redirect transfer
  14115. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14116. }
  14117. }
  14118. inline void
  14119. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14120. if (is_ssl_) {
  14121. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14122. std::move(verifier));
  14123. }
  14124. }
  14125. inline void Client::set_session_verifier(
  14126. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14127. if (is_ssl_) {
  14128. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14129. }
  14130. }
  14131. inline tls::ctx_t Client::tls_context() const {
  14132. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14133. return nullptr;
  14134. }
  14135. #endif // CPPHTTPLIB_SSL_ENABLED
  14136. /*
  14137. * Group 7: TLS abstraction layer - Common API
  14138. */
  14139. #ifdef CPPHTTPLIB_SSL_ENABLED
  14140. namespace tls {
  14141. // Helper for PeerCert construction
  14142. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14143. return PeerCert(get_peer_cert(session));
  14144. }
  14145. namespace impl {
  14146. inline VerifyCallback &get_verify_callback() {
  14147. static thread_local VerifyCallback callback;
  14148. return callback;
  14149. }
  14150. inline VerifyCallback &get_mbedtls_verify_callback() {
  14151. static thread_local VerifyCallback callback;
  14152. return callback;
  14153. }
  14154. // Check if a string is an IPv4 address
  14155. inline bool is_ipv4_address(const std::string &str) {
  14156. int dots = 0;
  14157. for (char c : str) {
  14158. if (c == '.') {
  14159. dots++;
  14160. } else if (!detail::is_ascii_digit(c)) {
  14161. return false;
  14162. }
  14163. }
  14164. return dots == 3;
  14165. }
  14166. // Parse IPv4 address string to bytes
  14167. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14168. const char *p = str.c_str();
  14169. for (int i = 0; i < 4; i++) {
  14170. if (i > 0) {
  14171. if (*p != '.') { return false; }
  14172. p++;
  14173. }
  14174. int val = 0;
  14175. int digits = 0;
  14176. while (detail::is_ascii_digit(*p)) {
  14177. val = val * 10 + (*p - '0');
  14178. if (val > 255) { return false; }
  14179. p++;
  14180. digits++;
  14181. }
  14182. if (digits == 0) { return false; }
  14183. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14184. if (digits > 1 && *(p - digits) == '0') { return false; }
  14185. out[i] = static_cast<unsigned char>(val);
  14186. }
  14187. return *p == '\0';
  14188. }
  14189. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14190. // `out` must have room for at least 16 bytes. Returns the address length
  14191. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14192. // literal. Used to match a host against iPAddress SANs the same way the
  14193. // OpenSSL backend does via X509_check_ip.
  14194. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14195. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14196. struct in6_addr addr6 = {};
  14197. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14198. memcpy(out, &addr6, 16);
  14199. return 16;
  14200. }
  14201. return 0;
  14202. }
  14203. #ifdef _WIN32
  14204. // Enumerate Windows system certificates and call callback with DER data
  14205. template <typename Callback>
  14206. inline bool enumerate_windows_system_certs(Callback cb) {
  14207. bool loaded = false;
  14208. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14209. for (auto store_name : store_names) {
  14210. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14211. if (hStore) {
  14212. PCCERT_CONTEXT pContext = nullptr;
  14213. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14214. nullptr) {
  14215. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14216. loaded = true;
  14217. }
  14218. }
  14219. CertCloseStore(hStore, 0);
  14220. }
  14221. }
  14222. return loaded;
  14223. }
  14224. #endif
  14225. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14226. // Enumerate macOS Keychain certificates and call callback with DER data
  14227. template <typename Callback>
  14228. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14229. bool loaded = false;
  14230. const SecTrustSettingsDomain domains[] = {
  14231. kSecTrustSettingsDomainSystem,
  14232. kSecTrustSettingsDomainAdmin,
  14233. kSecTrustSettingsDomainUser,
  14234. };
  14235. for (auto domain : domains) {
  14236. CFArrayRef certs = nullptr;
  14237. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14238. if (status != errSecSuccess || !certs) {
  14239. if (certs) CFRelease(certs);
  14240. continue;
  14241. }
  14242. CFIndex count = CFArrayGetCount(certs);
  14243. for (CFIndex i = 0; i < count; i++) {
  14244. SecCertificateRef cert =
  14245. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14246. CFDataRef data = SecCertificateCopyData(cert);
  14247. if (data) {
  14248. if (cb(CFDataGetBytePtr(data),
  14249. static_cast<size_t>(CFDataGetLength(data)))) {
  14250. loaded = true;
  14251. }
  14252. CFRelease(data);
  14253. }
  14254. }
  14255. CFRelease(certs);
  14256. }
  14257. return loaded;
  14258. }
  14259. #endif
  14260. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14261. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14262. // Common CA certificate file paths on Linux/Unix
  14263. inline const char **system_ca_paths() {
  14264. static const char *paths[] = {
  14265. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14266. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14267. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14268. "/etc/pki/tls/cacert.pem", // OpenELEC
  14269. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14270. nullptr};
  14271. return paths;
  14272. }
  14273. // Common CA certificate directory paths on Linux/Unix
  14274. inline const char **system_ca_dirs() {
  14275. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14276. "/etc/pki/tls/certs", // RHEL/CentOS
  14277. "/usr/share/ca-certificates", // Other
  14278. nullptr};
  14279. return dirs;
  14280. }
  14281. #endif
  14282. } // namespace impl
  14283. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14284. const char *ca_dir) {
  14285. if (!ctx) { return false; }
  14286. bool success = true;
  14287. if (ca_file && *ca_file) {
  14288. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14289. }
  14290. if (ca_dir && *ca_dir) {
  14291. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14292. }
  14293. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14294. // Set CA list for client certificate request (CertificateRequest message)
  14295. if (ca_file && *ca_file) {
  14296. auto list = SSL_load_client_CA_file(ca_file);
  14297. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14298. }
  14299. #endif
  14300. return success;
  14301. }
  14302. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14303. const char *password) {
  14304. return set_client_cert_pem(ctx, cert, key, password);
  14305. }
  14306. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14307. const char *key_path, const char *password) {
  14308. return set_client_cert_file(ctx, cert_path, key_path, password);
  14309. }
  14310. // PeerCert implementation
  14311. inline PeerCert::PeerCert() = default;
  14312. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14313. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14314. other.cert_ = nullptr;
  14315. }
  14316. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14317. if (this != &other) {
  14318. if (cert_) { free_cert(cert_); }
  14319. cert_ = other.cert_;
  14320. other.cert_ = nullptr;
  14321. }
  14322. return *this;
  14323. }
  14324. inline PeerCert::~PeerCert() {
  14325. if (cert_) { free_cert(cert_); }
  14326. }
  14327. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14328. inline std::string PeerCert::subject_cn() const {
  14329. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14330. }
  14331. inline std::string PeerCert::issuer_name() const {
  14332. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14333. }
  14334. inline bool PeerCert::check_hostname(const char *hostname) const {
  14335. return cert_ ? verify_hostname(cert_, hostname) : false;
  14336. }
  14337. inline std::vector<SanEntry> PeerCert::sans() const {
  14338. std::vector<SanEntry> result;
  14339. if (cert_) { get_cert_sans(cert_, result); }
  14340. return result;
  14341. }
  14342. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14343. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14344. }
  14345. inline std::string PeerCert::serial() const {
  14346. return cert_ ? get_cert_serial(cert_) : std::string();
  14347. }
  14348. // VerifyContext method implementations
  14349. inline std::string VerifyContext::subject_cn() const {
  14350. return cert ? get_cert_subject_cn(cert) : std::string();
  14351. }
  14352. inline std::string VerifyContext::issuer_name() const {
  14353. return cert ? get_cert_issuer_name(cert) : std::string();
  14354. }
  14355. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14356. return cert ? verify_hostname(cert, hostname) : false;
  14357. }
  14358. inline std::vector<SanEntry> VerifyContext::sans() const {
  14359. std::vector<SanEntry> result;
  14360. if (cert) { get_cert_sans(cert, result); }
  14361. return result;
  14362. }
  14363. inline bool VerifyContext::validity(time_t &not_before,
  14364. time_t &not_after) const {
  14365. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14366. }
  14367. inline std::string VerifyContext::serial() const {
  14368. return cert ? get_cert_serial(cert) : std::string();
  14369. }
  14370. // TlsError static method implementation
  14371. inline std::string TlsError::verify_error_to_string(long error_code) {
  14372. return verify_error_string(error_code);
  14373. }
  14374. } // namespace tls
  14375. // Request::peer_cert() implementation
  14376. inline tls::PeerCert Request::peer_cert() const {
  14377. return tls::get_peer_cert_from_session(ssl);
  14378. }
  14379. // Request::sni() implementation
  14380. inline std::string Request::sni() const {
  14381. if (!ssl) { return std::string(); }
  14382. const char *s = tls::get_sni(ssl);
  14383. return s ? std::string(s) : std::string();
  14384. }
  14385. #endif // CPPHTTPLIB_SSL_ENABLED
  14386. /*
  14387. * Group 8: TLS abstraction layer - OpenSSL backend
  14388. */
  14389. /*
  14390. * OpenSSL Backend Implementation
  14391. */
  14392. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14393. namespace tls {
  14394. namespace impl {
  14395. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14396. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14397. switch (ssl_error) {
  14398. case SSL_ERROR_NONE: return ErrorCode::Success;
  14399. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14400. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14401. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14402. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14403. case SSL_ERROR_SSL:
  14404. default: return ErrorCode::Fatal;
  14405. }
  14406. }
  14407. // Helper: Create client CA list from PEM string
  14408. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14409. // Caller takes ownership of returned list
  14410. inline STACK_OF(X509_NAME) *
  14411. create_client_ca_list_from_pem(const char *ca_pem) {
  14412. if (!ca_pem) { return nullptr; }
  14413. auto ca_list = sk_X509_NAME_new_null();
  14414. if (!ca_list) { return nullptr; }
  14415. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14416. if (!bio) {
  14417. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14418. return nullptr;
  14419. }
  14420. X509 *cert = nullptr;
  14421. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14422. nullptr) {
  14423. const X509_NAME *name = X509_get_subject_name(cert);
  14424. if (name) {
  14425. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14426. }
  14427. X509_free(cert);
  14428. }
  14429. BIO_free(bio);
  14430. return ca_list;
  14431. }
  14432. // OpenSSL verify callback wrapper
  14433. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14434. auto &callback = get_verify_callback();
  14435. if (!callback) { return preverify_ok; }
  14436. // Get SSL object from X509_STORE_CTX
  14437. auto ssl = static_cast<SSL *>(
  14438. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14439. if (!ssl) { return preverify_ok; }
  14440. // Get current certificate and depth
  14441. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14442. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14443. int error = X509_STORE_CTX_get_error(ctx);
  14444. // Build context
  14445. VerifyContext verify_ctx;
  14446. verify_ctx.session = static_cast<session_t>(ssl);
  14447. verify_ctx.cert = static_cast<cert_t>(cert);
  14448. verify_ctx.depth = depth;
  14449. verify_ctx.preverify_ok = (preverify_ok != 0);
  14450. verify_ctx.error_code = error;
  14451. verify_ctx.error_string =
  14452. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14453. return callback(verify_ctx) ? 1 : 0;
  14454. }
  14455. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14456. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14457. // that must be released with release_store_objects
  14458. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14459. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14460. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14461. #endif
  14462. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14463. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14464. return X509_STORE_get1_objects(store);
  14465. #else
  14466. return X509_STORE_get0_objects(store);
  14467. #endif
  14468. }
  14469. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14470. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14471. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14472. #else
  14473. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14474. #endif
  14475. }
  14476. } // namespace impl
  14477. inline ctx_t create_client_context() {
  14478. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14479. if (ctx) {
  14480. // Disable auto-retry to properly handle non-blocking I/O
  14481. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14482. // Set minimum TLS version
  14483. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14484. }
  14485. return static_cast<ctx_t>(ctx);
  14486. }
  14487. inline void free_context(ctx_t ctx) {
  14488. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14489. }
  14490. inline bool set_min_version(ctx_t ctx, Version version) {
  14491. if (!ctx) return false;
  14492. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14493. static_cast<int>(version)) == 1;
  14494. }
  14495. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14496. if (!ctx || !pem || len == 0) return false;
  14497. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14498. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14499. if (!store) return false;
  14500. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14501. if (!bio) return false;
  14502. bool ok = true;
  14503. X509 *cert = nullptr;
  14504. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14505. nullptr) {
  14506. if (X509_STORE_add_cert(store, cert) != 1) {
  14507. // Ignore duplicate errors
  14508. auto err = ERR_peek_last_error();
  14509. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14510. ok = false;
  14511. }
  14512. }
  14513. X509_free(cert);
  14514. if (!ok) break;
  14515. }
  14516. BIO_free(bio);
  14517. // Clear any "no more certificates" errors
  14518. ERR_clear_error();
  14519. return ok;
  14520. }
  14521. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14522. if (!ctx || !file_path) return false;
  14523. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14524. nullptr) == 1;
  14525. }
  14526. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14527. if (!ctx || !dir_path) return false;
  14528. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14529. dir_path) == 1;
  14530. }
  14531. inline bool load_system_certs(ctx_t ctx) {
  14532. if (!ctx) return false;
  14533. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14534. #ifdef _WIN32
  14535. // Windows: Load from system certificate store (ROOT and CA)
  14536. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14537. if (!store) return false;
  14538. bool loaded_any = false;
  14539. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14540. for (auto store_name : store_names) {
  14541. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14542. if (!hStore) continue;
  14543. PCCERT_CONTEXT pContext = nullptr;
  14544. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14545. nullptr) {
  14546. const unsigned char *data = pContext->pbCertEncoded;
  14547. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14548. if (x509) {
  14549. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14550. X509_free(x509);
  14551. }
  14552. }
  14553. CertCloseStore(hStore, 0);
  14554. }
  14555. return loaded_any;
  14556. #elif defined(__APPLE__)
  14557. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14558. // macOS: Load from Keychain
  14559. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14560. if (!store) return false;
  14561. bool loaded_any = false;
  14562. const SecTrustSettingsDomain domains[] = {
  14563. kSecTrustSettingsDomainSystem,
  14564. kSecTrustSettingsDomainAdmin,
  14565. kSecTrustSettingsDomainUser,
  14566. };
  14567. for (auto domain : domains) {
  14568. CFArrayRef certs = nullptr;
  14569. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14570. !certs) {
  14571. if (certs) CFRelease(certs);
  14572. continue;
  14573. }
  14574. auto count = CFArrayGetCount(certs);
  14575. for (CFIndex i = 0; i < count; i++) {
  14576. auto cert = reinterpret_cast<SecCertificateRef>(
  14577. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14578. CFDataRef der = SecCertificateCopyData(cert);
  14579. if (der) {
  14580. const unsigned char *data = CFDataGetBytePtr(der);
  14581. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14582. if (x509) {
  14583. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14584. X509_free(x509);
  14585. }
  14586. CFRelease(der);
  14587. }
  14588. }
  14589. CFRelease(certs);
  14590. }
  14591. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14592. #else
  14593. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14594. #endif
  14595. #else
  14596. // Other Unix: use default verify paths
  14597. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14598. #endif
  14599. }
  14600. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14601. const char *password) {
  14602. if (!ctx || !cert || !key) return false;
  14603. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14604. // Load certificate
  14605. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14606. if (!cert_bio) return false;
  14607. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14608. BIO_free(cert_bio);
  14609. if (!x509) return false;
  14610. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14611. X509_free(x509);
  14612. if (!cert_ok) return false;
  14613. // Load private key
  14614. auto key_bio = BIO_new_mem_buf(key, -1);
  14615. if (!key_bio) return false;
  14616. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14617. password ? const_cast<char *>(password)
  14618. : nullptr);
  14619. BIO_free(key_bio);
  14620. if (!pkey) return false;
  14621. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14622. EVP_PKEY_free(pkey);
  14623. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14624. }
  14625. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14626. const char *key_path, const char *password) {
  14627. if (!ctx || !cert_path || !key_path) return false;
  14628. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14629. if (password && password[0] != '\0') {
  14630. SSL_CTX_set_default_passwd_cb_userdata(
  14631. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14632. }
  14633. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14634. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14635. }
  14636. inline ctx_t create_server_context() {
  14637. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14638. if (ctx) {
  14639. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14640. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14641. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14642. }
  14643. return static_cast<ctx_t>(ctx);
  14644. }
  14645. inline void set_verify_client(ctx_t ctx, bool require) {
  14646. if (!ctx) return;
  14647. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14648. require
  14649. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14650. : SSL_VERIFY_NONE,
  14651. nullptr);
  14652. }
  14653. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14654. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14655. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14656. SSL *ssl = SSL_new(ssl_ctx);
  14657. if (!ssl) return nullptr;
  14658. // Disable auto-retry for proper non-blocking I/O handling
  14659. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14660. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14661. if (!bio) {
  14662. SSL_free(ssl);
  14663. return nullptr;
  14664. }
  14665. SSL_set_bio(ssl, bio, bio);
  14666. return static_cast<session_t>(ssl);
  14667. }
  14668. inline void free_session(session_t session) {
  14669. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14670. }
  14671. inline bool set_sni(session_t session, const char *hostname) {
  14672. if (!session || !hostname) return false;
  14673. auto ssl = static_cast<SSL *>(session);
  14674. // Set SNI (Server Name Indication) only - does not enable verification
  14675. #if defined(OPENSSL_IS_BORINGSSL)
  14676. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14677. #else
  14678. // Direct call instead of macro to suppress -Wold-style-cast warning
  14679. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14680. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14681. #endif
  14682. }
  14683. inline bool set_hostname(session_t session, const char *hostname) {
  14684. if (!session || !hostname) return false;
  14685. auto ssl = static_cast<SSL *>(session);
  14686. // Enable hostname verification
  14687. auto param = SSL_get0_param(ssl);
  14688. if (!param) return false;
  14689. if (detail::is_ip_address(hostname)) {
  14690. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14691. // certificate's IP SANs instead of its DNS names
  14692. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14693. } else {
  14694. // Set SNI (Server Name Indication)
  14695. if (!set_sni(session, hostname)) { return false; }
  14696. X509_VERIFY_PARAM_set_hostflags(param,
  14697. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14698. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14699. }
  14700. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14701. return true;
  14702. }
  14703. inline TlsError connect(session_t session) {
  14704. if (!session) { return TlsError(); }
  14705. auto ssl = static_cast<SSL *>(session);
  14706. auto ret = SSL_connect(ssl);
  14707. TlsError err;
  14708. if (ret == 1) {
  14709. err.code = ErrorCode::Success;
  14710. } else {
  14711. auto ssl_err = SSL_get_error(ssl, ret);
  14712. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14713. err.backend_code = ERR_get_error();
  14714. }
  14715. return err;
  14716. }
  14717. inline TlsError accept(session_t session) {
  14718. if (!session) { return TlsError(); }
  14719. auto ssl = static_cast<SSL *>(session);
  14720. auto ret = SSL_accept(ssl);
  14721. TlsError err;
  14722. if (ret == 1) {
  14723. err.code = ErrorCode::Success;
  14724. } else {
  14725. auto ssl_err = SSL_get_error(ssl, ret);
  14726. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14727. err.backend_code = ERR_get_error();
  14728. }
  14729. return err;
  14730. }
  14731. inline bool connect_nonblocking(session_t session, socket_t sock,
  14732. time_t timeout_sec, time_t timeout_usec,
  14733. TlsError *err) {
  14734. if (!session) {
  14735. if (err) { err->code = ErrorCode::Fatal; }
  14736. return false;
  14737. }
  14738. auto ssl = static_cast<SSL *>(session);
  14739. auto bio = SSL_get_rbio(ssl);
  14740. // Set non-blocking mode for handshake
  14741. detail::set_nonblocking(sock, true);
  14742. if (bio) { BIO_set_nbio(bio, 1); }
  14743. auto cleanup = detail::scope_exit([&]() {
  14744. // Restore blocking mode after handshake
  14745. if (bio) { BIO_set_nbio(bio, 0); }
  14746. detail::set_nonblocking(sock, false);
  14747. });
  14748. auto res = 0;
  14749. while ((res = SSL_connect(ssl)) != 1) {
  14750. auto ssl_err = SSL_get_error(ssl, res);
  14751. switch (ssl_err) {
  14752. case SSL_ERROR_WANT_READ:
  14753. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14754. continue;
  14755. }
  14756. break;
  14757. case SSL_ERROR_WANT_WRITE:
  14758. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14759. continue;
  14760. }
  14761. break;
  14762. default: break;
  14763. }
  14764. if (err) {
  14765. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14766. err->backend_code = ERR_get_error();
  14767. }
  14768. return false;
  14769. }
  14770. if (err) { err->code = ErrorCode::Success; }
  14771. return true;
  14772. }
  14773. inline bool accept_nonblocking(session_t session, socket_t sock,
  14774. time_t timeout_sec, time_t timeout_usec,
  14775. TlsError *err) {
  14776. if (!session) {
  14777. if (err) { err->code = ErrorCode::Fatal; }
  14778. return false;
  14779. }
  14780. auto ssl = static_cast<SSL *>(session);
  14781. auto bio = SSL_get_rbio(ssl);
  14782. // Set non-blocking mode for handshake
  14783. detail::set_nonblocking(sock, true);
  14784. if (bio) { BIO_set_nbio(bio, 1); }
  14785. auto cleanup = detail::scope_exit([&]() {
  14786. // Restore blocking mode after handshake
  14787. if (bio) { BIO_set_nbio(bio, 0); }
  14788. detail::set_nonblocking(sock, false);
  14789. });
  14790. auto res = 0;
  14791. while ((res = SSL_accept(ssl)) != 1) {
  14792. auto ssl_err = SSL_get_error(ssl, res);
  14793. switch (ssl_err) {
  14794. case SSL_ERROR_WANT_READ:
  14795. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14796. continue;
  14797. }
  14798. break;
  14799. case SSL_ERROR_WANT_WRITE:
  14800. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14801. continue;
  14802. }
  14803. break;
  14804. default: break;
  14805. }
  14806. if (err) {
  14807. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14808. err->backend_code = ERR_get_error();
  14809. }
  14810. return false;
  14811. }
  14812. if (err) { err->code = ErrorCode::Success; }
  14813. return true;
  14814. }
  14815. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14816. if (!session || !buf) {
  14817. err.code = ErrorCode::Fatal;
  14818. return -1;
  14819. }
  14820. auto ssl = static_cast<SSL *>(session);
  14821. constexpr auto max_len =
  14822. static_cast<size_t>((std::numeric_limits<int>::max)());
  14823. if (len > max_len) { len = max_len; }
  14824. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14825. if (ret > 0) {
  14826. err.code = ErrorCode::Success;
  14827. return ret;
  14828. }
  14829. auto ssl_err = SSL_get_error(ssl, ret);
  14830. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14831. if (err.code == ErrorCode::PeerClosed) {
  14832. return 0;
  14833. } // Gracefully handle the peer closed state.
  14834. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14835. return -1;
  14836. }
  14837. inline ssize_t write(session_t session, const void *buf, size_t len,
  14838. TlsError &err) {
  14839. if (!session || !buf) {
  14840. err.code = ErrorCode::Fatal;
  14841. return -1;
  14842. }
  14843. auto ssl = static_cast<SSL *>(session);
  14844. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14845. if (ret > 0) {
  14846. err.code = ErrorCode::Success;
  14847. return ret;
  14848. }
  14849. auto ssl_err = SSL_get_error(ssl, ret);
  14850. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14851. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14852. return -1;
  14853. }
  14854. inline int pending(const_session_t session) {
  14855. if (!session) return 0;
  14856. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14857. }
  14858. inline void shutdown(session_t session, bool graceful) {
  14859. if (!session) return;
  14860. auto ssl = static_cast<SSL *>(session);
  14861. if (graceful) {
  14862. // First call sends close_notify
  14863. if (SSL_shutdown(ssl) == 0) {
  14864. // Second call waits for peer's close_notify
  14865. SSL_shutdown(ssl);
  14866. }
  14867. }
  14868. }
  14869. inline bool is_peer_closed(session_t session, socket_t sock) {
  14870. if (!session) return true;
  14871. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14872. detail::set_nonblocking(sock, true);
  14873. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14874. auto ssl = static_cast<SSL *>(session);
  14875. char buf;
  14876. auto ret = SSL_peek(ssl, &buf, 1);
  14877. if (ret > 0) return false;
  14878. auto err = SSL_get_error(ssl, ret);
  14879. return err == SSL_ERROR_ZERO_RETURN;
  14880. }
  14881. inline cert_t get_peer_cert(const_session_t session) {
  14882. if (!session) return nullptr;
  14883. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14884. static_cast<SSL *>(const_cast<void *>(session))));
  14885. }
  14886. inline void free_cert(cert_t cert) {
  14887. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14888. }
  14889. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14890. if (!cert || !hostname) return false;
  14891. auto x509 = static_cast<X509 *>(cert);
  14892. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14893. if (detail::is_ip_address(hostname)) {
  14894. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14895. }
  14896. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14897. }
  14898. inline uint64_t hostname_mismatch_code() {
  14899. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14900. }
  14901. inline long get_verify_result(const_session_t session) {
  14902. if (!session) return X509_V_ERR_UNSPECIFIED;
  14903. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14904. }
  14905. inline std::string get_cert_subject_cn(cert_t cert) {
  14906. if (!cert) return "";
  14907. auto x509 = static_cast<X509 *>(cert);
  14908. auto subject_name = X509_get_subject_name(x509);
  14909. if (!subject_name) return "";
  14910. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14911. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14912. if (idx < 0) return "";
  14913. auto entry = X509_NAME_get_entry(subject_name, idx);
  14914. if (!entry) return "";
  14915. auto data = X509_NAME_ENTRY_get_data(entry);
  14916. if (!data) return "";
  14917. return std::string(
  14918. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14919. static_cast<size_t>(ASN1_STRING_length(data)));
  14920. }
  14921. inline std::string get_cert_issuer_name(cert_t cert) {
  14922. if (!cert) return "";
  14923. auto x509 = static_cast<X509 *>(cert);
  14924. auto issuer_name = X509_get_issuer_name(x509);
  14925. if (!issuer_name) return "";
  14926. char buf[256];
  14927. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14928. return std::string(buf);
  14929. }
  14930. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14931. sans.clear();
  14932. if (!cert) return false;
  14933. auto x509 = static_cast<X509 *>(cert);
  14934. auto names = static_cast<GENERAL_NAMES *>(
  14935. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14936. if (!names) return true; // No SANs is valid
  14937. auto count = sk_GENERAL_NAME_num(names);
  14938. for (decltype(count) i = 0; i < count; i++) {
  14939. auto gen = sk_GENERAL_NAME_value(names, i);
  14940. if (!gen) continue;
  14941. SanEntry entry;
  14942. switch (gen->type) {
  14943. case GEN_DNS:
  14944. entry.type = SanType::DNS;
  14945. if (gen->d.dNSName) {
  14946. entry.value = std::string(
  14947. reinterpret_cast<const char *>(
  14948. ASN1_STRING_get0_data(gen->d.dNSName)),
  14949. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14950. }
  14951. break;
  14952. case GEN_IPADD:
  14953. entry.type = SanType::IP;
  14954. if (gen->d.iPAddress) {
  14955. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14956. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14957. if (len == 4) {
  14958. // IPv4
  14959. char buf[INET_ADDRSTRLEN];
  14960. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14961. entry.value = buf;
  14962. } else if (len == 16) {
  14963. // IPv6
  14964. char buf[INET6_ADDRSTRLEN];
  14965. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14966. entry.value = buf;
  14967. }
  14968. }
  14969. break;
  14970. case GEN_EMAIL:
  14971. entry.type = SanType::EMAIL;
  14972. if (gen->d.rfc822Name) {
  14973. entry.value = std::string(
  14974. reinterpret_cast<const char *>(
  14975. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14976. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14977. }
  14978. break;
  14979. case GEN_URI:
  14980. entry.type = SanType::URI;
  14981. if (gen->d.uniformResourceIdentifier) {
  14982. entry.value = std::string(
  14983. reinterpret_cast<const char *>(
  14984. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14985. static_cast<size_t>(
  14986. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14987. }
  14988. break;
  14989. default: entry.type = SanType::OTHER; break;
  14990. }
  14991. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14992. }
  14993. GENERAL_NAMES_free(names);
  14994. return true;
  14995. }
  14996. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14997. time_t &not_after) {
  14998. if (!cert) return false;
  14999. auto x509 = static_cast<X509 *>(cert);
  15000. auto nb = X509_get0_notBefore(x509);
  15001. auto na = X509_get0_notAfter(x509);
  15002. if (!nb || !na) return false;
  15003. ASN1_TIME *epoch = ASN1_TIME_new();
  15004. if (!epoch) return false;
  15005. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  15006. if (!ASN1_TIME_set(epoch, 0)) return false;
  15007. int pday, psec;
  15008. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  15009. not_before = 86400 * (time_t)pday + psec;
  15010. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  15011. not_after = 86400 * (time_t)pday + psec;
  15012. return true;
  15013. }
  15014. inline std::string get_cert_serial(cert_t cert) {
  15015. if (!cert) return "";
  15016. auto x509 = static_cast<X509 *>(cert);
  15017. auto serial = X509_get_serialNumber(x509);
  15018. if (!serial) return "";
  15019. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  15020. if (!bn) return "";
  15021. auto hex = BN_bn2hex(bn);
  15022. BN_free(bn);
  15023. if (!hex) return "";
  15024. std::string result(hex);
  15025. OPENSSL_free(hex);
  15026. return result;
  15027. }
  15028. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15029. if (!cert) return false;
  15030. auto x509 = static_cast<X509 *>(cert);
  15031. auto len = i2d_X509(x509, nullptr);
  15032. if (len < 0) return false;
  15033. der.resize(static_cast<size_t>(len));
  15034. auto p = der.data();
  15035. i2d_X509(x509, &p);
  15036. return true;
  15037. }
  15038. inline const char *get_sni(const_session_t session) {
  15039. if (!session) return nullptr;
  15040. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15041. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15042. }
  15043. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  15044. inline uint64_t get_error() { return ERR_get_error(); }
  15045. inline std::string error_string(uint64_t code) {
  15046. char buf[256];
  15047. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  15048. return std::string(buf);
  15049. }
  15050. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15051. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  15052. if (!mem) { return nullptr; }
  15053. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  15054. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  15055. if (!inf) { return nullptr; }
  15056. auto store = X509_STORE_new();
  15057. if (store) {
  15058. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15059. auto itmp = sk_X509_INFO_value(inf, i);
  15060. if (!itmp) { continue; }
  15061. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15062. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15063. }
  15064. }
  15065. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15066. return static_cast<ca_store_t>(store);
  15067. }
  15068. inline void free_ca_store(ca_store_t store) {
  15069. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15070. }
  15071. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15072. if (!ctx || !store) { return false; }
  15073. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15074. auto x509_store = static_cast<X509_STORE *>(store);
  15075. // Check if same store is already set
  15076. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15077. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15078. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15079. return true;
  15080. }
  15081. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15082. certs.clear();
  15083. if (!ctx) { return 0; }
  15084. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15085. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15086. if (!store) { return 0; }
  15087. auto objs = impl::get_store_objects(store);
  15088. if (!objs) { return 0; }
  15089. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15090. auto count = sk_X509_OBJECT_num(objs);
  15091. for (decltype(count) i = 0; i < count; i++) {
  15092. auto obj = sk_X509_OBJECT_value(objs, i);
  15093. if (!obj) { continue; }
  15094. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15095. auto x509 = X509_OBJECT_get0_X509(obj);
  15096. if (x509) {
  15097. // Increment reference count so caller can free it
  15098. X509_up_ref(x509);
  15099. certs.push_back(static_cast<cert_t>(x509));
  15100. }
  15101. }
  15102. }
  15103. return certs.size();
  15104. }
  15105. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15106. std::vector<std::string> names;
  15107. if (!ctx) { return names; }
  15108. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15109. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15110. if (!store) { return names; }
  15111. auto objs = impl::get_store_objects(store);
  15112. if (!objs) { return names; }
  15113. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15114. auto count = sk_X509_OBJECT_num(objs);
  15115. for (decltype(count) i = 0; i < count; i++) {
  15116. auto obj = sk_X509_OBJECT_value(objs, i);
  15117. if (!obj) { continue; }
  15118. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15119. auto x509 = X509_OBJECT_get0_X509(obj);
  15120. if (x509) {
  15121. auto subject = X509_get_subject_name(x509);
  15122. if (subject) {
  15123. char buf[512];
  15124. X509_NAME_oneline(subject, buf, sizeof(buf));
  15125. names.push_back(buf);
  15126. }
  15127. }
  15128. }
  15129. }
  15130. return names;
  15131. }
  15132. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15133. const char *key_pem, const char *password) {
  15134. if (!ctx || !cert_pem || !key_pem) { return false; }
  15135. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15136. // Load certificate from PEM
  15137. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15138. if (!cert_bio) { return false; }
  15139. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15140. BIO_free(cert_bio);
  15141. if (!cert) { return false; }
  15142. // Load private key from PEM
  15143. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15144. if (!key_bio) {
  15145. X509_free(cert);
  15146. return false;
  15147. }
  15148. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15149. password ? const_cast<char *>(password)
  15150. : nullptr);
  15151. BIO_free(key_bio);
  15152. if (!key) {
  15153. X509_free(cert);
  15154. return false;
  15155. }
  15156. // Update certificate and key
  15157. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15158. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15159. X509_free(cert);
  15160. EVP_PKEY_free(key);
  15161. return ret;
  15162. }
  15163. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15164. if (!ctx || !ca_pem) { return false; }
  15165. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15166. // Create new X509_STORE from PEM
  15167. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15168. if (!store) { return false; }
  15169. // SSL_CTX_set_cert_store takes ownership
  15170. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15171. // Set client CA list for client certificate request
  15172. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15173. if (ca_list) {
  15174. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15175. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15176. }
  15177. return true;
  15178. }
  15179. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15180. if (!ctx) { return false; }
  15181. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15182. impl::get_verify_callback() = std::move(callback);
  15183. if (impl::get_verify_callback()) {
  15184. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15185. } else {
  15186. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15187. }
  15188. return true;
  15189. }
  15190. inline long get_verify_error(const_session_t session) {
  15191. if (!session) { return -1; }
  15192. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15193. return SSL_get_verify_result(ssl);
  15194. }
  15195. inline std::string verify_error_string(long error_code) {
  15196. if (error_code == X509_V_OK) { return ""; }
  15197. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15198. return str ? str : "unknown error";
  15199. }
  15200. } // namespace tls
  15201. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15202. /*
  15203. * Group 9: TLS abstraction layer - Mbed TLS backend
  15204. */
  15205. /*
  15206. * Mbed TLS Backend Implementation
  15207. */
  15208. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15209. namespace tls {
  15210. namespace impl {
  15211. // Mbed TLS session wrapper
  15212. struct MbedTlsSession {
  15213. mbedtls_ssl_context ssl;
  15214. socket_t sock = INVALID_SOCKET;
  15215. std::string hostname; // For client: set via set_sni
  15216. std::string sni_hostname; // For server: received from client via SNI callback
  15217. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15218. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15219. MbedTlsSession(const MbedTlsSession &) = delete;
  15220. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15221. };
  15222. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15223. // queue)
  15224. inline int &mbedtls_last_error() {
  15225. static thread_local int err = 0;
  15226. return err;
  15227. }
  15228. // Helper to map Mbed TLS error to ErrorCode
  15229. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15230. if (ret == 0) { return ErrorCode::Success; }
  15231. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15232. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15233. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15234. return ErrorCode::PeerClosed;
  15235. }
  15236. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15237. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15238. out_errno = errno;
  15239. return ErrorCode::SyscallError;
  15240. }
  15241. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15242. return ErrorCode::CertVerifyFailed;
  15243. }
  15244. return ErrorCode::Fatal;
  15245. }
  15246. // BIO-like send callback for Mbed TLS
  15247. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15248. size_t len) {
  15249. auto sock = *static_cast<socket_t *>(ctx);
  15250. #ifdef _WIN32
  15251. auto ret =
  15252. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15253. if (ret == SOCKET_ERROR) {
  15254. int err = WSAGetLastError();
  15255. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15256. return MBEDTLS_ERR_NET_SEND_FAILED;
  15257. }
  15258. #else
  15259. auto ret = send(sock, buf, len, 0);
  15260. if (ret < 0) {
  15261. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15262. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15263. }
  15264. return MBEDTLS_ERR_NET_SEND_FAILED;
  15265. }
  15266. #endif
  15267. return static_cast<int>(ret);
  15268. }
  15269. // BIO-like recv callback for Mbed TLS
  15270. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15271. auto sock = *static_cast<socket_t *>(ctx);
  15272. #ifdef _WIN32
  15273. auto ret =
  15274. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15275. if (ret == SOCKET_ERROR) {
  15276. int err = WSAGetLastError();
  15277. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15278. return MBEDTLS_ERR_NET_RECV_FAILED;
  15279. }
  15280. #else
  15281. auto ret = recv(sock, buf, len, 0);
  15282. if (ret < 0) {
  15283. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15284. return MBEDTLS_ERR_SSL_WANT_READ;
  15285. }
  15286. return MBEDTLS_ERR_NET_RECV_FAILED;
  15287. }
  15288. #endif
  15289. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15290. return static_cast<int>(ret);
  15291. }
  15292. // MbedTlsContext constructor/destructor implementations
  15293. inline MbedTlsContext::MbedTlsContext() {
  15294. mbedtls_ssl_config_init(&conf);
  15295. mbedtls_entropy_init(&entropy);
  15296. mbedtls_ctr_drbg_init(&ctr_drbg);
  15297. mbedtls_x509_crt_init(&ca_chain);
  15298. mbedtls_x509_crt_init(&own_cert);
  15299. mbedtls_pk_init(&own_key);
  15300. }
  15301. inline MbedTlsContext::~MbedTlsContext() {
  15302. mbedtls_pk_free(&own_key);
  15303. mbedtls_x509_crt_free(&own_cert);
  15304. mbedtls_x509_crt_free(&ca_chain);
  15305. mbedtls_ctr_drbg_free(&ctr_drbg);
  15306. mbedtls_entropy_free(&entropy);
  15307. mbedtls_ssl_config_free(&conf);
  15308. }
  15309. // Thread-local storage for SNI captured during handshake
  15310. // This is needed because the SNI callback doesn't have a way to pass
  15311. // session-specific data before the session is fully set up
  15312. inline std::string &mbedpending_sni() {
  15313. static thread_local std::string sni;
  15314. return sni;
  15315. }
  15316. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15317. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15318. const unsigned char *name, size_t name_len) {
  15319. (void)p_ctx;
  15320. (void)ssl;
  15321. // Store SNI name in thread-local storage
  15322. // It will be retrieved and stored in the session after handshake
  15323. if (name && name_len > 0) {
  15324. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15325. } else {
  15326. mbedpending_sni().clear();
  15327. }
  15328. return 0; // Accept any SNI
  15329. }
  15330. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15331. int cert_depth, uint32_t *flags);
  15332. // MbedTLS verify callback wrapper
  15333. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15334. int cert_depth, uint32_t *flags) {
  15335. auto &callback = get_verify_callback();
  15336. if (!callback) { return 0; } // Continue with default verification
  15337. // data points to the MbedTlsSession
  15338. auto *session = static_cast<MbedTlsSession *>(data);
  15339. // Build context
  15340. VerifyContext verify_ctx;
  15341. verify_ctx.session = static_cast<session_t>(session);
  15342. verify_ctx.cert = static_cast<cert_t>(crt);
  15343. verify_ctx.depth = cert_depth;
  15344. verify_ctx.preverify_ok = (*flags == 0);
  15345. verify_ctx.error_code = static_cast<long>(*flags);
  15346. // Convert Mbed TLS flags to error string
  15347. static thread_local char error_buf[256];
  15348. if (*flags != 0) {
  15349. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15350. verify_ctx.error_string = error_buf;
  15351. } else {
  15352. verify_ctx.error_string = nullptr;
  15353. }
  15354. bool accepted = callback(verify_ctx);
  15355. if (accepted) {
  15356. *flags = 0; // Clear all error flags
  15357. return 0;
  15358. }
  15359. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15360. }
  15361. } // namespace impl
  15362. inline ctx_t create_client_context() {
  15363. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15364. if (!ctx) { return nullptr; }
  15365. ctx->is_server = false;
  15366. // Seed the random number generator
  15367. const char *pers = "httplib_client";
  15368. int ret = mbedtls_ctr_drbg_seed(
  15369. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15370. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15371. if (ret != 0) {
  15372. impl::mbedtls_last_error() = ret;
  15373. delete ctx;
  15374. return nullptr;
  15375. }
  15376. // Set up SSL config for client
  15377. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15378. MBEDTLS_SSL_TRANSPORT_STREAM,
  15379. MBEDTLS_SSL_PRESET_DEFAULT);
  15380. if (ret != 0) {
  15381. impl::mbedtls_last_error() = ret;
  15382. delete ctx;
  15383. return nullptr;
  15384. }
  15385. // Set random number generator
  15386. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15387. // Default: verify peer certificate
  15388. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15389. // Set minimum TLS version to 1.2
  15390. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15391. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15392. #else
  15393. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15394. MBEDTLS_SSL_MINOR_VERSION_3);
  15395. #endif
  15396. return static_cast<ctx_t>(ctx);
  15397. }
  15398. inline ctx_t create_server_context() {
  15399. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15400. if (!ctx) { return nullptr; }
  15401. ctx->is_server = true;
  15402. // Seed the random number generator
  15403. const char *pers = "httplib_server";
  15404. int ret = mbedtls_ctr_drbg_seed(
  15405. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15406. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15407. if (ret != 0) {
  15408. impl::mbedtls_last_error() = ret;
  15409. delete ctx;
  15410. return nullptr;
  15411. }
  15412. // Set up SSL config for server
  15413. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15414. MBEDTLS_SSL_TRANSPORT_STREAM,
  15415. MBEDTLS_SSL_PRESET_DEFAULT);
  15416. if (ret != 0) {
  15417. impl::mbedtls_last_error() = ret;
  15418. delete ctx;
  15419. return nullptr;
  15420. }
  15421. // Set random number generator
  15422. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15423. // Default: don't verify client
  15424. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15425. // Set minimum TLS version to 1.2
  15426. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15427. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15428. #else
  15429. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15430. MBEDTLS_SSL_MINOR_VERSION_3);
  15431. #endif
  15432. // Set SNI callback to capture client's SNI hostname
  15433. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15434. return static_cast<ctx_t>(ctx);
  15435. }
  15436. inline void free_context(ctx_t ctx) {
  15437. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15438. }
  15439. inline bool set_min_version(ctx_t ctx, Version version) {
  15440. if (!ctx) { return false; }
  15441. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15442. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15443. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15444. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15445. if (version >= Version::TLS1_3) {
  15446. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15447. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15448. #endif
  15449. }
  15450. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15451. #else
  15452. // Mbed TLS 2.x uses major/minor version numbers
  15453. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15454. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15455. if (version >= Version::TLS1_3) {
  15456. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15457. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15458. #else
  15459. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15460. #endif
  15461. }
  15462. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15463. #endif
  15464. return true;
  15465. }
  15466. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15467. if (!ctx || !pem) { return false; }
  15468. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15469. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15470. // Add null terminator if not present
  15471. std::string pem_str(pem, len);
  15472. int ret = mbedtls_x509_crt_parse(
  15473. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15474. pem_str.size() + 1);
  15475. if (ret != 0) {
  15476. impl::mbedtls_last_error() = ret;
  15477. return false;
  15478. }
  15479. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15480. return true;
  15481. }
  15482. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15483. if (!ctx || !file_path) { return false; }
  15484. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15485. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15486. if (ret != 0) {
  15487. impl::mbedtls_last_error() = ret;
  15488. return false;
  15489. }
  15490. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15491. return true;
  15492. }
  15493. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15494. if (!ctx || !dir_path) { return false; }
  15495. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15496. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15497. if (ret < 0) { // Returns number of certs on success, negative on error
  15498. impl::mbedtls_last_error() = ret;
  15499. return false;
  15500. }
  15501. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15502. return true;
  15503. }
  15504. inline bool load_system_certs(ctx_t ctx) {
  15505. if (!ctx) { return false; }
  15506. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15507. bool loaded = false;
  15508. #ifdef _WIN32
  15509. loaded = impl::enumerate_windows_system_certs(
  15510. [&](const unsigned char *data, size_t len) {
  15511. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15512. });
  15513. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15514. loaded = impl::enumerate_macos_keychain_certs(
  15515. [&](const unsigned char *data, size_t len) {
  15516. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15517. });
  15518. #else
  15519. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15520. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15521. loaded = true;
  15522. break;
  15523. }
  15524. }
  15525. if (!loaded) {
  15526. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15527. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15528. loaded = true;
  15529. break;
  15530. }
  15531. }
  15532. }
  15533. #endif
  15534. if (loaded) {
  15535. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15536. }
  15537. return loaded;
  15538. }
  15539. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15540. const char *password) {
  15541. if (!ctx || !cert || !key) { return false; }
  15542. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15543. // Parse certificate
  15544. std::string cert_str(cert);
  15545. int ret = mbedtls_x509_crt_parse(
  15546. &mctx->own_cert,
  15547. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15548. cert_str.size() + 1);
  15549. if (ret != 0) {
  15550. impl::mbedtls_last_error() = ret;
  15551. return false;
  15552. }
  15553. // Parse private key
  15554. std::string key_str(key);
  15555. const unsigned char *pwd =
  15556. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15557. size_t pwd_len = password ? strlen(password) : 0;
  15558. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15559. ret = mbedtls_pk_parse_key(
  15560. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15561. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15562. &mctx->ctr_drbg);
  15563. #else
  15564. ret = mbedtls_pk_parse_key(
  15565. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15566. key_str.size() + 1, pwd, pwd_len);
  15567. #endif
  15568. if (ret != 0) {
  15569. impl::mbedtls_last_error() = ret;
  15570. return false;
  15571. }
  15572. // Verify that the certificate and private key match
  15573. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15574. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15575. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15576. #else
  15577. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15578. #endif
  15579. if (ret != 0) {
  15580. impl::mbedtls_last_error() = ret;
  15581. return false;
  15582. }
  15583. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15584. if (ret != 0) {
  15585. impl::mbedtls_last_error() = ret;
  15586. return false;
  15587. }
  15588. return true;
  15589. }
  15590. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15591. const char *key_path, const char *password) {
  15592. if (!ctx || !cert_path || !key_path) { return false; }
  15593. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15594. // Parse certificate file
  15595. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15596. if (ret != 0) {
  15597. impl::mbedtls_last_error() = ret;
  15598. return false;
  15599. }
  15600. // Parse private key file
  15601. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15602. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15603. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15604. #else
  15605. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15606. #endif
  15607. if (ret != 0) {
  15608. impl::mbedtls_last_error() = ret;
  15609. return false;
  15610. }
  15611. // Verify that the certificate and private key match
  15612. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15613. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15614. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15615. #else
  15616. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15617. #endif
  15618. if (ret != 0) {
  15619. impl::mbedtls_last_error() = ret;
  15620. return false;
  15621. }
  15622. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15623. if (ret != 0) {
  15624. impl::mbedtls_last_error() = ret;
  15625. return false;
  15626. }
  15627. return true;
  15628. }
  15629. inline void set_verify_client(ctx_t ctx, bool require) {
  15630. if (!ctx) { return; }
  15631. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15632. mctx->verify_client = require;
  15633. if (require) {
  15634. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15635. } else {
  15636. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15637. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15638. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15639. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15640. : MBEDTLS_SSL_VERIFY_NONE);
  15641. }
  15642. }
  15643. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15644. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15645. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15646. auto session = new (std::nothrow) impl::MbedTlsSession();
  15647. if (!session) { return nullptr; }
  15648. session->sock = sock;
  15649. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15650. if (ret != 0) {
  15651. impl::mbedtls_last_error() = ret;
  15652. delete session;
  15653. return nullptr;
  15654. }
  15655. // Explicitly opt out of in-handshake hostname verification by default;
  15656. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15657. // fails outright when no hostname was set. set_sni() installs the real
  15658. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15659. // caller verifies the certificate identity post-handshake via
  15660. // verify_hostname().
  15661. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15662. // Set BIO callbacks
  15663. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15664. impl::mbedtls_net_recv_cb, nullptr);
  15665. // Set per-session verify callback with session pointer if callback is
  15666. // registered
  15667. if (mctx->has_verify_callback) {
  15668. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15669. session);
  15670. }
  15671. return static_cast<session_t>(session);
  15672. }
  15673. inline void free_session(session_t session) {
  15674. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15675. }
  15676. inline bool set_sni(session_t session, const char *hostname) {
  15677. if (!session || !hostname) { return false; }
  15678. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15679. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15680. if (ret != 0) {
  15681. impl::mbedtls_last_error() = ret;
  15682. return false;
  15683. }
  15684. msession->hostname = hostname;
  15685. return true;
  15686. }
  15687. inline bool set_hostname(session_t session, const char *hostname) {
  15688. // In Mbed TLS, set_hostname also sets up hostname verification
  15689. return set_sni(session, hostname);
  15690. }
  15691. inline TlsError connect(session_t session) {
  15692. TlsError err;
  15693. if (!session) {
  15694. err.code = ErrorCode::Fatal;
  15695. return err;
  15696. }
  15697. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15698. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15699. if (ret == 0) {
  15700. err.code = ErrorCode::Success;
  15701. } else {
  15702. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15703. err.backend_code = static_cast<uint64_t>(-ret);
  15704. impl::mbedtls_last_error() = ret;
  15705. }
  15706. return err;
  15707. }
  15708. inline TlsError accept(session_t session) {
  15709. // Same as connect for Mbed TLS - handshake works for both client and server
  15710. auto result = connect(session);
  15711. // After successful handshake, capture SNI from thread-local storage
  15712. if (result.code == ErrorCode::Success && session) {
  15713. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15714. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15715. impl::mbedpending_sni().clear();
  15716. }
  15717. return result;
  15718. }
  15719. inline bool connect_nonblocking(session_t session, socket_t sock,
  15720. time_t timeout_sec, time_t timeout_usec,
  15721. TlsError *err) {
  15722. if (!session) {
  15723. if (err) { err->code = ErrorCode::Fatal; }
  15724. return false;
  15725. }
  15726. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15727. // Set socket to non-blocking mode
  15728. detail::set_nonblocking(sock, true);
  15729. auto cleanup =
  15730. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15731. int ret;
  15732. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15733. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15734. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15735. continue;
  15736. }
  15737. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15738. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15739. continue;
  15740. }
  15741. }
  15742. // TlsError or timeout
  15743. if (err) {
  15744. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15745. err->backend_code = static_cast<uint64_t>(-ret);
  15746. }
  15747. impl::mbedtls_last_error() = ret;
  15748. return false;
  15749. }
  15750. if (err) { err->code = ErrorCode::Success; }
  15751. return true;
  15752. }
  15753. inline bool accept_nonblocking(session_t session, socket_t sock,
  15754. time_t timeout_sec, time_t timeout_usec,
  15755. TlsError *err) {
  15756. // Same implementation as connect for Mbed TLS
  15757. bool result =
  15758. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15759. // After successful handshake, capture SNI from thread-local storage
  15760. if (result && session) {
  15761. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15762. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15763. impl::mbedpending_sni().clear();
  15764. }
  15765. return result;
  15766. }
  15767. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15768. if (!session || !buf) {
  15769. err.code = ErrorCode::Fatal;
  15770. return -1;
  15771. }
  15772. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15773. int ret =
  15774. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15775. if (ret > 0) {
  15776. err.code = ErrorCode::Success;
  15777. return static_cast<ssize_t>(ret);
  15778. }
  15779. if (ret == 0) {
  15780. err.code = ErrorCode::PeerClosed;
  15781. return 0;
  15782. }
  15783. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15784. err.backend_code = static_cast<uint64_t>(-ret);
  15785. impl::mbedtls_last_error() = ret;
  15786. // mbedTLS signals a clean close_notify via a negative error code rather
  15787. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15788. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15789. return -1;
  15790. }
  15791. inline ssize_t write(session_t session, const void *buf, size_t len,
  15792. TlsError &err) {
  15793. if (!session || !buf) {
  15794. err.code = ErrorCode::Fatal;
  15795. return -1;
  15796. }
  15797. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15798. int ret = mbedtls_ssl_write(&msession->ssl,
  15799. static_cast<const unsigned char *>(buf), len);
  15800. if (ret > 0) {
  15801. err.code = ErrorCode::Success;
  15802. return static_cast<ssize_t>(ret);
  15803. }
  15804. if (ret == 0) {
  15805. err.code = ErrorCode::PeerClosed;
  15806. return 0;
  15807. }
  15808. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15809. err.backend_code = static_cast<uint64_t>(-ret);
  15810. impl::mbedtls_last_error() = ret;
  15811. return -1;
  15812. }
  15813. inline int pending(const_session_t session) {
  15814. if (!session) { return 0; }
  15815. auto msession =
  15816. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15817. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15818. }
  15819. inline void shutdown(session_t session, bool graceful) {
  15820. if (!session) { return; }
  15821. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15822. if (graceful) {
  15823. // Try to send close_notify, but don't block forever
  15824. int ret;
  15825. int attempts = 0;
  15826. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15827. attempts < 3) {
  15828. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15829. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15830. break;
  15831. }
  15832. attempts++;
  15833. }
  15834. }
  15835. }
  15836. inline bool is_peer_closed(session_t session, socket_t sock) {
  15837. if (!session || sock == INVALID_SOCKET) { return true; }
  15838. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15839. // Check if there's already decrypted data available in the TLS buffer
  15840. // If so, the connection is definitely alive
  15841. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15842. // Set socket to non-blocking to avoid blocking on read
  15843. detail::set_nonblocking(sock, true);
  15844. auto cleanup =
  15845. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15846. // Try a 1-byte read to check connection status
  15847. // Note: This will consume the byte if data is available, but for the
  15848. // purpose of checking if peer is closed, this should be acceptable
  15849. // since we're only called when we expect the connection might be closing
  15850. unsigned char buf;
  15851. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15852. // If we got data or WANT_READ (would block), connection is alive
  15853. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15854. // If we get a peer close notify or a connection reset, the peer is closed
  15855. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15856. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15857. }
  15858. inline cert_t get_peer_cert(const_session_t session) {
  15859. if (!session) { return nullptr; }
  15860. auto msession =
  15861. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15862. // Mbed TLS returns a pointer to the internal peer cert chain.
  15863. // WARNING: This pointer is only valid while the session is active.
  15864. // Do not use the certificate after calling free_session().
  15865. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15866. return const_cast<mbedtls_x509_crt *>(cert);
  15867. }
  15868. inline void free_cert(cert_t cert) {
  15869. // Mbed TLS: peer certificate is owned by the SSL context.
  15870. // No-op here, but callers should still call this for cross-backend
  15871. // portability.
  15872. (void)cert;
  15873. }
  15874. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15875. if (!cert || !hostname) { return false; }
  15876. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15877. std::string host_str(hostname);
  15878. // Check if hostname is an IP address (IPv4 or IPv6)
  15879. unsigned char ip_bytes[16];
  15880. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15881. auto is_ip = ip_len > 0;
  15882. // Check Subject Alternative Names (SAN)
  15883. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15884. // - DNS names: raw string bytes
  15885. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15886. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15887. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15888. const unsigned char *p = san->buf.p;
  15889. size_t len = san->buf.len;
  15890. if (is_ip) {
  15891. // For an IP host, only a matching iPAddress SAN of the same family
  15892. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15893. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15894. } else {
  15895. // Check if this SAN is a DNS name (printable ASCII string)
  15896. bool is_dns = len > 0;
  15897. for (size_t i = 0; i < len && is_dns; i++) {
  15898. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15899. }
  15900. if (is_dns) {
  15901. std::string san_name(reinterpret_cast<const char *>(p), len);
  15902. if (detail::match_hostname(san_name, host_str)) { return true; }
  15903. }
  15904. }
  15905. san = san->next;
  15906. }
  15907. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15908. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15909. // the OpenSSL backend's X509_check_ip behaves the same way).
  15910. if (!is_ip) {
  15911. char cn[256];
  15912. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15913. if (ret > 0) {
  15914. std::string cn_str(cn);
  15915. // Look for "CN=" in the DN string
  15916. size_t cn_pos = cn_str.find("CN=");
  15917. if (cn_pos != std::string::npos) {
  15918. size_t start = cn_pos + 3;
  15919. size_t end = cn_str.find(',', start);
  15920. std::string cn_value =
  15921. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15922. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15923. }
  15924. }
  15925. }
  15926. return false;
  15927. }
  15928. inline uint64_t hostname_mismatch_code() {
  15929. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15930. }
  15931. inline long get_verify_result(const_session_t session) {
  15932. if (!session) { return -1; }
  15933. auto msession =
  15934. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15935. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15936. // Return 0 (X509_V_OK equivalent) if verification passed
  15937. return flags == 0 ? 0 : static_cast<long>(flags);
  15938. }
  15939. inline std::string get_cert_subject_cn(cert_t cert) {
  15940. if (!cert) return "";
  15941. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15942. // Find the CN in the subject
  15943. const mbedtls_x509_name *name = &x509->subject;
  15944. while (name != nullptr) {
  15945. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15946. return std::string(reinterpret_cast<const char *>(name->val.p),
  15947. name->val.len);
  15948. }
  15949. name = name->next;
  15950. }
  15951. return "";
  15952. }
  15953. inline std::string get_cert_issuer_name(cert_t cert) {
  15954. if (!cert) return "";
  15955. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15956. // Build a human-readable issuer name string
  15957. char buf[512];
  15958. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15959. if (ret < 0) return "";
  15960. return std::string(buf);
  15961. }
  15962. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15963. sans.clear();
  15964. if (!cert) return false;
  15965. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15966. // Parse the Subject Alternative Name extension
  15967. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15968. while (cur != nullptr) {
  15969. if (cur->buf.len > 0) {
  15970. // Mbed TLS stores SAN as ASN.1 sequences
  15971. // The tag byte indicates the type
  15972. const unsigned char *p = cur->buf.p;
  15973. size_t len = cur->buf.len;
  15974. // First byte is the tag
  15975. unsigned char tag = *p;
  15976. p++;
  15977. len--;
  15978. // Parse length (simple single-byte length assumed)
  15979. if (len > 0 && *p < 0x80) {
  15980. size_t value_len = *p;
  15981. p++;
  15982. len--;
  15983. if (value_len <= len) {
  15984. SanEntry entry;
  15985. // ASN.1 context tags for GeneralName
  15986. switch (tag & 0x1F) {
  15987. case 2: // dNSName
  15988. entry.type = SanType::DNS;
  15989. entry.value =
  15990. std::string(reinterpret_cast<const char *>(p), value_len);
  15991. break;
  15992. case 7: // iPAddress
  15993. entry.type = SanType::IP;
  15994. if (value_len == 4) {
  15995. // IPv4
  15996. char buf[16];
  15997. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15998. entry.value = buf;
  15999. } else if (value_len == 16) {
  16000. // IPv6
  16001. char buf[64];
  16002. snprintf(buf, sizeof(buf),
  16003. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16004. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16005. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  16006. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  16007. entry.value = buf;
  16008. }
  16009. break;
  16010. case 1: // rfc822Name (email)
  16011. entry.type = SanType::EMAIL;
  16012. entry.value =
  16013. std::string(reinterpret_cast<const char *>(p), value_len);
  16014. break;
  16015. case 6: // uniformResourceIdentifier
  16016. entry.type = SanType::URI;
  16017. entry.value =
  16018. std::string(reinterpret_cast<const char *>(p), value_len);
  16019. break;
  16020. default: entry.type = SanType::OTHER; break;
  16021. }
  16022. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16023. }
  16024. }
  16025. }
  16026. cur = cur->next;
  16027. }
  16028. return true;
  16029. }
  16030. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16031. time_t &not_after) {
  16032. if (!cert) return false;
  16033. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16034. // Convert mbedtls_x509_time to time_t
  16035. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  16036. struct tm tm_time = {};
  16037. tm_time.tm_year = t.year - 1900;
  16038. tm_time.tm_mon = t.mon - 1;
  16039. tm_time.tm_mday = t.day;
  16040. tm_time.tm_hour = t.hour;
  16041. tm_time.tm_min = t.min;
  16042. tm_time.tm_sec = t.sec;
  16043. #ifdef _WIN32
  16044. return _mkgmtime(&tm_time);
  16045. #else
  16046. return timegm(&tm_time);
  16047. #endif
  16048. };
  16049. not_before = to_time_t(x509->valid_from);
  16050. not_after = to_time_t(x509->valid_to);
  16051. return true;
  16052. }
  16053. inline std::string get_cert_serial(cert_t cert) {
  16054. if (!cert) return "";
  16055. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16056. // Convert serial number to hex string
  16057. std::string result;
  16058. result.reserve(x509->serial.len * 2);
  16059. for (size_t i = 0; i < x509->serial.len; i++) {
  16060. char hex[3];
  16061. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16062. result += hex;
  16063. }
  16064. return result;
  16065. }
  16066. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16067. if (!cert) return false;
  16068. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16069. if (!crt->raw.p || crt->raw.len == 0) return false;
  16070. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16071. return true;
  16072. }
  16073. inline const char *get_sni(const_session_t session) {
  16074. if (!session) return nullptr;
  16075. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16076. // For server: return SNI received from client during handshake
  16077. if (!msession->sni_hostname.empty()) {
  16078. return msession->sni_hostname.c_str();
  16079. }
  16080. // For client: return the hostname set via set_sni
  16081. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16082. return nullptr;
  16083. }
  16084. inline uint64_t peek_error() {
  16085. // Mbed TLS doesn't have an error queue, return the last error
  16086. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16087. }
  16088. inline uint64_t get_error() {
  16089. // Mbed TLS doesn't have an error queue, return and clear the last error
  16090. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16091. impl::mbedtls_last_error() = 0;
  16092. return err;
  16093. }
  16094. inline std::string error_string(uint64_t code) {
  16095. char buf[256];
  16096. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16097. return std::string(buf);
  16098. }
  16099. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16100. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16101. if (!ca_chain) { return nullptr; }
  16102. mbedtls_x509_crt_init(ca_chain);
  16103. // mbedtls_x509_crt_parse expects null-terminated PEM
  16104. int ret = mbedtls_x509_crt_parse(ca_chain,
  16105. reinterpret_cast<const unsigned char *>(pem),
  16106. len + 1); // +1 for null terminator
  16107. if (ret != 0) {
  16108. // Try without +1 in case PEM is already null-terminated
  16109. ret = mbedtls_x509_crt_parse(
  16110. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16111. if (ret != 0) {
  16112. mbedtls_x509_crt_free(ca_chain);
  16113. delete ca_chain;
  16114. return nullptr;
  16115. }
  16116. }
  16117. return static_cast<ca_store_t>(ca_chain);
  16118. }
  16119. inline void free_ca_store(ca_store_t store) {
  16120. if (store) {
  16121. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16122. mbedtls_x509_crt_free(ca_chain);
  16123. delete ca_chain;
  16124. }
  16125. }
  16126. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16127. if (!ctx || !store) { return false; }
  16128. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16129. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16130. // Free existing CA chain
  16131. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16132. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16133. // Copy the CA chain (deep copy)
  16134. // Parse from the raw data of the source cert
  16135. mbedtls_x509_crt *src = ca_chain;
  16136. while (src != nullptr) {
  16137. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16138. src->raw.len);
  16139. if (ret != 0) {
  16140. free_ca_store(store);
  16141. return false;
  16142. }
  16143. src = src->next;
  16144. }
  16145. // This function takes ownership of the store; the chain was deep-copied
  16146. // above, so release the source
  16147. free_ca_store(store);
  16148. // Update the SSL config to use the new CA chain
  16149. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16150. return true;
  16151. }
  16152. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16153. certs.clear();
  16154. if (!ctx) { return 0; }
  16155. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16156. // Iterate through the CA chain
  16157. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16158. while (cert != nullptr && cert->raw.len > 0) {
  16159. // Create a copy of the certificate for the caller
  16160. auto *copy = new mbedtls_x509_crt;
  16161. mbedtls_x509_crt_init(copy);
  16162. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16163. if (ret == 0) {
  16164. certs.push_back(static_cast<cert_t>(copy));
  16165. } else {
  16166. mbedtls_x509_crt_free(copy);
  16167. delete copy;
  16168. }
  16169. cert = cert->next;
  16170. }
  16171. return certs.size();
  16172. }
  16173. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16174. std::vector<std::string> names;
  16175. if (!ctx) { return names; }
  16176. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16177. // Iterate through the CA chain
  16178. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16179. while (cert != nullptr && cert->raw.len > 0) {
  16180. char buf[512];
  16181. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16182. if (ret > 0) { names.push_back(buf); }
  16183. cert = cert->next;
  16184. }
  16185. return names;
  16186. }
  16187. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16188. const char *key_pem, const char *password) {
  16189. if (!ctx || !cert_pem || !key_pem) { return false; }
  16190. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16191. // Free existing certificate and key
  16192. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16193. mbedtls_pk_free(&mbed_ctx->own_key);
  16194. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16195. mbedtls_pk_init(&mbed_ctx->own_key);
  16196. // Parse certificate PEM
  16197. int ret = mbedtls_x509_crt_parse(
  16198. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16199. strlen(cert_pem) + 1);
  16200. if (ret != 0) {
  16201. impl::mbedtls_last_error() = ret;
  16202. return false;
  16203. }
  16204. // Parse private key PEM
  16205. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16206. ret = mbedtls_pk_parse_key(
  16207. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16208. strlen(key_pem) + 1,
  16209. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16210. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16211. &mbed_ctx->ctr_drbg);
  16212. #else
  16213. ret = mbedtls_pk_parse_key(
  16214. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16215. strlen(key_pem) + 1,
  16216. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16217. password ? strlen(password) : 0);
  16218. #endif
  16219. if (ret != 0) {
  16220. impl::mbedtls_last_error() = ret;
  16221. return false;
  16222. }
  16223. // Configure SSL to use the new certificate and key
  16224. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16225. &mbed_ctx->own_key);
  16226. if (ret != 0) {
  16227. impl::mbedtls_last_error() = ret;
  16228. return false;
  16229. }
  16230. return true;
  16231. }
  16232. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16233. if (!ctx || !ca_pem) { return false; }
  16234. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16235. // Free existing CA chain
  16236. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16237. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16238. // Parse CA PEM
  16239. int ret = mbedtls_x509_crt_parse(
  16240. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16241. strlen(ca_pem) + 1);
  16242. if (ret != 0) {
  16243. impl::mbedtls_last_error() = ret;
  16244. return false;
  16245. }
  16246. // Update SSL config to use new CA chain
  16247. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16248. return true;
  16249. }
  16250. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16251. if (!ctx) { return false; }
  16252. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16253. impl::get_verify_callback() = std::move(callback);
  16254. mbed_ctx->has_verify_callback =
  16255. static_cast<bool>(impl::get_verify_callback());
  16256. if (mbed_ctx->has_verify_callback) {
  16257. // Set OPTIONAL mode to ensure callback is called even when verification
  16258. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16259. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16260. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16261. nullptr);
  16262. } else {
  16263. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16264. }
  16265. return true;
  16266. }
  16267. inline long get_verify_error(const_session_t session) {
  16268. if (!session) { return -1; }
  16269. auto *msession =
  16270. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16271. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16272. }
  16273. inline std::string verify_error_string(long error_code) {
  16274. if (error_code == 0) { return ""; }
  16275. char buf[256];
  16276. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16277. static_cast<uint32_t>(error_code));
  16278. // Remove trailing newline if present
  16279. std::string result(buf);
  16280. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16281. result.pop_back();
  16282. }
  16283. return result;
  16284. }
  16285. } // namespace tls
  16286. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16287. /*
  16288. * Group 10: TLS abstraction layer - wolfSSL backend
  16289. */
  16290. /*
  16291. * wolfSSL Backend Implementation
  16292. */
  16293. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16294. namespace tls {
  16295. namespace impl {
  16296. // wolfSSL session wrapper
  16297. struct WolfSSLSession {
  16298. WOLFSSL *ssl = nullptr;
  16299. socket_t sock = INVALID_SOCKET;
  16300. std::string hostname; // For client: set via set_sni
  16301. std::string sni_hostname; // For server: received from client via SNI callback
  16302. WolfSSLSession() = default;
  16303. ~WolfSSLSession() {
  16304. if (ssl) { wolfSSL_free(ssl); }
  16305. }
  16306. WolfSSLSession(const WolfSSLSession &) = delete;
  16307. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16308. };
  16309. // Thread-local error code accessor for wolfSSL
  16310. inline uint64_t &wolfssl_last_error() {
  16311. static thread_local uint64_t err = 0;
  16312. return err;
  16313. }
  16314. // Helper to map wolfSSL error to ErrorCode.
  16315. // ssl_error is the value from wolfSSL_get_error().
  16316. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16317. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16318. int &out_errno) {
  16319. switch (ssl_error) {
  16320. case SSL_ERROR_NONE: return ErrorCode::Success;
  16321. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16322. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16323. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16324. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16325. default:
  16326. if (ssl) {
  16327. // wolfSSL stores the low-level error code as a negative value.
  16328. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16329. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16330. if (low_err == DOMAIN_NAME_MISMATCH) {
  16331. return ErrorCode::HostnameMismatch;
  16332. }
  16333. // Check verify result to distinguish cert verification from generic SSL
  16334. // errors.
  16335. long vr = wolfSSL_get_verify_result(ssl);
  16336. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16337. }
  16338. return ErrorCode::Fatal;
  16339. }
  16340. }
  16341. // WolfSSLContext constructor/destructor implementations
  16342. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16343. inline WolfSSLContext::~WolfSSLContext() {
  16344. if (ctx) { wolfSSL_CTX_free(ctx); }
  16345. }
  16346. // Thread-local storage for SNI captured during handshake
  16347. inline std::string &wolfssl_pending_sni() {
  16348. static thread_local std::string sni;
  16349. return sni;
  16350. }
  16351. // SNI callback for wolfSSL server to capture client's SNI hostname
  16352. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16353. (void)ret;
  16354. (void)exArg;
  16355. void *name_data = nullptr;
  16356. unsigned short name_len =
  16357. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16358. if (name_data && name_len > 0) {
  16359. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16360. name_len);
  16361. } else {
  16362. wolfssl_pending_sni().clear();
  16363. }
  16364. return 0; // Continue regardless
  16365. }
  16366. // wolfSSL verify callback wrapper
  16367. inline int wolfssl_verify_callback(int preverify_ok,
  16368. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16369. auto &callback = get_verify_callback();
  16370. if (!callback) { return preverify_ok; }
  16371. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16372. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16373. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16374. // Get the WOLFSSL object from the X509_STORE_CTX
  16375. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16376. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16377. VerifyContext verify_ctx;
  16378. verify_ctx.session = static_cast<session_t>(ssl);
  16379. verify_ctx.cert = static_cast<cert_t>(cert);
  16380. verify_ctx.depth = depth;
  16381. verify_ctx.preverify_ok = (preverify_ok != 0);
  16382. verify_ctx.error_code = static_cast<long>(err);
  16383. if (err != 0) {
  16384. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16385. } else {
  16386. verify_ctx.error_string = nullptr;
  16387. }
  16388. bool accepted = callback(verify_ctx);
  16389. return accepted ? 1 : 0;
  16390. }
  16391. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16392. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16393. wolfSSL_CTX_set_default_passwd_cb(
  16394. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16395. auto *pwd = static_cast<const char *>(userdata);
  16396. if (!pwd) return 0;
  16397. auto len = static_cast<int>(strlen(pwd));
  16398. if (len > size) len = size;
  16399. memcpy(buf, pwd, static_cast<size_t>(len));
  16400. return len;
  16401. });
  16402. }
  16403. } // namespace impl
  16404. inline ctx_t create_client_context() {
  16405. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16406. if (!ctx) { return nullptr; }
  16407. ctx->is_server = false;
  16408. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16409. if (!method) {
  16410. delete ctx;
  16411. return nullptr;
  16412. }
  16413. ctx->ctx = wolfSSL_CTX_new(method);
  16414. if (!ctx->ctx) {
  16415. delete ctx;
  16416. return nullptr;
  16417. }
  16418. // Default: verify peer certificate
  16419. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16420. return static_cast<ctx_t>(ctx);
  16421. }
  16422. inline ctx_t create_server_context() {
  16423. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16424. if (!ctx) { return nullptr; }
  16425. ctx->is_server = true;
  16426. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16427. if (!method) {
  16428. delete ctx;
  16429. return nullptr;
  16430. }
  16431. ctx->ctx = wolfSSL_CTX_new(method);
  16432. if (!ctx->ctx) {
  16433. delete ctx;
  16434. return nullptr;
  16435. }
  16436. // Default: don't verify client
  16437. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16438. // Enable SNI on server
  16439. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16440. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16441. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16442. return static_cast<ctx_t>(ctx);
  16443. }
  16444. inline void free_context(ctx_t ctx) {
  16445. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16446. }
  16447. inline bool set_min_version(ctx_t ctx, Version version) {
  16448. if (!ctx) { return false; }
  16449. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16450. int min_ver = WOLFSSL_TLSV1_2;
  16451. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16452. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16453. }
  16454. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16455. if (!ctx || !pem) { return false; }
  16456. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16457. int ret = wolfSSL_CTX_load_verify_buffer(
  16458. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16459. static_cast<long>(len), SSL_FILETYPE_PEM);
  16460. if (ret != SSL_SUCCESS) {
  16461. impl::wolfssl_last_error() =
  16462. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16463. return false;
  16464. }
  16465. wctx->ca_pem_data_.append(pem, len);
  16466. return true;
  16467. }
  16468. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16469. if (!ctx || !file_path) { return false; }
  16470. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16471. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16472. if (ret != SSL_SUCCESS) {
  16473. impl::wolfssl_last_error() =
  16474. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16475. return false;
  16476. }
  16477. return true;
  16478. }
  16479. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16480. if (!ctx || !dir_path) { return false; }
  16481. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16482. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16483. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16484. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16485. // immediately. Return true even on failure since the CA file may have
  16486. // already been loaded, matching OpenSSL's lenient behavior.
  16487. (void)ret;
  16488. return true;
  16489. }
  16490. inline bool load_system_certs(ctx_t ctx) {
  16491. if (!ctx) { return false; }
  16492. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16493. bool loaded = false;
  16494. #ifdef _WIN32
  16495. loaded = impl::enumerate_windows_system_certs(
  16496. [&](const unsigned char *data, size_t len) {
  16497. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16498. static_cast<long>(len),
  16499. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16500. });
  16501. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16502. loaded = impl::enumerate_macos_keychain_certs(
  16503. [&](const unsigned char *data, size_t len) {
  16504. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16505. static_cast<long>(len),
  16506. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16507. });
  16508. #else
  16509. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16510. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16511. SSL_SUCCESS) {
  16512. loaded = true;
  16513. break;
  16514. }
  16515. }
  16516. if (!loaded) {
  16517. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16518. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16519. SSL_SUCCESS) {
  16520. loaded = true;
  16521. break;
  16522. }
  16523. }
  16524. }
  16525. #endif
  16526. return loaded;
  16527. }
  16528. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16529. const char *password) {
  16530. if (!ctx || !cert || !key) { return false; }
  16531. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16532. // Load certificate
  16533. int ret = wolfSSL_CTX_use_certificate_buffer(
  16534. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16535. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16536. if (ret != SSL_SUCCESS) {
  16537. impl::wolfssl_last_error() =
  16538. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16539. return false;
  16540. }
  16541. // Set password callback if password is provided
  16542. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16543. // Load private key
  16544. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16545. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16546. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16547. if (ret != SSL_SUCCESS) {
  16548. impl::wolfssl_last_error() =
  16549. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16550. return false;
  16551. }
  16552. // Verify that the certificate and private key match
  16553. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16554. }
  16555. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16556. const char *key_path, const char *password) {
  16557. if (!ctx || !cert_path || !key_path) { return false; }
  16558. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16559. // Load certificate file
  16560. int ret =
  16561. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16562. if (ret != SSL_SUCCESS) {
  16563. impl::wolfssl_last_error() =
  16564. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16565. return false;
  16566. }
  16567. // Set password callback if password is provided
  16568. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16569. // Load private key file
  16570. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16571. if (ret != SSL_SUCCESS) {
  16572. impl::wolfssl_last_error() =
  16573. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16574. return false;
  16575. }
  16576. // Verify that the certificate and private key match
  16577. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16578. }
  16579. inline void set_verify_client(ctx_t ctx, bool require) {
  16580. if (!ctx) { return; }
  16581. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16582. wctx->verify_client = require;
  16583. if (require) {
  16584. wolfSSL_CTX_set_verify(
  16585. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16586. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16587. } else {
  16588. if (wctx->has_verify_callback) {
  16589. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16590. impl::wolfssl_verify_callback);
  16591. } else {
  16592. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16593. }
  16594. }
  16595. }
  16596. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16597. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16598. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16599. auto session = new (std::nothrow) impl::WolfSSLSession();
  16600. if (!session) { return nullptr; }
  16601. session->sock = sock;
  16602. session->ssl = wolfSSL_new(wctx->ctx);
  16603. if (!session->ssl) {
  16604. impl::wolfssl_last_error() =
  16605. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16606. delete session;
  16607. return nullptr;
  16608. }
  16609. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16610. return static_cast<session_t>(session);
  16611. }
  16612. inline void free_session(session_t session) {
  16613. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16614. }
  16615. inline bool set_sni(session_t session, const char *hostname) {
  16616. if (!session || !hostname) { return false; }
  16617. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16618. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16619. static_cast<word16>(strlen(hostname)));
  16620. if (ret != WOLFSSL_SUCCESS) {
  16621. impl::wolfssl_last_error() =
  16622. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16623. return false;
  16624. }
  16625. // Also set hostname for verification
  16626. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16627. wsession->hostname = hostname;
  16628. return true;
  16629. }
  16630. inline bool set_hostname(session_t session, const char *hostname) {
  16631. // In wolfSSL, set_hostname also sets up hostname verification
  16632. return set_sni(session, hostname);
  16633. }
  16634. inline TlsError connect(session_t session) {
  16635. TlsError err;
  16636. if (!session) {
  16637. err.code = ErrorCode::Fatal;
  16638. return err;
  16639. }
  16640. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16641. int ret = wolfSSL_connect(wsession->ssl);
  16642. if (ret == SSL_SUCCESS) {
  16643. err.code = ErrorCode::Success;
  16644. } else {
  16645. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16646. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16647. err.backend_code = static_cast<uint64_t>(ssl_error);
  16648. impl::wolfssl_last_error() = err.backend_code;
  16649. }
  16650. return err;
  16651. }
  16652. inline TlsError accept(session_t session) {
  16653. TlsError err;
  16654. if (!session) {
  16655. err.code = ErrorCode::Fatal;
  16656. return err;
  16657. }
  16658. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16659. int ret = wolfSSL_accept(wsession->ssl);
  16660. if (ret == SSL_SUCCESS) {
  16661. err.code = ErrorCode::Success;
  16662. // Capture SNI from thread-local storage after successful handshake
  16663. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16664. impl::wolfssl_pending_sni().clear();
  16665. } else {
  16666. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16667. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16668. err.backend_code = static_cast<uint64_t>(ssl_error);
  16669. impl::wolfssl_last_error() = err.backend_code;
  16670. }
  16671. return err;
  16672. }
  16673. inline bool connect_nonblocking(session_t session, socket_t sock,
  16674. time_t timeout_sec, time_t timeout_usec,
  16675. TlsError *err) {
  16676. if (!session) {
  16677. if (err) { err->code = ErrorCode::Fatal; }
  16678. return false;
  16679. }
  16680. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16681. // Set socket to non-blocking mode
  16682. detail::set_nonblocking(sock, true);
  16683. auto cleanup =
  16684. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16685. int ret;
  16686. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16687. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16688. if (ssl_error == SSL_ERROR_WANT_READ) {
  16689. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16690. continue;
  16691. }
  16692. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16693. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16694. continue;
  16695. }
  16696. }
  16697. // Error or timeout
  16698. if (err) {
  16699. err->code =
  16700. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16701. err->backend_code = static_cast<uint64_t>(ssl_error);
  16702. }
  16703. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16704. return false;
  16705. }
  16706. if (err) { err->code = ErrorCode::Success; }
  16707. return true;
  16708. }
  16709. inline bool accept_nonblocking(session_t session, socket_t sock,
  16710. time_t timeout_sec, time_t timeout_usec,
  16711. TlsError *err) {
  16712. if (!session) {
  16713. if (err) { err->code = ErrorCode::Fatal; }
  16714. return false;
  16715. }
  16716. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16717. // Set socket to non-blocking mode
  16718. detail::set_nonblocking(sock, true);
  16719. auto cleanup =
  16720. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16721. int ret;
  16722. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16723. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16724. if (ssl_error == SSL_ERROR_WANT_READ) {
  16725. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16726. continue;
  16727. }
  16728. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16729. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16730. continue;
  16731. }
  16732. }
  16733. // Error or timeout
  16734. if (err) {
  16735. err->code =
  16736. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16737. err->backend_code = static_cast<uint64_t>(ssl_error);
  16738. }
  16739. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16740. return false;
  16741. }
  16742. if (err) { err->code = ErrorCode::Success; }
  16743. // Capture SNI from thread-local storage after successful handshake
  16744. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16745. impl::wolfssl_pending_sni().clear();
  16746. return true;
  16747. }
  16748. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16749. if (!session || !buf) {
  16750. err.code = ErrorCode::Fatal;
  16751. return -1;
  16752. }
  16753. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16754. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16755. if (ret > 0) {
  16756. err.code = ErrorCode::Success;
  16757. return static_cast<ssize_t>(ret);
  16758. }
  16759. if (ret == 0) {
  16760. err.code = ErrorCode::PeerClosed;
  16761. return 0;
  16762. }
  16763. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16764. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16765. err.backend_code = static_cast<uint64_t>(ssl_error);
  16766. impl::wolfssl_last_error() = err.backend_code;
  16767. return -1;
  16768. }
  16769. inline ssize_t write(session_t session, const void *buf, size_t len,
  16770. TlsError &err) {
  16771. if (!session || !buf) {
  16772. err.code = ErrorCode::Fatal;
  16773. return -1;
  16774. }
  16775. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16776. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16777. if (ret > 0) {
  16778. err.code = ErrorCode::Success;
  16779. return static_cast<ssize_t>(ret);
  16780. }
  16781. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16782. // Treat this as an error (return -1) so callers don't spin in a
  16783. // write loop adding zero to the offset.
  16784. if (ret == 0) {
  16785. err.code = ErrorCode::PeerClosed;
  16786. return -1;
  16787. }
  16788. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16789. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16790. err.backend_code = static_cast<uint64_t>(ssl_error);
  16791. impl::wolfssl_last_error() = err.backend_code;
  16792. return -1;
  16793. }
  16794. inline int pending(const_session_t session) {
  16795. if (!session) { return 0; }
  16796. auto wsession =
  16797. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16798. return wolfSSL_pending(wsession->ssl);
  16799. }
  16800. inline void shutdown(session_t session, bool graceful) {
  16801. if (!session) { return; }
  16802. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16803. if (graceful) {
  16804. int ret;
  16805. int attempts = 0;
  16806. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16807. attempts < 3) {
  16808. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16809. if (ssl_error != SSL_ERROR_WANT_READ &&
  16810. ssl_error != SSL_ERROR_WANT_WRITE) {
  16811. break;
  16812. }
  16813. attempts++;
  16814. }
  16815. } else {
  16816. wolfSSL_shutdown(wsession->ssl);
  16817. }
  16818. }
  16819. inline bool is_peer_closed(session_t session, socket_t sock) {
  16820. if (!session || sock == INVALID_SOCKET) { return true; }
  16821. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16822. // Check if there's already decrypted data available
  16823. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16824. // Set socket to non-blocking to avoid blocking on read
  16825. detail::set_nonblocking(sock, true);
  16826. auto cleanup =
  16827. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16828. // Peek 1 byte to check connection status without consuming data
  16829. unsigned char buf;
  16830. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16831. // If we got data or WANT_READ (would block), connection is alive
  16832. if (ret > 0) { return false; }
  16833. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16834. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16835. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16836. ret == 0;
  16837. }
  16838. inline cert_t get_peer_cert(const_session_t session) {
  16839. if (!session) { return nullptr; }
  16840. auto wsession =
  16841. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16842. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16843. return static_cast<cert_t>(cert);
  16844. }
  16845. inline void free_cert(cert_t cert) {
  16846. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16847. }
  16848. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16849. if (!cert || !hostname) { return false; }
  16850. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16851. std::string host_str(hostname);
  16852. // Check if hostname is an IP address (IPv4 or IPv6)
  16853. unsigned char ip_bytes[16];
  16854. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16855. auto is_ip = ip_len > 0;
  16856. // Check Subject Alternative Names
  16857. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16858. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16859. if (san_names) {
  16860. int san_count = wolfSSL_sk_num(san_names);
  16861. for (int i = 0; i < san_count; i++) {
  16862. auto *names =
  16863. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16864. if (!names) continue;
  16865. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16866. // DNS name
  16867. unsigned char *dns_name = nullptr;
  16868. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16869. if (dns_name && dns_len > 0) {
  16870. std::string san_name(reinterpret_cast<char *>(dns_name),
  16871. static_cast<size_t>(dns_len));
  16872. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16873. if (detail::match_hostname(san_name, host_str)) {
  16874. wolfSSL_sk_free(san_names);
  16875. return true;
  16876. }
  16877. }
  16878. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16879. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16880. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16881. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16882. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16883. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16884. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16885. wolfSSL_sk_free(san_names);
  16886. return true;
  16887. }
  16888. }
  16889. }
  16890. wolfSSL_sk_free(san_names);
  16891. }
  16892. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16893. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16894. // the OpenSSL backend's X509_check_ip behaves the same way).
  16895. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16896. if (subject) {
  16897. char cn[256] = {};
  16898. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16899. sizeof(cn));
  16900. if (cn_len > 0) {
  16901. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16902. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16903. }
  16904. }
  16905. return false;
  16906. }
  16907. inline uint64_t hostname_mismatch_code() {
  16908. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16909. }
  16910. inline long get_verify_result(const_session_t session) {
  16911. if (!session) { return -1; }
  16912. auto wsession =
  16913. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16914. long result = wolfSSL_get_verify_result(wsession->ssl);
  16915. return result;
  16916. }
  16917. inline std::string get_cert_subject_cn(cert_t cert) {
  16918. if (!cert) return "";
  16919. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16920. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16921. if (!subject) return "";
  16922. char cn[256] = {};
  16923. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16924. sizeof(cn));
  16925. if (cn_len <= 0) return "";
  16926. return std::string(cn, static_cast<size_t>(cn_len));
  16927. }
  16928. inline std::string get_cert_issuer_name(cert_t cert) {
  16929. if (!cert) return "";
  16930. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16931. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16932. if (!issuer) return "";
  16933. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16934. if (!name_str) return "";
  16935. std::string result(name_str);
  16936. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16937. return result;
  16938. }
  16939. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16940. sans.clear();
  16941. if (!cert) return false;
  16942. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16943. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16944. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16945. if (!san_names) return true; // No SANs is not an error
  16946. int count = wolfSSL_sk_num(san_names);
  16947. for (int i = 0; i < count; i++) {
  16948. auto *name =
  16949. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16950. if (!name) continue;
  16951. SanEntry entry;
  16952. switch (name->type) {
  16953. case WOLFSSL_GEN_DNS: {
  16954. entry.type = SanType::DNS;
  16955. unsigned char *dns_name = nullptr;
  16956. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16957. if (dns_name && dns_len > 0) {
  16958. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16959. static_cast<size_t>(dns_len));
  16960. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16961. }
  16962. break;
  16963. }
  16964. case WOLFSSL_GEN_IPADD: {
  16965. entry.type = SanType::IP;
  16966. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16967. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16968. if (ip_data && ip_len == 4) {
  16969. char buf[16];
  16970. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16971. ip_data[2], ip_data[3]);
  16972. entry.value = buf;
  16973. } else if (ip_data && ip_len == 16) {
  16974. char buf[64];
  16975. snprintf(buf, sizeof(buf),
  16976. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16977. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16978. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16979. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16980. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16981. ip_data[14], ip_data[15]);
  16982. entry.value = buf;
  16983. }
  16984. break;
  16985. }
  16986. case WOLFSSL_GEN_EMAIL:
  16987. entry.type = SanType::EMAIL;
  16988. {
  16989. unsigned char *email = nullptr;
  16990. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16991. if (email && email_len > 0) {
  16992. entry.value = std::string(reinterpret_cast<char *>(email),
  16993. static_cast<size_t>(email_len));
  16994. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16995. }
  16996. }
  16997. break;
  16998. case WOLFSSL_GEN_URI:
  16999. entry.type = SanType::URI;
  17000. {
  17001. unsigned char *uri = nullptr;
  17002. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  17003. &uri, name->d.uniformResourceIdentifier);
  17004. if (uri && uri_len > 0) {
  17005. entry.value = std::string(reinterpret_cast<char *>(uri),
  17006. static_cast<size_t>(uri_len));
  17007. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  17008. }
  17009. }
  17010. break;
  17011. default: entry.type = SanType::OTHER; break;
  17012. }
  17013. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17014. }
  17015. wolfSSL_sk_free(san_names);
  17016. return true;
  17017. }
  17018. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17019. time_t &not_after) {
  17020. if (!cert) return false;
  17021. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17022. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  17023. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  17024. if (!nb || !na) return false;
  17025. // wolfSSL_ASN1_TIME_to_tm is available
  17026. struct tm tm_nb = {}, tm_na = {};
  17027. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  17028. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  17029. #ifdef _WIN32
  17030. not_before = _mkgmtime(&tm_nb);
  17031. not_after = _mkgmtime(&tm_na);
  17032. #else
  17033. not_before = timegm(&tm_nb);
  17034. not_after = timegm(&tm_na);
  17035. #endif
  17036. return true;
  17037. }
  17038. inline std::string get_cert_serial(cert_t cert) {
  17039. if (!cert) return "";
  17040. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17041. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  17042. if (!serial_asn1) return "";
  17043. // Get the serial number data
  17044. int len = serial_asn1->length;
  17045. unsigned char *data = serial_asn1->data;
  17046. if (!data || len <= 0) return "";
  17047. std::string result;
  17048. result.reserve(static_cast<size_t>(len) * 2);
  17049. for (int i = 0; i < len; i++) {
  17050. char hex[3];
  17051. snprintf(hex, sizeof(hex), "%02X", data[i]);
  17052. result += hex;
  17053. }
  17054. return result;
  17055. }
  17056. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17057. if (!cert) return false;
  17058. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17059. int der_len = 0;
  17060. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17061. if (!der_data || der_len <= 0) return false;
  17062. der.assign(der_data, der_data + der_len);
  17063. return true;
  17064. }
  17065. inline const char *get_sni(const_session_t session) {
  17066. if (!session) return nullptr;
  17067. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17068. // For server: return SNI received from client during handshake
  17069. if (!wsession->sni_hostname.empty()) {
  17070. return wsession->sni_hostname.c_str();
  17071. }
  17072. // For client: return the hostname set via set_sni
  17073. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17074. return nullptr;
  17075. }
  17076. inline uint64_t peek_error() {
  17077. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17078. }
  17079. inline uint64_t get_error() {
  17080. uint64_t err = impl::wolfssl_last_error();
  17081. impl::wolfssl_last_error() = 0;
  17082. return err;
  17083. }
  17084. inline std::string error_string(uint64_t code) {
  17085. char buf[256];
  17086. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17087. return std::string(buf);
  17088. }
  17089. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17090. if (!pem || len == 0) { return nullptr; }
  17091. // Validate by attempting to load into a temporary ctx
  17092. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17093. if (!tmp_ctx) { return nullptr; }
  17094. int ret = wolfSSL_CTX_load_verify_buffer(
  17095. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17096. static_cast<long>(len), SSL_FILETYPE_PEM);
  17097. wolfSSL_CTX_free(tmp_ctx);
  17098. if (ret != SSL_SUCCESS) { return nullptr; }
  17099. return static_cast<ca_store_t>(
  17100. new impl::WolfSSLCAStore{std::string(pem, len)});
  17101. }
  17102. inline void free_ca_store(ca_store_t store) {
  17103. delete static_cast<impl::WolfSSLCAStore *>(store);
  17104. }
  17105. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17106. if (!ctx || !store) { return false; }
  17107. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17108. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17109. int ret = wolfSSL_CTX_load_verify_buffer(
  17110. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17111. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17112. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17113. // This function takes ownership of the store; the PEM data was copied into
  17114. // the context, so release the source
  17115. free_ca_store(store);
  17116. return ret == SSL_SUCCESS;
  17117. }
  17118. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17119. certs.clear();
  17120. if (!ctx) { return 0; }
  17121. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17122. if (wctx->ca_pem_data_.empty()) { return 0; }
  17123. const std::string &pem = wctx->ca_pem_data_;
  17124. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17125. const std::string end_marker = "-----END CERTIFICATE-----";
  17126. size_t pos = 0;
  17127. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17128. size_t end_pos = pem.find(end_marker, pos);
  17129. if (end_pos == std::string::npos) { break; }
  17130. end_pos += end_marker.size();
  17131. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17132. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17133. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17134. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17135. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17136. pos = end_pos;
  17137. }
  17138. return certs.size();
  17139. }
  17140. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17141. std::vector<std::string> names;
  17142. if (!ctx) { return names; }
  17143. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17144. if (wctx->ca_pem_data_.empty()) { return names; }
  17145. const std::string &pem = wctx->ca_pem_data_;
  17146. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17147. const std::string end_marker = "-----END CERTIFICATE-----";
  17148. size_t pos = 0;
  17149. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17150. size_t end_pos = pem.find(end_marker, pos);
  17151. if (end_pos == std::string::npos) { break; }
  17152. end_pos += end_marker.size();
  17153. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17154. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17155. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17156. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17157. if (x509) {
  17158. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17159. if (subject) {
  17160. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17161. if (name_str) {
  17162. names.push_back(name_str);
  17163. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17164. }
  17165. }
  17166. wolfSSL_X509_free(x509);
  17167. }
  17168. pos = end_pos;
  17169. }
  17170. return names;
  17171. }
  17172. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17173. const char *key_pem, const char *password) {
  17174. if (!ctx || !cert_pem || !key_pem) { return false; }
  17175. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17176. // Load new certificate
  17177. int ret = wolfSSL_CTX_use_certificate_buffer(
  17178. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17179. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17180. if (ret != SSL_SUCCESS) {
  17181. impl::wolfssl_last_error() =
  17182. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17183. return false;
  17184. }
  17185. // Set password if provided
  17186. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17187. // Load new private key
  17188. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17189. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17190. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17191. if (ret != SSL_SUCCESS) {
  17192. impl::wolfssl_last_error() =
  17193. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17194. return false;
  17195. }
  17196. return true;
  17197. }
  17198. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17199. if (!ctx || !ca_pem) { return false; }
  17200. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17201. int ret = wolfSSL_CTX_load_verify_buffer(
  17202. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17203. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17204. if (ret != SSL_SUCCESS) {
  17205. impl::wolfssl_last_error() =
  17206. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17207. return false;
  17208. }
  17209. return true;
  17210. }
  17211. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17212. if (!ctx) { return false; }
  17213. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17214. impl::get_verify_callback() = std::move(callback);
  17215. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17216. if (wctx->has_verify_callback) {
  17217. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17218. impl::wolfssl_verify_callback);
  17219. } else {
  17220. wolfSSL_CTX_set_verify(
  17221. wctx->ctx,
  17222. wctx->verify_client
  17223. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17224. : SSL_VERIFY_NONE,
  17225. nullptr);
  17226. }
  17227. return true;
  17228. }
  17229. inline long get_verify_error(const_session_t session) {
  17230. if (!session) { return -1; }
  17231. auto *wsession =
  17232. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17233. return wolfSSL_get_verify_result(wsession->ssl);
  17234. }
  17235. inline std::string verify_error_string(long error_code) {
  17236. if (error_code == 0) { return ""; }
  17237. const char *str =
  17238. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17239. return str ? std::string(str) : std::string();
  17240. }
  17241. } // namespace tls
  17242. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17243. // WebSocket implementation
  17244. namespace ws {
  17245. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17246. bool fin) {
  17247. std::lock_guard<std::mutex> lock(write_mutex_);
  17248. if (closed_) { return false; }
  17249. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17250. }
  17251. inline ReadResult WebSocket::read(std::string &msg) {
  17252. while (!closed_) {
  17253. Opcode opcode;
  17254. std::string payload;
  17255. bool fin;
  17256. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17257. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17258. closed_ = true;
  17259. return Fail;
  17260. }
  17261. switch (opcode) {
  17262. case Opcode::Ping: {
  17263. std::lock_guard<std::mutex> lock(write_mutex_);
  17264. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17265. payload.size(), true, !is_server_);
  17266. continue;
  17267. }
  17268. case Opcode::Pong: {
  17269. std::lock_guard<std::mutex> lock(ping_mutex_);
  17270. unacked_pings_ = 0;
  17271. continue;
  17272. }
  17273. case Opcode::Close: {
  17274. if (!closed_.exchange(true)) {
  17275. // Echo close frame back
  17276. std::lock_guard<std::mutex> lock(write_mutex_);
  17277. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17278. payload.size(), true, !is_server_);
  17279. }
  17280. return Fail;
  17281. }
  17282. case Opcode::Text:
  17283. case Opcode::Binary: {
  17284. auto result = opcode == Opcode::Text ? Text : Binary;
  17285. msg = std::move(payload);
  17286. // Handle fragmentation
  17287. if (!fin) {
  17288. while (true) {
  17289. Opcode cont_opcode;
  17290. std::string cont_payload;
  17291. bool cont_fin;
  17292. if (!impl::read_websocket_frame(
  17293. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17294. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17295. closed_ = true;
  17296. return Fail;
  17297. }
  17298. if (cont_opcode == Opcode::Ping) {
  17299. std::lock_guard<std::mutex> lock(write_mutex_);
  17300. detail::write_websocket_frame(
  17301. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17302. true, !is_server_);
  17303. continue;
  17304. }
  17305. if (cont_opcode == Opcode::Pong) {
  17306. std::lock_guard<std::mutex> lock(ping_mutex_);
  17307. unacked_pings_ = 0;
  17308. continue;
  17309. }
  17310. if (cont_opcode == Opcode::Close) {
  17311. if (!closed_.exchange(true)) {
  17312. std::lock_guard<std::mutex> lock(write_mutex_);
  17313. detail::write_websocket_frame(
  17314. strm_, Opcode::Close, cont_payload.data(),
  17315. cont_payload.size(), true, !is_server_);
  17316. }
  17317. return Fail;
  17318. }
  17319. // RFC 6455: continuation frames must use opcode 0x0
  17320. if (cont_opcode != Opcode::Continuation) {
  17321. closed_ = true;
  17322. return Fail;
  17323. }
  17324. msg += cont_payload;
  17325. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17326. closed_ = true;
  17327. return Fail;
  17328. }
  17329. if (cont_fin) { break; }
  17330. }
  17331. }
  17332. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17333. if (result == Text && !impl::is_valid_utf8(msg)) {
  17334. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17335. return Fail;
  17336. }
  17337. return result;
  17338. }
  17339. default: closed_ = true; return Fail;
  17340. }
  17341. }
  17342. return Fail;
  17343. }
  17344. inline bool WebSocket::send(const std::string &data) {
  17345. return send_frame(Opcode::Text, data.data(), data.size());
  17346. }
  17347. inline bool WebSocket::send(const char *data, size_t len) {
  17348. return send_frame(Opcode::Binary, data, len);
  17349. }
  17350. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17351. if (closed_.exchange(true)) { return; }
  17352. ping_cv_.notify_all();
  17353. std::string payload;
  17354. auto code = static_cast<uint16_t>(status);
  17355. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17356. payload.push_back(static_cast<char>(code & 0xFF));
  17357. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17358. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17359. payload += reason.substr(0, 123);
  17360. {
  17361. std::lock_guard<std::mutex> lock(write_mutex_);
  17362. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17363. payload.size(), true, !is_server_);
  17364. }
  17365. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17366. // Close response before closing the TCP connection. Use a short timeout to
  17367. // avoid hanging if the peer doesn't respond.
  17368. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17369. Opcode op;
  17370. std::string resp;
  17371. bool fin;
  17372. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17373. if (op == Opcode::Close) { break; }
  17374. }
  17375. }
  17376. inline WebSocket::~WebSocket() {
  17377. {
  17378. std::lock_guard<std::mutex> lock(ping_mutex_);
  17379. closed_ = true;
  17380. }
  17381. ping_cv_.notify_all();
  17382. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17383. }
  17384. inline void WebSocket::start_heartbeat() {
  17385. if (ping_interval_sec_ == 0) { return; }
  17386. ping_thread_ = std::thread([this]() {
  17387. std::unique_lock<std::mutex> lock(ping_mutex_);
  17388. while (!closed_) {
  17389. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17390. if (closed_) { break; }
  17391. // If the peer has failed to respond to the previous pings, give up.
  17392. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17393. // opt-in liveness check controlled by max_missed_pongs_.
  17394. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17395. lock.unlock();
  17396. close(CloseStatus::GoingAway, "pong timeout");
  17397. return;
  17398. }
  17399. lock.unlock();
  17400. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17401. lock.lock();
  17402. closed_ = true;
  17403. break;
  17404. }
  17405. lock.lock();
  17406. unacked_pings_++;
  17407. }
  17408. });
  17409. }
  17410. inline const Request &WebSocket::request() const { return req_; }
  17411. inline bool WebSocket::is_open() const { return !closed_; }
  17412. // WebSocketClient implementation
  17413. inline WebSocketClient::WebSocketClient(
  17414. const std::string &scheme_host_port_path, const Headers &headers)
  17415. : headers_(headers) {
  17416. detail::UrlComponents uc;
  17417. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17418. !uc.host.empty() && !uc.path.empty()) {
  17419. auto &scheme = uc.scheme;
  17420. #ifdef CPPHTTPLIB_SSL_ENABLED
  17421. if (scheme != "ws" && scheme != "wss") {
  17422. #else
  17423. if (scheme != "ws") {
  17424. #endif
  17425. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17426. std::string msg = "'" + scheme + "' scheme is not supported.";
  17427. throw std::invalid_argument(msg);
  17428. #endif
  17429. return;
  17430. }
  17431. auto is_ssl = scheme == "wss";
  17432. host_ = std::move(uc.host);
  17433. port_ = is_ssl ? 443 : 80;
  17434. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17435. path_ = std::move(uc.path);
  17436. if (!uc.query.empty()) { path_ += uc.query; }
  17437. #ifdef CPPHTTPLIB_SSL_ENABLED
  17438. is_ssl_ = is_ssl;
  17439. if (is_ssl_) {
  17440. // The context lives as long as the client so that CA configuration
  17441. // survives reconnects; sessions are created per connection.
  17442. tls_ctx_ = tls::create_client_context();
  17443. if (!tls_ctx_) { return; }
  17444. }
  17445. #else
  17446. if (is_ssl) { return; }
  17447. #endif
  17448. is_valid_ = true;
  17449. }
  17450. }
  17451. inline WebSocketClient::~WebSocketClient() {
  17452. shutdown_and_close();
  17453. #ifdef CPPHTTPLIB_SSL_ENABLED
  17454. if (tls_ctx_) {
  17455. tls::free_context(tls_ctx_);
  17456. tls_ctx_ = nullptr;
  17457. }
  17458. #endif
  17459. }
  17460. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17461. inline void WebSocketClient::shutdown_and_close() {
  17462. // Send the close frame while the TLS session is still alive: ws_ holds an
  17463. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  17464. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  17465. if (ws_ && ws_->is_open()) { ws_->close(); }
  17466. ws_.reset();
  17467. #ifdef CPPHTTPLIB_SSL_ENABLED
  17468. if (is_ssl_) {
  17469. if (tls_session_) {
  17470. tls::shutdown(tls_session_, true);
  17471. tls::free_session(tls_session_);
  17472. tls_session_ = nullptr;
  17473. }
  17474. }
  17475. #endif
  17476. if (sock_ != INVALID_SOCKET) {
  17477. detail::shutdown_socket(sock_);
  17478. detail::close_socket(sock_);
  17479. sock_ = INVALID_SOCKET;
  17480. }
  17481. }
  17482. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17483. #ifdef CPPHTTPLIB_SSL_ENABLED
  17484. if (is_ssl_) {
  17485. if (server_certificate_verification_ && !certs_loaded_) {
  17486. uint64_t backend_error = 0;
  17487. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17488. custom_ca_loaded_, system_ca_mode_,
  17489. backend_error);
  17490. certs_loaded_ = true;
  17491. }
  17492. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17493. server_certificate_verification_,
  17494. read_timeout_sec_,
  17495. read_timeout_usec_)) {
  17496. return false;
  17497. }
  17498. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17499. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17500. write_timeout_sec_, write_timeout_usec_));
  17501. return true;
  17502. }
  17503. #endif
  17504. strm = std::unique_ptr<Stream>(
  17505. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17506. write_timeout_sec_, write_timeout_usec_));
  17507. return true;
  17508. }
  17509. inline bool WebSocketClient::connect() {
  17510. if (!is_valid_) { return false; }
  17511. shutdown_and_close();
  17512. // Check is custom IP specified for host_
  17513. std::string ip;
  17514. auto it = addr_map_.find(host_);
  17515. if (it != addr_map_.end()) { ip = it->second; }
  17516. Error error;
  17517. sock_ = detail::create_client_socket(
  17518. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17519. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17520. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17521. write_timeout_usec_, interface_, error);
  17522. if (sock_ == INVALID_SOCKET) { return false; }
  17523. std::unique_ptr<Stream> strm;
  17524. if (!create_stream(strm)) {
  17525. shutdown_and_close();
  17526. return false;
  17527. }
  17528. #ifdef CPPHTTPLIB_SSL_ENABLED
  17529. auto is_ssl = is_ssl_;
  17530. #else
  17531. auto is_ssl = false;
  17532. #endif
  17533. std::string selected_subprotocol;
  17534. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17535. headers_, selected_subprotocol)) {
  17536. shutdown_and_close();
  17537. return false;
  17538. }
  17539. subprotocol_ = std::move(selected_subprotocol);
  17540. Request req;
  17541. req.method = "GET";
  17542. req.path = path_;
  17543. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17544. websocket_ping_interval_sec_,
  17545. websocket_max_missed_pongs_));
  17546. return true;
  17547. }
  17548. inline ReadResult WebSocketClient::read(std::string &msg) {
  17549. if (!ws_) { return Fail; }
  17550. return ws_->read(msg);
  17551. }
  17552. inline bool WebSocketClient::send(const std::string &data) {
  17553. if (!ws_) { return false; }
  17554. return ws_->send(data);
  17555. }
  17556. inline bool WebSocketClient::send(const char *data, size_t len) {
  17557. if (!ws_) { return false; }
  17558. return ws_->send(data, len);
  17559. }
  17560. inline void WebSocketClient::close(CloseStatus status,
  17561. const std::string &reason) {
  17562. if (ws_) { ws_->close(status, reason); }
  17563. }
  17564. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17565. inline const std::string &WebSocketClient::subprotocol() const {
  17566. return subprotocol_;
  17567. }
  17568. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17569. read_timeout_sec_ = sec;
  17570. read_timeout_usec_ = usec;
  17571. }
  17572. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17573. write_timeout_sec_ = sec;
  17574. write_timeout_usec_ = usec;
  17575. }
  17576. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17577. websocket_ping_interval_sec_ = sec;
  17578. }
  17579. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17580. websocket_max_missed_pongs_ = count;
  17581. }
  17582. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17583. inline void WebSocketClient::set_address_family(int family) {
  17584. address_family_ = family;
  17585. }
  17586. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17587. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17588. socket_options_ = std::move(socket_options);
  17589. }
  17590. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17591. connection_timeout_sec_ = sec;
  17592. connection_timeout_usec_ = usec;
  17593. }
  17594. inline void WebSocketClient::set_interface(const std::string &intf) {
  17595. interface_ = intf;
  17596. }
  17597. inline void WebSocketClient::set_hostname_addr_map(
  17598. std::map<std::string, std::string> addr_map) {
  17599. addr_map_ = std::move(addr_map);
  17600. }
  17601. #ifdef CPPHTTPLIB_SSL_ENABLED
  17602. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17603. ca_cert_file_path_ = path;
  17604. }
  17605. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17606. if (store && tls_ctx_) {
  17607. // set_ca_store takes ownership of store
  17608. tls::set_ca_store(tls_ctx_, store);
  17609. custom_ca_loaded_ = true;
  17610. } else if (store) {
  17611. tls::free_ca_store(store);
  17612. }
  17613. }
  17614. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17615. std::size_t size) {
  17616. if (tls_ctx_ && ca_cert && size > 0) {
  17617. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17618. custom_ca_loaded_ = true;
  17619. }
  17620. }
  17621. inline void
  17622. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17623. server_certificate_verification_ = enabled;
  17624. }
  17625. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17626. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17627. }
  17628. #endif // CPPHTTPLIB_SSL_ENABLED
  17629. } // namespace ws
  17630. // ----------------------------------------------------------------------------
  17631. } // namespace httplib
  17632. #endif // CPPHTTPLIB_HTTPLIB_H