httplib.h 688 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788
  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. std::string s = method;
  6250. s += ' ';
  6251. s += path;
  6252. s += " HTTP/1.1\r\n";
  6253. return strm.write(s.data(), s.size());
  6254. }
  6255. inline ssize_t write_response_line(Stream &strm, int status) {
  6256. std::string s = "HTTP/1.1 ";
  6257. s += std::to_string(status);
  6258. s += ' ';
  6259. s += httplib::status_message(status);
  6260. s += "\r\n";
  6261. return strm.write(s.data(), s.size());
  6262. }
  6263. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6264. ssize_t write_len = 0;
  6265. for (const auto &x : headers) {
  6266. std::string s;
  6267. s = x.first;
  6268. s += ": ";
  6269. s += x.second;
  6270. s += "\r\n";
  6271. auto len = strm.write(s.data(), s.size());
  6272. if (len < 0) { return len; }
  6273. write_len += len;
  6274. }
  6275. auto len = strm.write("\r\n");
  6276. if (len < 0) { return len; }
  6277. write_len += len;
  6278. return write_len;
  6279. }
  6280. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6281. size_t offset = 0;
  6282. while (offset < l) {
  6283. auto length = strm.write(d + offset, l - offset);
  6284. if (length < 0) { return false; }
  6285. offset += static_cast<size_t>(length);
  6286. }
  6287. return true;
  6288. }
  6289. template <typename T>
  6290. inline bool write_content_with_progress(Stream &strm,
  6291. const ContentProvider &content_provider,
  6292. size_t offset, size_t length,
  6293. T is_shutting_down,
  6294. const UploadProgress &upload_progress,
  6295. Error &error) {
  6296. size_t end_offset = offset + length;
  6297. size_t start_offset = offset;
  6298. auto ok = true;
  6299. DataSink data_sink;
  6300. data_sink.write = [&](const char *d, size_t l) -> bool {
  6301. if (ok) {
  6302. if (write_data(strm, d, l)) {
  6303. offset += l;
  6304. if (upload_progress && length > 0) {
  6305. size_t current_written = offset - start_offset;
  6306. if (!upload_progress(current_written, length)) {
  6307. ok = false;
  6308. return false;
  6309. }
  6310. }
  6311. } else {
  6312. ok = false;
  6313. }
  6314. }
  6315. return ok;
  6316. };
  6317. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6318. while (offset < end_offset && !is_shutting_down()) {
  6319. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6320. error = Error::Write;
  6321. return false;
  6322. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6323. error = Error::Canceled;
  6324. return false;
  6325. } else if (!ok) {
  6326. error = Error::Write;
  6327. return false;
  6328. }
  6329. }
  6330. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6331. error = Error::Write;
  6332. return false;
  6333. }
  6334. error = Error::Success;
  6335. return true;
  6336. }
  6337. template <typename T>
  6338. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6339. size_t offset, size_t length, T is_shutting_down,
  6340. Error &error) {
  6341. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6342. is_shutting_down, nullptr, error);
  6343. }
  6344. template <typename T>
  6345. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6346. size_t offset, size_t length,
  6347. const T &is_shutting_down) {
  6348. auto error = Error::Success;
  6349. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6350. error);
  6351. }
  6352. template <typename T>
  6353. inline bool
  6354. write_content_without_length(Stream &strm,
  6355. const ContentProvider &content_provider,
  6356. const T &is_shutting_down) {
  6357. size_t offset = 0;
  6358. auto data_available = true;
  6359. auto ok = true;
  6360. DataSink data_sink;
  6361. data_sink.write = [&](const char *d, size_t l) -> bool {
  6362. if (ok) {
  6363. offset += l;
  6364. if (!write_data(strm, d, l)) { ok = false; }
  6365. }
  6366. return ok;
  6367. };
  6368. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6369. data_sink.done = [&](void) { data_available = false; };
  6370. while (data_available && !is_shutting_down()) {
  6371. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6372. return false;
  6373. } else if (!content_provider(offset, 0, data_sink)) {
  6374. return false;
  6375. } else if (!ok) {
  6376. return false;
  6377. }
  6378. }
  6379. return !data_available; // true only if done() was called, false if shutting
  6380. // down
  6381. }
  6382. template <typename T, typename U>
  6383. inline bool
  6384. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6385. const T &is_shutting_down, U &compressor, Error &error) {
  6386. size_t offset = 0;
  6387. auto data_available = true;
  6388. auto ok = true;
  6389. DataSink data_sink;
  6390. data_sink.write = [&](const char *d, size_t l) -> bool {
  6391. if (ok) {
  6392. data_available = l > 0;
  6393. offset += l;
  6394. std::string payload;
  6395. if (compressor.compress(d, l, false,
  6396. [&](const char *data, size_t data_len) {
  6397. payload.append(data, data_len);
  6398. return true;
  6399. })) {
  6400. if (!payload.empty()) {
  6401. // Emit chunked response header and footer for each chunk
  6402. auto chunk =
  6403. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6404. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6405. }
  6406. } else {
  6407. ok = false;
  6408. }
  6409. }
  6410. return ok;
  6411. };
  6412. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6413. auto done_with_trailer = [&](const Headers *trailer) {
  6414. if (!ok) { return; }
  6415. data_available = false;
  6416. std::string payload;
  6417. if (!compressor.compress(nullptr, 0, true,
  6418. [&](const char *data, size_t data_len) {
  6419. payload.append(data, data_len);
  6420. return true;
  6421. })) {
  6422. ok = false;
  6423. return;
  6424. }
  6425. if (!payload.empty()) {
  6426. // Emit chunked response header and footer for each chunk
  6427. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6428. if (!write_data(strm, chunk.data(), chunk.size())) {
  6429. ok = false;
  6430. return;
  6431. }
  6432. }
  6433. constexpr const char done_marker[] = "0\r\n";
  6434. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6435. // Trailer
  6436. if (trailer) {
  6437. for (const auto &kv : *trailer) {
  6438. // Skip fields with invalid names or values to prevent response
  6439. // splitting via CR/LF injection, matching set_header().
  6440. if (!fields::is_field_name(kv.first) ||
  6441. !fields::is_field_value(kv.second)) {
  6442. continue;
  6443. }
  6444. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6445. if (!write_data(strm, field_line.data(), field_line.size())) {
  6446. ok = false;
  6447. }
  6448. }
  6449. }
  6450. constexpr const char crlf[] = "\r\n";
  6451. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6452. };
  6453. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6454. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6455. done_with_trailer(&trailer);
  6456. };
  6457. while (data_available && !is_shutting_down()) {
  6458. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6459. error = Error::Write;
  6460. return false;
  6461. } else if (!content_provider(offset, 0, data_sink)) {
  6462. error = Error::Canceled;
  6463. return false;
  6464. } else if (!ok) {
  6465. error = Error::Write;
  6466. return false;
  6467. }
  6468. }
  6469. if (data_available) { // exited due to is_shutting_down(), not done()
  6470. error = Error::Write;
  6471. return false;
  6472. }
  6473. error = Error::Success;
  6474. return true;
  6475. }
  6476. template <typename T, typename U>
  6477. inline bool write_content_chunked(Stream &strm,
  6478. const ContentProvider &content_provider,
  6479. const T &is_shutting_down, U &compressor) {
  6480. auto error = Error::Success;
  6481. return write_content_chunked(strm, content_provider, is_shutting_down,
  6482. compressor, error);
  6483. }
  6484. template <typename T>
  6485. inline bool redirect(T &cli, Request &req, Response &res,
  6486. const std::string &path, const std::string &location,
  6487. Error &error) {
  6488. Request new_req = req;
  6489. new_req.path = path;
  6490. new_req.redirect_count_ -= 1;
  6491. if (res.status == StatusCode::SeeOther_303 &&
  6492. (req.method != "GET" && req.method != "HEAD")) {
  6493. new_req.method = "GET";
  6494. new_req.body.clear();
  6495. new_req.headers.clear();
  6496. }
  6497. Response new_res;
  6498. auto ret = cli.send(new_req, new_res, error);
  6499. if (ret) {
  6500. req = std::move(new_req);
  6501. res = std::move(new_res);
  6502. if (res.location.empty()) { res.location = location; }
  6503. }
  6504. return ret;
  6505. }
  6506. inline std::string params_to_query_str(const Params &params) {
  6507. std::string query;
  6508. for (auto it = params.begin(); it != params.end(); ++it) {
  6509. if (it != params.begin()) { query += '&'; }
  6510. query += encode_query_component(it->first);
  6511. query += '=';
  6512. query += encode_query_component(it->second);
  6513. }
  6514. return query;
  6515. }
  6516. inline void parse_query_text(const char *data, std::size_t size,
  6517. Params &params) {
  6518. std::set<std::string> cache;
  6519. split(data, data + size, '&', [&](const char *b, const char *e) {
  6520. std::string kv(b, e);
  6521. if (cache.find(kv) != cache.end()) { return; }
  6522. cache.insert(std::move(kv));
  6523. std::string key;
  6524. std::string val;
  6525. divide(b, static_cast<std::size_t>(e - b), '=',
  6526. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6527. std::size_t rhs_size) {
  6528. key.assign(lhs_data, lhs_size);
  6529. val.assign(rhs_data, rhs_size);
  6530. });
  6531. if (!key.empty()) {
  6532. params.emplace(decode_query_component(key), decode_query_component(val));
  6533. }
  6534. });
  6535. }
  6536. inline void parse_query_text(const std::string &s, Params &params) {
  6537. parse_query_text(s.data(), s.size(), params);
  6538. }
  6539. // Normalize a query string by decoding and re-encoding each key/value pair
  6540. // while preserving the original parameter order. This avoids double-encoding
  6541. // and ensures consistent encoding without reordering (unlike Params which
  6542. // uses std::multimap and sorts keys).
  6543. inline std::string normalize_query_string(const std::string &query) {
  6544. std::string result;
  6545. split(query.data(), query.data() + query.size(), '&',
  6546. [&](const char *b, const char *e) {
  6547. std::string key;
  6548. std::string val;
  6549. divide(b, static_cast<std::size_t>(e - b), '=',
  6550. [&](const char *lhs_data, std::size_t lhs_size,
  6551. const char *rhs_data, std::size_t rhs_size) {
  6552. key.assign(lhs_data, lhs_size);
  6553. val.assign(rhs_data, rhs_size);
  6554. });
  6555. if (!key.empty()) {
  6556. auto dec_key = decode_query_component(key);
  6557. auto dec_val = decode_query_component(val);
  6558. if (!result.empty()) { result += '&'; }
  6559. result += encode_query_component(dec_key);
  6560. if (!val.empty() || std::find(b, e, '=') != e) {
  6561. result += '=';
  6562. result += encode_query_component(dec_val);
  6563. }
  6564. }
  6565. });
  6566. return result;
  6567. }
  6568. inline bool parse_multipart_boundary(const std::string &content_type,
  6569. std::string &boundary) {
  6570. std::map<std::string, std::string> params;
  6571. extract_media_type(content_type, &params);
  6572. auto it = params.find("boundary");
  6573. if (it == params.end()) { return false; }
  6574. boundary = it->second;
  6575. return !boundary.empty();
  6576. }
  6577. inline void parse_disposition_params(const std::string &s, Params &params) {
  6578. std::set<std::string> cache;
  6579. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6580. std::string kv(b, e);
  6581. if (cache.find(kv) != cache.end()) { return; }
  6582. cache.insert(kv);
  6583. std::string key;
  6584. std::string val;
  6585. split(b, e, '=', [&](const char *b2, const char *e2) {
  6586. if (key.empty()) {
  6587. key.assign(b2, e2);
  6588. } else {
  6589. val.assign(b2, e2);
  6590. }
  6591. });
  6592. if (!key.empty()) {
  6593. params.emplace(trim_double_quotes_copy((key)),
  6594. trim_double_quotes_copy((val)));
  6595. }
  6596. });
  6597. }
  6598. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6599. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6600. #else
  6601. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6602. #endif
  6603. auto is_valid = [](const std::string &str) {
  6604. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6605. };
  6606. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6607. const auto pos = static_cast<size_t>(6);
  6608. const auto len = static_cast<size_t>(s.size() - 6);
  6609. auto all_valid_ranges = true;
  6610. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6611. if (!all_valid_ranges) { return; }
  6612. const auto it = std::find(b, e, '-');
  6613. if (it == e) {
  6614. all_valid_ranges = false;
  6615. return;
  6616. }
  6617. const auto lhs = std::string(b, it);
  6618. const auto rhs = std::string(it + 1, e);
  6619. if (!is_valid(lhs) || !is_valid(rhs)) {
  6620. all_valid_ranges = false;
  6621. return;
  6622. }
  6623. ssize_t first = -1;
  6624. if (!lhs.empty()) {
  6625. ssize_t v;
  6626. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6627. if (res.ec == std::errc{}) { first = v; }
  6628. }
  6629. ssize_t last = -1;
  6630. if (!rhs.empty()) {
  6631. ssize_t v;
  6632. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6633. if (res.ec == std::errc{}) { last = v; }
  6634. }
  6635. if ((first == -1 && last == -1) ||
  6636. (first != -1 && last != -1 && first > last)) {
  6637. all_valid_ranges = false;
  6638. return;
  6639. }
  6640. ranges.emplace_back(first, last);
  6641. });
  6642. return all_valid_ranges && !ranges.empty();
  6643. }
  6644. return false;
  6645. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6646. }
  6647. #else
  6648. } catch (...) { return false; }
  6649. #endif
  6650. inline bool parse_accept_header(const std::string &s,
  6651. std::vector<std::string> &content_types) {
  6652. content_types.clear();
  6653. // Empty string is considered valid (no preference)
  6654. if (s.empty()) { return true; }
  6655. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6656. if (s.front() == ',' || s.back() == ',' ||
  6657. s.find(",,") != std::string::npos) {
  6658. return false;
  6659. }
  6660. struct AcceptEntry {
  6661. std::string media_type;
  6662. double quality;
  6663. int order;
  6664. };
  6665. std::vector<AcceptEntry> entries;
  6666. int order = 0;
  6667. bool has_invalid_entry = false;
  6668. // Split by comma and parse each entry
  6669. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6670. std::string entry(b, e);
  6671. entry = trim_copy(entry);
  6672. if (entry.empty()) {
  6673. has_invalid_entry = true;
  6674. return;
  6675. }
  6676. AcceptEntry accept_entry;
  6677. accept_entry.order = order++;
  6678. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6679. accept_entry.media_type, accept_entry.quality)) {
  6680. has_invalid_entry = true;
  6681. return;
  6682. }
  6683. // Remove additional parameters from media type
  6684. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6685. // Basic validation of media type format
  6686. if (accept_entry.media_type.empty()) {
  6687. has_invalid_entry = true;
  6688. return;
  6689. }
  6690. // Check for basic media type format (should contain '/' or be '*')
  6691. if (accept_entry.media_type != "*" &&
  6692. accept_entry.media_type.find('/') == std::string::npos) {
  6693. has_invalid_entry = true;
  6694. return;
  6695. }
  6696. entries.push_back(std::move(accept_entry));
  6697. });
  6698. // Return false if any invalid entry was found
  6699. if (has_invalid_entry) { return false; }
  6700. // Sort by quality (descending), then by original order (ascending)
  6701. std::sort(entries.begin(), entries.end(),
  6702. [](const AcceptEntry &a, const AcceptEntry &b) {
  6703. if (a.quality != b.quality) {
  6704. return a.quality > b.quality; // Higher quality first
  6705. }
  6706. return a.order < b.order; // Earlier order first for same quality
  6707. });
  6708. // Extract sorted media types
  6709. content_types.reserve(entries.size());
  6710. for (auto &entry : entries) {
  6711. content_types.push_back(std::move(entry.media_type));
  6712. }
  6713. return true;
  6714. }
  6715. class FormDataParser {
  6716. public:
  6717. FormDataParser() = default;
  6718. void set_boundary(std::string &&boundary) {
  6719. boundary_ = std::move(boundary);
  6720. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6721. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6722. }
  6723. bool is_valid() const { return is_valid_; }
  6724. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6725. const ContentReceiver &content_callback) {
  6726. buf_append(buf, n);
  6727. while (buf_size() > 0) {
  6728. switch (state_) {
  6729. case 0: { // Initial boundary
  6730. auto pos = buf_find(dash_boundary_crlf_);
  6731. if (pos == buf_size()) { return true; }
  6732. buf_erase(pos + dash_boundary_crlf_.size());
  6733. state_ = 1;
  6734. break;
  6735. }
  6736. case 1: { // New entry
  6737. clear_file_info();
  6738. state_ = 2;
  6739. break;
  6740. }
  6741. case 2: { // Headers
  6742. auto pos = buf_find(crlf_);
  6743. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6744. while (pos < buf_size()) {
  6745. // Empty line
  6746. if (pos == 0) {
  6747. if (!header_callback(file_)) {
  6748. is_valid_ = false;
  6749. return false;
  6750. }
  6751. buf_erase(crlf_.size());
  6752. state_ = 3;
  6753. break;
  6754. }
  6755. const auto header = buf_head(pos);
  6756. if (!parse_header(header.data(), header.data() + header.size(),
  6757. [&](const std::string &, const std::string &) {})) {
  6758. is_valid_ = false;
  6759. return false;
  6760. }
  6761. // Parse and emplace space trimmed headers into a map
  6762. if (!parse_header(
  6763. header.data(), header.data() + header.size(),
  6764. [&](const std::string &key, const std::string &val) {
  6765. file_.headers.emplace(key, val);
  6766. })) {
  6767. is_valid_ = false;
  6768. return false;
  6769. }
  6770. constexpr const char header_content_type[] = "Content-Type:";
  6771. if (start_with_case_ignore(header, header_content_type)) {
  6772. file_.content_type =
  6773. trim_copy(header.substr(str_len(header_content_type)));
  6774. } else {
  6775. std::string disposition_params;
  6776. if (parse_content_disposition(header, disposition_params)) {
  6777. Params params;
  6778. parse_disposition_params(disposition_params, params);
  6779. auto it = params.find("name");
  6780. if (it != params.end()) {
  6781. file_.name = it->second;
  6782. } else {
  6783. is_valid_ = false;
  6784. return false;
  6785. }
  6786. it = params.find("filename");
  6787. if (it != params.end()) { file_.filename = it->second; }
  6788. it = params.find("filename*");
  6789. if (it != params.end()) {
  6790. // RFC 5987: only UTF-8 encoding is allowed
  6791. const auto &val = it->second;
  6792. constexpr const char utf8_prefix[] = "UTF-8''";
  6793. constexpr size_t prefix_len = str_len(utf8_prefix);
  6794. if (val.size() > prefix_len &&
  6795. start_with_case_ignore(val, utf8_prefix)) {
  6796. file_.filename = decode_path_component(
  6797. val.substr(prefix_len)); // override...
  6798. } else {
  6799. is_valid_ = false;
  6800. return false;
  6801. }
  6802. }
  6803. }
  6804. }
  6805. buf_erase(pos + crlf_.size());
  6806. pos = buf_find(crlf_);
  6807. }
  6808. if (state_ != 3) { return true; }
  6809. break;
  6810. }
  6811. case 3: { // Body
  6812. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6813. auto pos = buf_find(crlf_dash_boundary_);
  6814. if (pos < buf_size()) {
  6815. if (!content_callback(buf_data(), pos)) {
  6816. is_valid_ = false;
  6817. return false;
  6818. }
  6819. buf_erase(pos + crlf_dash_boundary_.size());
  6820. state_ = 4;
  6821. } else {
  6822. auto len = buf_size() - crlf_dash_boundary_.size();
  6823. if (len > 0) {
  6824. if (!content_callback(buf_data(), len)) {
  6825. is_valid_ = false;
  6826. return false;
  6827. }
  6828. buf_erase(len);
  6829. }
  6830. return true;
  6831. }
  6832. break;
  6833. }
  6834. case 4: { // Boundary
  6835. if (crlf_.size() > buf_size()) { return true; }
  6836. if (buf_start_with(crlf_)) {
  6837. buf_erase(crlf_.size());
  6838. state_ = 1;
  6839. } else {
  6840. if (dash_.size() > buf_size()) { return true; }
  6841. if (buf_start_with(dash_)) {
  6842. buf_erase(dash_.size());
  6843. is_valid_ = true;
  6844. buf_erase(buf_size()); // Remove epilogue
  6845. } else {
  6846. return true;
  6847. }
  6848. }
  6849. break;
  6850. }
  6851. }
  6852. }
  6853. return true;
  6854. }
  6855. private:
  6856. void clear_file_info() {
  6857. file_.name.clear();
  6858. file_.filename.clear();
  6859. file_.content_type.clear();
  6860. file_.headers.clear();
  6861. }
  6862. bool start_with_case_ignore(const std::string &a, const char *b,
  6863. size_t offset = 0) const {
  6864. const auto b_len = strlen(b);
  6865. if (a.size() < offset + b_len) { return false; }
  6866. for (size_t i = 0; i < b_len; i++) {
  6867. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6868. return false;
  6869. }
  6870. }
  6871. return true;
  6872. }
  6873. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6874. // Returns true if header matches, with the params portion in `params_out`.
  6875. bool parse_content_disposition(const std::string &header,
  6876. std::string &params_out) const {
  6877. constexpr const char prefix[] = "Content-Disposition:";
  6878. constexpr size_t prefix_len = str_len(prefix);
  6879. if (!start_with_case_ignore(header, prefix)) { return false; }
  6880. // Skip whitespace after "Content-Disposition:"
  6881. auto pos = prefix_len;
  6882. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6883. pos++;
  6884. }
  6885. // Match "form-data;" (case-insensitive)
  6886. constexpr const char form_data[] = "form-data;";
  6887. constexpr size_t form_data_len = str_len(form_data);
  6888. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6889. pos += form_data_len;
  6890. // Skip whitespace after "form-data;"
  6891. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6892. pos++;
  6893. }
  6894. params_out = header.substr(pos);
  6895. return true;
  6896. }
  6897. const std::string dash_ = "--";
  6898. const std::string crlf_ = "\r\n";
  6899. std::string boundary_;
  6900. std::string dash_boundary_crlf_;
  6901. std::string crlf_dash_boundary_;
  6902. size_t state_ = 0;
  6903. bool is_valid_ = false;
  6904. FormData file_;
  6905. // Buffer
  6906. bool start_with(const std::string &a, size_t spos, size_t epos,
  6907. const std::string &b) const {
  6908. if (epos - spos < b.size()) { return false; }
  6909. for (size_t i = 0; i < b.size(); i++) {
  6910. if (a[i + spos] != b[i]) { return false; }
  6911. }
  6912. return true;
  6913. }
  6914. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6915. const char *buf_data() const { return &buf_[buf_spos_]; }
  6916. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6917. bool buf_start_with(const std::string &s) const {
  6918. return start_with(buf_, buf_spos_, buf_epos_, s);
  6919. }
  6920. size_t buf_find(const std::string &s) const {
  6921. auto c = s.front();
  6922. size_t off = buf_spos_;
  6923. while (off < buf_epos_) {
  6924. auto pos = off;
  6925. while (true) {
  6926. if (pos == buf_epos_) { return buf_size(); }
  6927. if (buf_[pos] == c) { break; }
  6928. pos++;
  6929. }
  6930. auto remaining_size = buf_epos_ - pos;
  6931. if (s.size() > remaining_size) { return buf_size(); }
  6932. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6933. off = pos + 1;
  6934. }
  6935. return buf_size();
  6936. }
  6937. void buf_append(const char *data, size_t n) {
  6938. auto remaining_size = buf_size();
  6939. if (remaining_size > 0 && buf_spos_ > 0) {
  6940. for (size_t i = 0; i < remaining_size; i++) {
  6941. buf_[i] = buf_[buf_spos_ + i];
  6942. }
  6943. }
  6944. buf_spos_ = 0;
  6945. buf_epos_ = remaining_size;
  6946. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6947. for (size_t i = 0; i < n; i++) {
  6948. buf_[buf_epos_ + i] = data[i];
  6949. }
  6950. buf_epos_ += n;
  6951. }
  6952. void buf_erase(size_t size) { buf_spos_ += size; }
  6953. std::string buf_;
  6954. size_t buf_spos_ = 0;
  6955. size_t buf_epos_ = 0;
  6956. };
  6957. inline std::string random_string(size_t length) {
  6958. constexpr const char data[] =
  6959. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6960. thread_local auto engine([]() {
  6961. // std::random_device might actually be deterministic on some
  6962. // platforms, but due to lack of support in the c++ standard library,
  6963. // doing better requires either some ugly hacks or breaking portability.
  6964. std::random_device seed_gen;
  6965. // Request 128 bits of entropy for initialization
  6966. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6967. return std::mt19937(seed_sequence);
  6968. }());
  6969. std::string result;
  6970. for (size_t i = 0; i < length; i++) {
  6971. result += data[engine() % (sizeof(data) - 1)];
  6972. }
  6973. return result;
  6974. }
  6975. inline std::string make_multipart_data_boundary() {
  6976. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6977. }
  6978. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6979. auto valid = true;
  6980. for (size_t i = 0; i < boundary.size(); i++) {
  6981. auto c = boundary[i];
  6982. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  6983. valid = false;
  6984. break;
  6985. }
  6986. }
  6987. return valid;
  6988. }
  6989. // Escape a multipart field name/filename following the WHATWG HTML standard
  6990. // ("escape a multipart form-data name"), which is what browsers send:
  6991. // '"' -> %22, CR -> %0D, LF -> %0A
  6992. // With escape_quote = false, only CR and LF are escaped; this is for header
  6993. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  6994. inline std::string escape_multipart_field(const std::string &s,
  6995. bool escape_quote = true) {
  6996. std::string result;
  6997. result.reserve(s.size());
  6998. for (auto c : s) {
  6999. switch (c) {
  7000. case '"':
  7001. if (escape_quote) {
  7002. result += "%22";
  7003. } else {
  7004. result += c;
  7005. }
  7006. break;
  7007. case '\r': result += "%0D"; break;
  7008. case '\n': result += "%0A"; break;
  7009. default: result += c; break;
  7010. }
  7011. }
  7012. return result;
  7013. }
  7014. template <typename T>
  7015. inline std::string
  7016. serialize_multipart_formdata_item_begin(const T &item,
  7017. const std::string &boundary) {
  7018. std::string body = "--" + boundary + "\r\n";
  7019. body += "Content-Disposition: form-data; name=\"" +
  7020. escape_multipart_field(item.name) + "\"";
  7021. if (!item.filename.empty()) {
  7022. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  7023. }
  7024. body += "\r\n";
  7025. if (!item.content_type.empty()) {
  7026. body +=
  7027. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  7028. "\r\n";
  7029. }
  7030. body += "\r\n";
  7031. return body;
  7032. }
  7033. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7034. inline std::string
  7035. serialize_multipart_formdata_finish(const std::string &boundary) {
  7036. return "--" + boundary + "--\r\n";
  7037. }
  7038. inline std::string
  7039. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7040. return "multipart/form-data; boundary=" + boundary;
  7041. }
  7042. inline std::string
  7043. serialize_multipart_formdata(const UploadFormDataItems &items,
  7044. const std::string &boundary, bool finish = true) {
  7045. std::string body;
  7046. for (const auto &item : items) {
  7047. body += serialize_multipart_formdata_item_begin(item, boundary);
  7048. body += item.content + serialize_multipart_formdata_item_end();
  7049. }
  7050. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7051. return body;
  7052. }
  7053. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7054. const std::string &boundary) {
  7055. size_t total = 0;
  7056. for (const auto &item : items) {
  7057. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7058. total += item.content.size();
  7059. total += serialize_multipart_formdata_item_end().size();
  7060. }
  7061. total += serialize_multipart_formdata_finish(boundary).size();
  7062. return total;
  7063. }
  7064. struct MultipartSegment {
  7065. const char *data;
  7066. size_t size;
  7067. };
  7068. // NOTE: items must outlive the returned ContentProvider
  7069. // (safe for synchronous use inside Post/Put/Patch)
  7070. inline ContentProvider
  7071. make_multipart_content_provider(const UploadFormDataItems &items,
  7072. const std::string &boundary) {
  7073. // Own the per-item header strings and the finish string
  7074. std::vector<std::string> owned;
  7075. owned.reserve(items.size() + 1);
  7076. for (const auto &item : items)
  7077. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7078. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7079. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7080. std::vector<MultipartSegment> segs;
  7081. segs.reserve(items.size() * 3 + 1);
  7082. static const char crlf[] = "\r\n";
  7083. for (size_t i = 0; i < items.size(); i++) {
  7084. segs.push_back({owned[i].data(), owned[i].size()});
  7085. segs.push_back({items[i].content.data(), items[i].content.size()});
  7086. segs.push_back({crlf, 2});
  7087. }
  7088. segs.push_back({owned.back().data(), owned.back().size()});
  7089. struct MultipartState {
  7090. std::vector<std::string> owned;
  7091. std::vector<MultipartSegment> segs;
  7092. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7093. };
  7094. auto state = std::make_shared<MultipartState>();
  7095. state->owned = std::move(owned);
  7096. // `segs` holds raw pointers into owned strings; std::string move preserves
  7097. // the data pointer, so these pointers remain valid after the move above.
  7098. state->segs = std::move(segs);
  7099. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7100. // Buffer multiple small segments into fewer, larger writes to avoid
  7101. // excessive TCP packets when there are many form data items (#2410)
  7102. auto &buf = state->buf;
  7103. auto buf_size = buf.size();
  7104. size_t buf_len = 0;
  7105. size_t remaining = length;
  7106. // Find the first segment containing 'offset'
  7107. size_t pos = 0;
  7108. size_t seg_idx = 0;
  7109. for (; seg_idx < state->segs.size(); seg_idx++) {
  7110. const auto &seg = state->segs[seg_idx];
  7111. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7112. pos += seg.size;
  7113. }
  7114. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7115. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7116. const auto &seg = state->segs[seg_idx];
  7117. size_t available = seg.size - seg_offset;
  7118. size_t to_copy = (std::min)(available, remaining);
  7119. const char *src = seg.data + seg_offset;
  7120. seg_offset = 0; // only the first segment has a non-zero offset
  7121. while (to_copy > 0) {
  7122. size_t space = buf_size - buf_len;
  7123. size_t chunk = (std::min)(to_copy, space);
  7124. std::memcpy(buf.data() + buf_len, src, chunk);
  7125. buf_len += chunk;
  7126. src += chunk;
  7127. to_copy -= chunk;
  7128. remaining -= chunk;
  7129. if (buf_len == buf_size) {
  7130. if (!sink.write(buf.data(), buf_len)) { return false; }
  7131. buf_len = 0;
  7132. }
  7133. }
  7134. }
  7135. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7136. return true;
  7137. };
  7138. }
  7139. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7140. if (ranges.size() <= 1) return;
  7141. // Sort ranges by start position
  7142. std::sort(ranges.begin(), ranges.end(),
  7143. [](const Range &a, const Range &b) { return a.first < b.first; });
  7144. Ranges coalesced;
  7145. coalesced.reserve(ranges.size());
  7146. for (auto &r : ranges) {
  7147. auto first_pos = r.first;
  7148. auto last_pos = r.second;
  7149. // Handle special cases like in range_error
  7150. if (first_pos == -1 && last_pos == -1) {
  7151. first_pos = 0;
  7152. last_pos = static_cast<ssize_t>(content_length);
  7153. }
  7154. if (first_pos == -1) {
  7155. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7156. last_pos = static_cast<ssize_t>(content_length) - 1;
  7157. }
  7158. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7159. last_pos = static_cast<ssize_t>(content_length) - 1;
  7160. }
  7161. // Skip invalid ranges
  7162. if (!(0 <= first_pos && first_pos <= last_pos &&
  7163. last_pos < static_cast<ssize_t>(content_length))) {
  7164. continue;
  7165. }
  7166. // Coalesce with previous range if overlapping or adjacent (but not
  7167. // identical)
  7168. if (!coalesced.empty()) {
  7169. auto &prev = coalesced.back();
  7170. // Check if current range overlaps or is adjacent to previous range
  7171. // but don't coalesce identical ranges (allow duplicates)
  7172. if (first_pos <= prev.second + 1 &&
  7173. !(first_pos == prev.first && last_pos == prev.second)) {
  7174. // Extend the previous range
  7175. prev.second = (std::max)(prev.second, last_pos);
  7176. continue;
  7177. }
  7178. }
  7179. // Add new range
  7180. coalesced.emplace_back(first_pos, last_pos);
  7181. }
  7182. ranges = std::move(coalesced);
  7183. }
  7184. inline bool range_error(Request &req, Response &res) {
  7185. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7186. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7187. req.ranges.clear();
  7188. if (res.status == StatusCode::PartialContent_206) {
  7189. res.status = StatusCode::OK_200;
  7190. }
  7191. return false;
  7192. }
  7193. ssize_t content_len = static_cast<ssize_t>(
  7194. res.content_length_ ? res.content_length_ : res.body.size());
  7195. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7196. size_t overwrapping_count = 0;
  7197. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7198. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7199. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7200. // Too many ranges
  7201. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7202. for (auto &r : req.ranges) {
  7203. auto &first_pos = r.first;
  7204. auto &last_pos = r.second;
  7205. if (first_pos == -1 && last_pos == -1) {
  7206. first_pos = 0;
  7207. last_pos = content_len;
  7208. }
  7209. if (first_pos == -1) {
  7210. first_pos = content_len - last_pos;
  7211. last_pos = content_len - 1;
  7212. }
  7213. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7214. // A client can limit the number of bytes requested without knowing the
  7215. // size of the selected representation. If the last-pos value is absent,
  7216. // or if the value is greater than or equal to the current length of the
  7217. // representation data, the byte range is interpreted as the remainder of
  7218. // the representation (i.e., the server replaces the value of last-pos
  7219. // with a value that is one less than the current length of the selected
  7220. // representation).
  7221. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7222. if (last_pos == -1 || last_pos >= content_len) {
  7223. last_pos = content_len - 1;
  7224. }
  7225. // Range must be within content length
  7226. if (!(0 <= first_pos && first_pos <= last_pos &&
  7227. last_pos <= content_len - 1)) {
  7228. return true;
  7229. }
  7230. // Request must not have more than two overlapping ranges
  7231. for (const auto &processed_range : processed_ranges) {
  7232. if (!(last_pos < processed_range.first ||
  7233. first_pos > processed_range.second)) {
  7234. overwrapping_count++;
  7235. if (overwrapping_count > 2) { return true; }
  7236. break; // Only count once per range
  7237. }
  7238. }
  7239. processed_ranges.emplace_back(first_pos, last_pos);
  7240. }
  7241. // After validation, coalesce overlapping ranges as per RFC 9110
  7242. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7243. }
  7244. return false;
  7245. }
  7246. inline std::pair<size_t, size_t>
  7247. get_range_offset_and_length(Range r, size_t content_length) {
  7248. assert(r.first != -1 && r.second != -1);
  7249. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7250. assert(r.first <= r.second &&
  7251. r.second < static_cast<ssize_t>(content_length));
  7252. (void)(content_length);
  7253. return std::make_pair(static_cast<size_t>(r.first),
  7254. static_cast<size_t>(r.second - r.first) + 1);
  7255. }
  7256. inline std::string make_content_range_header_field(
  7257. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7258. auto st = offset_and_length.first;
  7259. auto ed = st + offset_and_length.second - 1;
  7260. std::string field = "bytes ";
  7261. field += std::to_string(st);
  7262. field += '-';
  7263. field += std::to_string(ed);
  7264. field += '/';
  7265. field += std::to_string(content_length);
  7266. return field;
  7267. }
  7268. template <typename SToken, typename CToken, typename Content>
  7269. bool process_multipart_ranges_data(const Request &req,
  7270. const std::string &boundary,
  7271. const std::string &content_type,
  7272. size_t content_length, SToken stoken,
  7273. CToken ctoken, Content content) {
  7274. for (size_t i = 0; i < req.ranges.size(); i++) {
  7275. ctoken("--");
  7276. stoken(boundary);
  7277. ctoken("\r\n");
  7278. if (!content_type.empty()) {
  7279. ctoken("Content-Type: ");
  7280. stoken(content_type);
  7281. ctoken("\r\n");
  7282. }
  7283. auto offset_and_length =
  7284. get_range_offset_and_length(req.ranges[i], content_length);
  7285. ctoken("Content-Range: ");
  7286. stoken(make_content_range_header_field(offset_and_length, content_length));
  7287. ctoken("\r\n");
  7288. ctoken("\r\n");
  7289. if (!content(offset_and_length.first, offset_and_length.second)) {
  7290. return false;
  7291. }
  7292. ctoken("\r\n");
  7293. }
  7294. ctoken("--");
  7295. stoken(boundary);
  7296. ctoken("--");
  7297. return true;
  7298. }
  7299. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7300. const std::string &boundary,
  7301. const std::string &content_type,
  7302. size_t content_length,
  7303. std::string &data) {
  7304. process_multipart_ranges_data(
  7305. req, boundary, content_type, content_length,
  7306. [&](const std::string &token) { data += token; },
  7307. [&](const std::string &token) { data += token; },
  7308. [&](size_t offset, size_t length) {
  7309. assert(offset + length <= content_length);
  7310. data += res.body.substr(offset, length);
  7311. return true;
  7312. });
  7313. }
  7314. inline size_t get_multipart_ranges_data_length(const Request &req,
  7315. const std::string &boundary,
  7316. const std::string &content_type,
  7317. size_t content_length) {
  7318. size_t data_length = 0;
  7319. process_multipart_ranges_data(
  7320. req, boundary, content_type, content_length,
  7321. [&](const std::string &token) { data_length += token.size(); },
  7322. [&](const std::string &token) { data_length += token.size(); },
  7323. [&](size_t /*offset*/, size_t length) {
  7324. data_length += length;
  7325. return true;
  7326. });
  7327. return data_length;
  7328. }
  7329. template <typename T>
  7330. inline bool
  7331. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7332. const std::string &boundary,
  7333. const std::string &content_type,
  7334. size_t content_length, const T &is_shutting_down) {
  7335. return process_multipart_ranges_data(
  7336. req, boundary, content_type, content_length,
  7337. [&](const std::string &token) { strm.write(token); },
  7338. [&](const std::string &token) { strm.write(token); },
  7339. [&](size_t offset, size_t length) {
  7340. return write_content(strm, res.content_provider_, offset, length,
  7341. is_shutting_down);
  7342. });
  7343. }
  7344. inline bool has_framed_body(const Request &req) {
  7345. return is_chunked_transfer_encoding(req.headers) ||
  7346. req.get_header_value_u64("Content-Length") > 0;
  7347. }
  7348. inline bool is_connection_persistent(const Request &req) {
  7349. auto conn = req.get_header_value("Connection");
  7350. if (conn == "close") { return false; }
  7351. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7352. return true;
  7353. }
  7354. inline bool expect_content(const Request &req) {
  7355. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7356. req.method == "DELETE") {
  7357. return true;
  7358. }
  7359. return has_framed_body(req);
  7360. }
  7361. #ifdef _WIN32
  7362. class WSInit {
  7363. public:
  7364. WSInit() {
  7365. WSADATA wsaData;
  7366. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7367. }
  7368. ~WSInit() {
  7369. if (is_valid_) WSACleanup();
  7370. }
  7371. bool is_valid_ = false;
  7372. };
  7373. static WSInit wsinit_;
  7374. #endif
  7375. inline bool parse_www_authenticate(const Response &res,
  7376. std::map<std::string, std::string> &auth,
  7377. bool is_proxy) {
  7378. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7379. if (res.has_header(auth_key)) {
  7380. thread_local auto re =
  7381. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7382. auto s = res.get_header_value(auth_key);
  7383. auto pos = s.find(' ');
  7384. if (pos != std::string::npos) {
  7385. auto type = s.substr(0, pos);
  7386. if (type == "Basic") {
  7387. return false;
  7388. } else if (type == "Digest") {
  7389. s = s.substr(pos + 1);
  7390. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7391. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7392. const auto &m = *i;
  7393. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7394. static_cast<size_t>(m.length(1)));
  7395. auto val = m.length(2) > 0
  7396. ? s.substr(static_cast<size_t>(m.position(2)),
  7397. static_cast<size_t>(m.length(2)))
  7398. : s.substr(static_cast<size_t>(m.position(3)),
  7399. static_cast<size_t>(m.length(3)));
  7400. auth[std::move(key)] = std::move(val);
  7401. }
  7402. return true;
  7403. }
  7404. }
  7405. }
  7406. return false;
  7407. }
  7408. class ContentProviderAdapter {
  7409. public:
  7410. explicit ContentProviderAdapter(
  7411. ContentProviderWithoutLength &&content_provider)
  7412. : content_provider_(std::move(content_provider)) {}
  7413. bool operator()(size_t offset, size_t, DataSink &sink) {
  7414. return content_provider_(offset, sink);
  7415. }
  7416. private:
  7417. ContentProviderWithoutLength content_provider_;
  7418. };
  7419. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7420. namespace fields {
  7421. inline bool is_token_char(char c) {
  7422. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7423. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7424. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7425. }
  7426. inline bool is_token(const std::string &s) {
  7427. if (s.empty()) { return false; }
  7428. for (auto c : s) {
  7429. if (!is_token_char(c)) { return false; }
  7430. }
  7431. return true;
  7432. }
  7433. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7434. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7435. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7436. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7437. inline bool is_field_content(const std::string &s) {
  7438. if (s.empty()) { return true; }
  7439. if (s.size() == 1) {
  7440. return is_field_vchar(s[0]);
  7441. } else if (s.size() == 2) {
  7442. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7443. } else {
  7444. size_t i = 0;
  7445. if (!is_field_vchar(s[i])) { return false; }
  7446. i++;
  7447. while (i < s.size() - 1) {
  7448. auto c = s[i++];
  7449. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7450. } else {
  7451. return false;
  7452. }
  7453. }
  7454. return is_field_vchar(s[i]);
  7455. }
  7456. }
  7457. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7458. } // namespace fields
  7459. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7460. int port, bool is_ssl,
  7461. const std::string &path,
  7462. const Headers &headers,
  7463. std::string &selected_subprotocol) {
  7464. // Validate path and host
  7465. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7466. return false;
  7467. }
  7468. // Validate user-provided headers
  7469. for (const auto &h : headers) {
  7470. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7471. return false;
  7472. }
  7473. }
  7474. // Generate random Sec-WebSocket-Key
  7475. thread_local std::mt19937 rng(std::random_device{}());
  7476. std::string key_bytes(16, '\0');
  7477. for (size_t i = 0; i < 16; i += 4) {
  7478. auto r = rng();
  7479. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7480. }
  7481. auto client_key = base64_encode(key_bytes);
  7482. // Build upgrade request
  7483. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7484. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7485. req_str += "Upgrade: websocket\r\n";
  7486. req_str += "Connection: Upgrade\r\n";
  7487. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7488. req_str += "Sec-WebSocket-Version: 13\r\n";
  7489. for (const auto &h : headers) {
  7490. req_str += h.first + ": " + h.second + "\r\n";
  7491. }
  7492. req_str += "\r\n";
  7493. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7494. // Verify 101 response and Sec-WebSocket-Accept header
  7495. auto expected_accept = websocket_accept_key(client_key);
  7496. return read_websocket_upgrade_response(strm, expected_accept,
  7497. selected_subprotocol);
  7498. }
  7499. } // namespace detail
  7500. /*
  7501. * Group 2: detail namespace - SSL common utilities
  7502. */
  7503. #ifdef CPPHTTPLIB_SSL_ENABLED
  7504. namespace detail {
  7505. class SSLSocketStream final : public Stream {
  7506. public:
  7507. SSLSocketStream(
  7508. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7509. time_t read_timeout_usec, time_t write_timeout_sec,
  7510. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7511. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7512. (std::chrono::steady_clock::time_point::min)());
  7513. ~SSLSocketStream() override;
  7514. bool is_readable() const override;
  7515. bool wait_readable() const override;
  7516. bool wait_writable() const override;
  7517. bool is_peer_alive() const override;
  7518. ssize_t read(char *ptr, size_t size) override;
  7519. ssize_t write(const char *ptr, size_t size) override;
  7520. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7521. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7522. socket_t socket() const override;
  7523. time_t duration() const override;
  7524. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7525. private:
  7526. socket_t sock_;
  7527. tls::session_t session_;
  7528. time_t read_timeout_sec_;
  7529. time_t read_timeout_usec_;
  7530. time_t write_timeout_sec_;
  7531. time_t write_timeout_usec_;
  7532. time_t max_timeout_msec_;
  7533. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7534. };
  7535. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7536. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7537. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7538. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7539. unsigned int hash_length = 0;
  7540. unsigned char hash[EVP_MAX_MD_SIZE];
  7541. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7542. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7543. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7544. std::stringstream ss;
  7545. for (auto i = 0u; i < hash_length; ++i) {
  7546. ss << std::hex << std::setw(2) << std::setfill('0')
  7547. << static_cast<unsigned int>(hash[i]);
  7548. }
  7549. return ss.str();
  7550. }
  7551. inline std::string MD5(const std::string &s) {
  7552. return message_digest(s, EVP_md5());
  7553. }
  7554. inline std::string SHA_256(const std::string &s) {
  7555. return message_digest(s, EVP_sha256());
  7556. }
  7557. inline std::string SHA_512(const std::string &s) {
  7558. return message_digest(s, EVP_sha512());
  7559. }
  7560. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7561. namespace {
  7562. template <size_t N>
  7563. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7564. std::stringstream ss;
  7565. for (size_t i = 0; i < N; ++i) {
  7566. ss << std::hex << std::setw(2) << std::setfill('0')
  7567. << static_cast<unsigned int>(hash[i]);
  7568. }
  7569. return ss.str();
  7570. }
  7571. } // namespace
  7572. inline std::string MD5(const std::string &s) {
  7573. unsigned char hash[16];
  7574. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7575. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7576. hash);
  7577. #else
  7578. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7579. hash);
  7580. #endif
  7581. return hash_to_hex(hash);
  7582. }
  7583. inline std::string SHA_256(const std::string &s) {
  7584. unsigned char hash[32];
  7585. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7586. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7587. hash, 0);
  7588. #else
  7589. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7590. s.size(), hash, 0);
  7591. #endif
  7592. return hash_to_hex(hash);
  7593. }
  7594. inline std::string SHA_512(const std::string &s) {
  7595. unsigned char hash[64];
  7596. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7597. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7598. hash, 0);
  7599. #else
  7600. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7601. s.size(), hash, 0);
  7602. #endif
  7603. return hash_to_hex(hash);
  7604. }
  7605. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7606. namespace {
  7607. template <size_t N>
  7608. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7609. std::stringstream ss;
  7610. for (size_t i = 0; i < N; ++i) {
  7611. ss << std::hex << std::setw(2) << std::setfill('0')
  7612. << static_cast<unsigned int>(hash[i]);
  7613. }
  7614. return ss.str();
  7615. }
  7616. } // namespace
  7617. inline std::string MD5(const std::string &s) {
  7618. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7619. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7620. static_cast<word32>(s.size()), hash);
  7621. return hash_to_hex(hash);
  7622. }
  7623. inline std::string SHA_256(const std::string &s) {
  7624. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7625. wc_Sha256Hash(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_512(const std::string &s) {
  7630. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7631. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7632. static_cast<word32>(s.size()), hash);
  7633. return hash_to_hex(hash);
  7634. }
  7635. #endif
  7636. inline bool is_ip_address(const std::string &host) {
  7637. struct in_addr addr4;
  7638. struct in6_addr addr6;
  7639. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7640. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7641. }
  7642. template <typename T>
  7643. inline bool process_server_socket_ssl(
  7644. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7645. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7646. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7647. time_t write_timeout_usec, T callback) {
  7648. return process_server_socket_core(
  7649. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7650. [&](bool close_connection, bool &connection_closed) {
  7651. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7652. write_timeout_sec, write_timeout_usec);
  7653. return callback(strm, close_connection, connection_closed);
  7654. });
  7655. }
  7656. template <typename T>
  7657. inline bool process_client_socket_ssl(
  7658. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7659. time_t read_timeout_usec, time_t write_timeout_sec,
  7660. time_t write_timeout_usec, time_t max_timeout_msec,
  7661. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7662. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7663. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7664. start_time);
  7665. return callback(strm);
  7666. }
  7667. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7668. const Request &req, const std::map<std::string, std::string> &auth,
  7669. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7670. const std::string &password, bool is_proxy = false) {
  7671. std::string nc;
  7672. {
  7673. std::stringstream ss;
  7674. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7675. nc = ss.str();
  7676. }
  7677. std::string qop;
  7678. if (auth.find("qop") != auth.end()) {
  7679. qop = auth.at("qop");
  7680. if (qop.find("auth-int") != std::string::npos) {
  7681. qop = "auth-int";
  7682. } else if (qop.find("auth") != std::string::npos) {
  7683. qop = "auth";
  7684. } else {
  7685. qop.clear();
  7686. }
  7687. }
  7688. std::string algo = "MD5";
  7689. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7690. std::string response;
  7691. {
  7692. auto H = algo == "SHA-256" ? detail::SHA_256
  7693. : algo == "SHA-512" ? detail::SHA_512
  7694. : detail::MD5;
  7695. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7696. auto A2 = req.method + ":" + req.path;
  7697. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7698. if (qop.empty()) {
  7699. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7700. } else {
  7701. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7702. ":" + qop + ":" + H(A2));
  7703. }
  7704. }
  7705. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7706. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7707. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7708. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7709. (qop.empty() ? ", response=\""
  7710. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7711. cnonce + "\", response=\"") +
  7712. response + "\"" +
  7713. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7714. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7715. return std::make_pair(key, field);
  7716. }
  7717. inline bool match_hostname(const std::string &pattern,
  7718. const std::string &hostname) {
  7719. // Exact match (case-insensitive)
  7720. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7721. // Split both pattern and hostname into components by '.'
  7722. std::vector<std::string> pattern_components;
  7723. if (!pattern.empty()) {
  7724. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7725. [&](const char *b, const char *e) {
  7726. pattern_components.emplace_back(b, e);
  7727. });
  7728. }
  7729. std::vector<std::string> host_components;
  7730. if (!hostname.empty()) {
  7731. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7732. [&](const char *b, const char *e) {
  7733. host_components.emplace_back(b, e);
  7734. });
  7735. }
  7736. // Component count must match
  7737. if (host_components.size() != pattern_components.size()) { return false; }
  7738. // Compare each component with wildcard support
  7739. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7740. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7741. auto itr = pattern_components.begin();
  7742. for (const auto &h : host_components) {
  7743. auto &p = *itr;
  7744. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7745. bool partial_match = false;
  7746. if (!p.empty() && p[p.size() - 1] == '*') {
  7747. const auto prefix_length = p.size() - 1;
  7748. if (prefix_length == 0) {
  7749. partial_match = true;
  7750. } else if (h.size() >= prefix_length) {
  7751. partial_match =
  7752. std::equal(p.begin(),
  7753. p.begin() + static_cast<std::string::difference_type>(
  7754. prefix_length),
  7755. h.begin(), [](const char ca, const char cb) {
  7756. return detail::case_ignore::to_lower(ca) ==
  7757. detail::case_ignore::to_lower(cb);
  7758. });
  7759. }
  7760. }
  7761. if (!partial_match) { return false; }
  7762. }
  7763. ++itr;
  7764. }
  7765. return true;
  7766. }
  7767. #ifdef _WIN32
  7768. // Verify certificate using Windows CertGetCertificateChain API.
  7769. // This provides real-time certificate validation with Windows Update
  7770. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7771. inline bool
  7772. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7773. const std::string &hostname,
  7774. bool verify_hostname, uint64_t &out_error) {
  7775. if (der_cert.empty()) { return false; }
  7776. out_error = 0;
  7777. // Create Windows certificate context from DER data
  7778. auto cert_context = CertCreateCertificateContext(
  7779. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7780. static_cast<DWORD>(der_cert.size()));
  7781. if (!cert_context) {
  7782. out_error = GetLastError();
  7783. return false;
  7784. }
  7785. auto cert_guard =
  7786. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7787. // Setup chain parameters
  7788. CERT_CHAIN_PARA chain_para = {};
  7789. chain_para.cbSize = sizeof(chain_para);
  7790. // Build certificate chain with revocation checking
  7791. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7792. auto chain_result = CertGetCertificateChain(
  7793. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7794. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7795. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7796. nullptr, &chain_context);
  7797. if (!chain_result || !chain_context) {
  7798. out_error = GetLastError();
  7799. return false;
  7800. }
  7801. auto chain_guard =
  7802. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7803. // Check if chain has errors
  7804. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7805. out_error = chain_context->TrustStatus.dwErrorStatus;
  7806. return false;
  7807. }
  7808. // Verify SSL policy
  7809. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7810. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7811. #ifdef AUTHTYPE_SERVER
  7812. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7813. #endif
  7814. std::wstring whost;
  7815. if (verify_hostname) {
  7816. whost = u8string_to_wstring(hostname.c_str());
  7817. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7818. }
  7819. CERT_CHAIN_POLICY_PARA policy_para = {};
  7820. policy_para.cbSize = sizeof(policy_para);
  7821. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7822. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7823. #else
  7824. policy_para.dwFlags = 0;
  7825. #endif
  7826. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7827. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7828. policy_status.cbSize = sizeof(policy_status);
  7829. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7830. &policy_para, &policy_status)) {
  7831. out_error = GetLastError();
  7832. return false;
  7833. }
  7834. if (policy_status.dwError != 0) {
  7835. out_error = policy_status.dwError;
  7836. return false;
  7837. }
  7838. return true;
  7839. }
  7840. #endif // _WIN32
  7841. // Loads CA file/dir configuration and applies the system CA policy to a
  7842. // client TLS context. PEM data and native stores are applied to the context
  7843. // directly at set time; has_custom_store reflects them for the Auto policy
  7844. // decision.
  7845. inline bool load_client_ca_config(tls::ctx_t ctx,
  7846. const std::string &ca_cert_file_path,
  7847. const std::string &ca_cert_dir_path,
  7848. bool has_custom_store, SystemCAMode mode,
  7849. uint64_t &backend_error) {
  7850. auto ret = true;
  7851. if (!ca_cert_file_path.empty()) {
  7852. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7853. backend_error = tls::get_error();
  7854. ret = false;
  7855. }
  7856. } else if (!ca_cert_dir_path.empty()) {
  7857. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7858. backend_error = tls::get_error();
  7859. ret = false;
  7860. }
  7861. }
  7862. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7863. !ca_cert_dir_path.empty() || has_custom_store;
  7864. if (mode == SystemCAMode::Enabled ||
  7865. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7866. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7867. }
  7868. return ret;
  7869. }
  7870. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7871. tls::session_t &session, socket_t sock,
  7872. bool server_certificate_verification,
  7873. time_t timeout_sec, time_t timeout_usec) {
  7874. using namespace tls;
  7875. if (!ctx) { return false; }
  7876. bool is_ip = is_ip_address(host);
  7877. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7878. // Chain verification happens during the handshake even for IP hosts; the
  7879. // certificate identity is verified post-handshake via verify_hostname()
  7880. set_verify_client(ctx, server_certificate_verification);
  7881. #endif
  7882. session = create_session(ctx, sock);
  7883. if (!session) { return false; }
  7884. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7885. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7886. // their identity is checked post-handshake below instead.
  7887. if (!is_ip) {
  7888. if (server_certificate_verification) {
  7889. set_hostname(session, host.c_str());
  7890. } else {
  7891. set_sni(session, host.c_str());
  7892. }
  7893. }
  7894. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7895. return false;
  7896. }
  7897. if (server_certificate_verification) {
  7898. if (get_verify_result(session) != 0) { return false; }
  7899. // Identity check against the peer certificate, post-handshake for all
  7900. // backends (same as SSLClient). For IP hosts this is the only identity
  7901. // verification since no hostname is bound during the handshake.
  7902. auto server_cert = get_peer_cert(session);
  7903. if (!server_cert) { return false; }
  7904. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7905. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7906. }
  7907. return true;
  7908. }
  7909. } // namespace detail
  7910. #endif // CPPHTTPLIB_SSL_ENABLED
  7911. /*
  7912. * Group 3: httplib namespace - Non-SSL public API implementations
  7913. */
  7914. inline void default_socket_options(socket_t sock) {
  7915. set_socket_opt(sock, SOL_SOCKET,
  7916. #ifdef SO_REUSEPORT
  7917. SO_REUSEPORT,
  7918. #else
  7919. SO_REUSEADDR,
  7920. #endif
  7921. 1);
  7922. }
  7923. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7924. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7925. sizeof(optval));
  7926. }
  7927. inline std::string get_bearer_token_auth(const Request &req) {
  7928. if (req.has_header("Authorization")) {
  7929. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7930. return req.get_header_value("Authorization")
  7931. .substr(bearer_header_prefix_len);
  7932. }
  7933. return "";
  7934. }
  7935. inline const char *status_message(int status) {
  7936. switch (status) {
  7937. case StatusCode::Continue_100: return "Continue";
  7938. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7939. case StatusCode::Processing_102: return "Processing";
  7940. case StatusCode::EarlyHints_103: return "Early Hints";
  7941. case StatusCode::OK_200: return "OK";
  7942. case StatusCode::Created_201: return "Created";
  7943. case StatusCode::Accepted_202: return "Accepted";
  7944. case StatusCode::NonAuthoritativeInformation_203:
  7945. return "Non-Authoritative Information";
  7946. case StatusCode::NoContent_204: return "No Content";
  7947. case StatusCode::ResetContent_205: return "Reset Content";
  7948. case StatusCode::PartialContent_206: return "Partial Content";
  7949. case StatusCode::MultiStatus_207: return "Multi-Status";
  7950. case StatusCode::AlreadyReported_208: return "Already Reported";
  7951. case StatusCode::IMUsed_226: return "IM Used";
  7952. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7953. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7954. case StatusCode::Found_302: return "Found";
  7955. case StatusCode::SeeOther_303: return "See Other";
  7956. case StatusCode::NotModified_304: return "Not Modified";
  7957. case StatusCode::UseProxy_305: return "Use Proxy";
  7958. case StatusCode::unused_306: return "unused";
  7959. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7960. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7961. case StatusCode::BadRequest_400: return "Bad Request";
  7962. case StatusCode::Unauthorized_401: return "Unauthorized";
  7963. case StatusCode::PaymentRequired_402: return "Payment Required";
  7964. case StatusCode::Forbidden_403: return "Forbidden";
  7965. case StatusCode::NotFound_404: return "Not Found";
  7966. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7967. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7968. case StatusCode::ProxyAuthenticationRequired_407:
  7969. return "Proxy Authentication Required";
  7970. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7971. case StatusCode::Conflict_409: return "Conflict";
  7972. case StatusCode::Gone_410: return "Gone";
  7973. case StatusCode::LengthRequired_411: return "Length Required";
  7974. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7975. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7976. case StatusCode::UriTooLong_414: return "URI Too Long";
  7977. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7978. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7979. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7980. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7981. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7982. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7983. case StatusCode::Locked_423: return "Locked";
  7984. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7985. case StatusCode::TooEarly_425: return "Too Early";
  7986. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7987. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7988. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7989. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7990. return "Request Header Fields Too Large";
  7991. case StatusCode::UnavailableForLegalReasons_451:
  7992. return "Unavailable For Legal Reasons";
  7993. case StatusCode::NotImplemented_501: return "Not Implemented";
  7994. case StatusCode::BadGateway_502: return "Bad Gateway";
  7995. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7996. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7997. case StatusCode::HttpVersionNotSupported_505:
  7998. return "HTTP Version Not Supported";
  7999. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  8000. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  8001. case StatusCode::LoopDetected_508: return "Loop Detected";
  8002. case StatusCode::NotExtended_510: return "Not Extended";
  8003. case StatusCode::NetworkAuthenticationRequired_511:
  8004. return "Network Authentication Required";
  8005. default:
  8006. case StatusCode::InternalServerError_500: return "Internal Server Error";
  8007. }
  8008. }
  8009. inline std::string to_string(const Error error) {
  8010. switch (error) {
  8011. case Error::Success: return "Success (no error)";
  8012. case Error::Unknown: return "Unknown";
  8013. case Error::Connection: return "Could not establish connection";
  8014. case Error::BindIPAddress: return "Failed to bind IP address";
  8015. case Error::Read: return "Failed to read connection";
  8016. case Error::Write: return "Failed to write connection";
  8017. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  8018. case Error::Canceled: return "Connection handling canceled";
  8019. case Error::SSLConnection: return "SSL connection failed";
  8020. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  8021. case Error::SSLServerVerification: return "SSL server verification failed";
  8022. case Error::SSLServerHostnameVerification:
  8023. return "SSL server hostname verification failed";
  8024. case Error::UnsupportedMultipartBoundaryChars:
  8025. return "Unsupported HTTP multipart boundary characters";
  8026. case Error::Compression: return "Compression failed";
  8027. case Error::ConnectionTimeout: return "Connection timed out";
  8028. case Error::ProxyConnection: return "Proxy connection failed";
  8029. case Error::ConnectionClosed: return "Connection closed by server";
  8030. case Error::Timeout: return "Read timeout";
  8031. case Error::ResourceExhaustion: return "Resource exhaustion";
  8032. case Error::TooManyFormDataFiles: return "Too many form data files";
  8033. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8034. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8035. case Error::ExceedMaxSocketDescriptorCount:
  8036. return "Exceeded maximum socket descriptor count";
  8037. case Error::InvalidRequestLine: return "Invalid request line";
  8038. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8039. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8040. case Error::InvalidHeaders: return "Invalid headers";
  8041. case Error::MultipartParsing: return "Multipart parsing failed";
  8042. case Error::OpenFile: return "Failed to open file";
  8043. case Error::Listen: return "Failed to listen on socket";
  8044. case Error::GetSockName: return "Failed to get socket name";
  8045. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8046. case Error::HTTPParsing: return "HTTP parsing failed";
  8047. case Error::InvalidRangeHeader: return "Invalid Range header";
  8048. default: break;
  8049. }
  8050. return "Invalid";
  8051. }
  8052. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8053. os << to_string(obj);
  8054. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8055. return os;
  8056. }
  8057. inline std::string hosted_at(const std::string &hostname) {
  8058. std::vector<std::string> addrs;
  8059. hosted_at(hostname, addrs);
  8060. if (addrs.empty()) { return std::string(); }
  8061. return addrs[0];
  8062. }
  8063. inline void hosted_at(const std::string &hostname,
  8064. std::vector<std::string> &addrs) {
  8065. struct addrinfo hints;
  8066. struct addrinfo *result;
  8067. memset(&hints, 0, sizeof(struct addrinfo));
  8068. hints.ai_family = AF_UNSPEC;
  8069. hints.ai_socktype = SOCK_STREAM;
  8070. hints.ai_protocol = 0;
  8071. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8072. &result, 0)) {
  8073. #if defined __linux__ && !defined __ANDROID__
  8074. res_init();
  8075. #endif
  8076. return;
  8077. }
  8078. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8079. for (auto rp = result; rp; rp = rp->ai_next) {
  8080. const auto &addr =
  8081. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8082. std::string ip;
  8083. auto dummy = -1;
  8084. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8085. dummy)) {
  8086. addrs.emplace_back(std::move(ip));
  8087. }
  8088. }
  8089. }
  8090. inline std::string encode_uri_component(const std::string &value) {
  8091. std::ostringstream escaped;
  8092. escaped.fill('0');
  8093. escaped << std::hex;
  8094. for (auto c : value) {
  8095. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8096. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8097. escaped << c;
  8098. } else {
  8099. escaped << std::uppercase;
  8100. escaped << '%' << std::setw(2)
  8101. << static_cast<int>(static_cast<unsigned char>(c));
  8102. escaped << std::nouppercase;
  8103. }
  8104. }
  8105. return escaped.str();
  8106. }
  8107. inline std::string encode_uri(const std::string &value) {
  8108. std::ostringstream escaped;
  8109. escaped.fill('0');
  8110. escaped << std::hex;
  8111. for (auto c : value) {
  8112. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8113. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8114. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8115. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8116. escaped << c;
  8117. } else {
  8118. escaped << std::uppercase;
  8119. escaped << '%' << std::setw(2)
  8120. << static_cast<int>(static_cast<unsigned char>(c));
  8121. escaped << std::nouppercase;
  8122. }
  8123. }
  8124. return escaped.str();
  8125. }
  8126. inline std::string decode_uri_component(const std::string &value) {
  8127. std::string result;
  8128. for (size_t i = 0; i < value.size(); i++) {
  8129. if (value[i] == '%' && i + 2 < value.size()) {
  8130. auto val = 0;
  8131. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8132. result += static_cast<char>(val);
  8133. i += 2;
  8134. } else {
  8135. result += value[i];
  8136. }
  8137. } else {
  8138. result += value[i];
  8139. }
  8140. }
  8141. return result;
  8142. }
  8143. inline std::string decode_uri(const std::string &value) {
  8144. std::string result;
  8145. for (size_t i = 0; i < value.size(); i++) {
  8146. if (value[i] == '%' && i + 2 < value.size()) {
  8147. auto val = 0;
  8148. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8149. result += static_cast<char>(val);
  8150. i += 2;
  8151. } else {
  8152. result += value[i];
  8153. }
  8154. } else {
  8155. result += value[i];
  8156. }
  8157. }
  8158. return result;
  8159. }
  8160. inline std::string encode_path_component(const std::string &component) {
  8161. std::string result;
  8162. result.reserve(component.size() * 3);
  8163. for (size_t i = 0; i < component.size(); i++) {
  8164. auto c = static_cast<unsigned char>(component[i]);
  8165. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8166. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8167. c == '_' || c == '~') {
  8168. result += static_cast<char>(c);
  8169. }
  8170. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8171. // "," / ";" / "="
  8172. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8173. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8174. c == '=') {
  8175. result += static_cast<char>(c);
  8176. }
  8177. // Colon is allowed in path segments except first segment
  8178. else if (c == ':') {
  8179. result += static_cast<char>(c);
  8180. }
  8181. // @ is allowed in path
  8182. else if (c == '@') {
  8183. result += static_cast<char>(c);
  8184. } else {
  8185. result += '%';
  8186. char hex[3];
  8187. snprintf(hex, sizeof(hex), "%02X", c);
  8188. result.append(hex, 2);
  8189. }
  8190. }
  8191. return result;
  8192. }
  8193. inline std::string decode_path_component(const std::string &component) {
  8194. std::string result;
  8195. result.reserve(component.size());
  8196. for (size_t i = 0; i < component.size(); i++) {
  8197. if (component[i] == '%' && i + 1 < component.size()) {
  8198. if (component[i + 1] == 'u') {
  8199. // Unicode %uXXXX encoding
  8200. auto val = 0;
  8201. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8202. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8203. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8204. char buff[4];
  8205. size_t len = detail::to_utf8(val, buff);
  8206. if (len > 0) { result.append(buff, len); }
  8207. i += 5; // 'u0000'
  8208. } else {
  8209. result += component[i];
  8210. }
  8211. } else {
  8212. // Standard %XX encoding
  8213. auto val = 0;
  8214. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8215. // 2 digits hex codes
  8216. result += static_cast<char>(val);
  8217. i += 2; // 'XX'
  8218. } else {
  8219. result += component[i];
  8220. }
  8221. }
  8222. } else {
  8223. result += component[i];
  8224. }
  8225. }
  8226. return result;
  8227. }
  8228. inline std::string encode_query_component(const std::string &component,
  8229. bool space_as_plus) {
  8230. std::string result;
  8231. result.reserve(component.size() * 3);
  8232. for (size_t i = 0; i < component.size(); i++) {
  8233. auto c = static_cast<unsigned char>(component[i]);
  8234. // Unreserved characters per RFC 3986
  8235. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8236. c == '_' || c == '~') {
  8237. result += static_cast<char>(c);
  8238. }
  8239. // Space handling
  8240. else if (c == ' ') {
  8241. if (space_as_plus) {
  8242. result += '+';
  8243. } else {
  8244. result += "%20";
  8245. }
  8246. }
  8247. // Plus sign handling
  8248. else if (c == '+') {
  8249. if (space_as_plus) {
  8250. result += "%2B";
  8251. } else {
  8252. result += static_cast<char>(c);
  8253. }
  8254. }
  8255. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8256. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8257. c == '*' || c == ',' || c == ';') {
  8258. result += static_cast<char>(c);
  8259. }
  8260. // Colon and @ are allowed in query
  8261. else if (c == ':' || c == '@') {
  8262. result += static_cast<char>(c);
  8263. }
  8264. // Forward slash is allowed in query values
  8265. else if (c == '/') {
  8266. result += static_cast<char>(c);
  8267. }
  8268. // Question mark is allowed in query values (after first ?)
  8269. else if (c == '?') {
  8270. result += static_cast<char>(c);
  8271. } else {
  8272. result += '%';
  8273. char hex[3];
  8274. snprintf(hex, sizeof(hex), "%02X", c);
  8275. result.append(hex, 2);
  8276. }
  8277. }
  8278. return result;
  8279. }
  8280. inline std::string decode_query_component(const std::string &component,
  8281. bool plus_as_space) {
  8282. std::string result;
  8283. result.reserve(component.size());
  8284. for (size_t i = 0; i < component.size(); i++) {
  8285. if (component[i] == '%' && i + 2 < component.size()) {
  8286. auto val = 0;
  8287. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8288. result += static_cast<char>(val);
  8289. i += 2;
  8290. } else {
  8291. result += component[i];
  8292. }
  8293. } else if (component[i] == '+' && plus_as_space) {
  8294. result += ' '; // + becomes space in form-urlencoded
  8295. } else {
  8296. result += component[i];
  8297. }
  8298. }
  8299. return result;
  8300. }
  8301. inline std::string sanitize_filename(const std::string &filename) {
  8302. // Extract basename: find the last path separator (/ or \)
  8303. auto pos = filename.find_last_of("/\\");
  8304. auto result =
  8305. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8306. // Strip null bytes
  8307. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8308. // Trim whitespace
  8309. {
  8310. auto start = result.find_first_not_of(" \t");
  8311. auto end = result.find_last_not_of(" \t");
  8312. result = (start == std::string::npos)
  8313. ? ""
  8314. : result.substr(start, end - start + 1);
  8315. }
  8316. // Reject . and ..
  8317. if (result == "." || result == "..") { return ""; }
  8318. return result;
  8319. }
  8320. inline std::string append_query_params(const std::string &path,
  8321. const Params &params) {
  8322. std::string path_with_query = path;
  8323. thread_local const std::regex re("[^?]+\\?.*");
  8324. auto delm = std::regex_match(path, re) ? '&' : '?';
  8325. path_with_query += delm + detail::params_to_query_str(params);
  8326. return path_with_query;
  8327. }
  8328. // Header utilities
  8329. inline std::pair<std::string, std::string>
  8330. make_range_header(const Ranges &ranges) {
  8331. std::string field = "bytes=";
  8332. auto i = 0;
  8333. for (const auto &r : ranges) {
  8334. if (i != 0) { field += ", "; }
  8335. if (r.first != -1) { field += std::to_string(r.first); }
  8336. field += '-';
  8337. if (r.second != -1) { field += std::to_string(r.second); }
  8338. i++;
  8339. }
  8340. return std::make_pair("Range", std::move(field));
  8341. }
  8342. inline std::pair<std::string, std::string>
  8343. make_basic_authentication_header(const std::string &username,
  8344. const std::string &password, bool is_proxy) {
  8345. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8346. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8347. return std::make_pair(key, std::move(field));
  8348. }
  8349. inline std::pair<std::string, std::string>
  8350. make_bearer_token_authentication_header(const std::string &token,
  8351. bool is_proxy = false) {
  8352. auto field = "Bearer " + token;
  8353. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8354. return std::make_pair(key, std::move(field));
  8355. }
  8356. // Request implementation
  8357. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8358. size_t id) const {
  8359. return detail::get_header_value_u64(headers, key, def, id);
  8360. }
  8361. inline bool Request::has_header(const std::string &key) const {
  8362. return detail::has_header(headers, key);
  8363. }
  8364. inline std::string Request::get_header_value(const std::string &key,
  8365. const char *def, size_t id) const {
  8366. return detail::get_header_value(headers, key, def, id);
  8367. }
  8368. inline size_t Request::get_header_value_count(const std::string &key) const {
  8369. return detail::get_header_value_count(headers, key);
  8370. }
  8371. inline void Request::set_header(const std::string &key,
  8372. const std::string &val) {
  8373. detail::set_header(headers, key, val);
  8374. }
  8375. inline bool Request::has_trailer(const std::string &key) const {
  8376. return trailers.find(key) != trailers.end();
  8377. }
  8378. inline std::string Request::get_trailer_value(const std::string &key,
  8379. size_t id) const {
  8380. return detail::get_multimap_value(trailers, key, id);
  8381. }
  8382. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8383. auto r = trailers.equal_range(key);
  8384. return static_cast<size_t>(std::distance(r.first, r.second));
  8385. }
  8386. inline bool Request::has_param(const std::string &key) const {
  8387. return params.find(key) != params.end();
  8388. }
  8389. inline std::string Request::get_param_value(const std::string &key,
  8390. size_t id) const {
  8391. return detail::get_multimap_value(params, key, id);
  8392. }
  8393. inline std::vector<std::string>
  8394. Request::get_param_values(const std::string &key) const {
  8395. auto rng = params.equal_range(key);
  8396. std::vector<std::string> values;
  8397. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8398. for (auto it = rng.first; it != rng.second; ++it) {
  8399. values.push_back(it->second);
  8400. }
  8401. return values;
  8402. }
  8403. inline size_t Request::get_param_value_count(const std::string &key) const {
  8404. auto r = params.equal_range(key);
  8405. return static_cast<size_t>(std::distance(r.first, r.second));
  8406. }
  8407. inline bool Request::is_multipart_form_data() const {
  8408. const auto &content_type = get_header_value("Content-Type");
  8409. return detail::extract_media_type(content_type) == "multipart/form-data";
  8410. }
  8411. // Multipart FormData implementation
  8412. inline std::string MultipartFormData::get_field(const std::string &key,
  8413. size_t id) const {
  8414. auto rng = fields.equal_range(key);
  8415. auto it = rng.first;
  8416. std::advance(it, static_cast<ssize_t>(id));
  8417. if (it != rng.second) { return it->second.content; }
  8418. return std::string();
  8419. }
  8420. inline std::vector<std::string>
  8421. MultipartFormData::get_fields(const std::string &key) const {
  8422. std::vector<std::string> values;
  8423. auto rng = fields.equal_range(key);
  8424. for (auto it = rng.first; it != rng.second; it++) {
  8425. values.push_back(it->second.content);
  8426. }
  8427. return values;
  8428. }
  8429. inline bool MultipartFormData::has_field(const std::string &key) const {
  8430. return fields.find(key) != fields.end();
  8431. }
  8432. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8433. auto r = fields.equal_range(key);
  8434. return static_cast<size_t>(std::distance(r.first, r.second));
  8435. }
  8436. inline FormData MultipartFormData::get_file(const std::string &key,
  8437. size_t id) const {
  8438. return detail::get_multimap_value(files, key, id);
  8439. }
  8440. inline std::vector<FormData>
  8441. MultipartFormData::get_files(const std::string &key) const {
  8442. std::vector<FormData> values;
  8443. auto rng = files.equal_range(key);
  8444. for (auto it = rng.first; it != rng.second; it++) {
  8445. values.push_back(it->second);
  8446. }
  8447. return values;
  8448. }
  8449. inline bool MultipartFormData::has_file(const std::string &key) const {
  8450. return files.find(key) != files.end();
  8451. }
  8452. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8453. auto r = files.equal_range(key);
  8454. return static_cast<size_t>(std::distance(r.first, r.second));
  8455. }
  8456. // Multipart FormData writer implementation
  8457. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8458. return detail::is_multipart_boundary_chars_valid(boundary);
  8459. }
  8460. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8461. : boundary_(detail::make_multipart_data_boundary()) {}
  8462. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8463. : boundary_(std::move(boundary)) {}
  8464. inline const std::string &MultipartFormDataWriter::boundary() const {
  8465. return boundary_;
  8466. }
  8467. inline std::string MultipartFormDataWriter::content_type() const {
  8468. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8469. }
  8470. inline std::string
  8471. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8472. return detail::serialize_multipart_formdata(items, boundary_);
  8473. }
  8474. inline size_t MultipartFormDataWriter::content_length(
  8475. const UploadFormDataItems &items) const {
  8476. return detail::get_multipart_content_length(items, boundary_);
  8477. }
  8478. inline std::string
  8479. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8480. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8481. }
  8482. inline std::string MultipartFormDataWriter::item_end() {
  8483. return detail::serialize_multipart_formdata_item_end();
  8484. }
  8485. inline std::string MultipartFormDataWriter::finish() const {
  8486. return detail::serialize_multipart_formdata_finish(boundary_);
  8487. }
  8488. // Response implementation
  8489. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8490. size_t id) const {
  8491. return detail::get_header_value_u64(headers, key, def, id);
  8492. }
  8493. inline bool Response::has_header(const std::string &key) const {
  8494. return headers.find(key) != headers.end();
  8495. }
  8496. inline std::string Response::get_header_value(const std::string &key,
  8497. const char *def,
  8498. size_t id) const {
  8499. return detail::get_header_value(headers, key, def, id);
  8500. }
  8501. inline size_t Response::get_header_value_count(const std::string &key) const {
  8502. return detail::get_header_value_count(headers, key);
  8503. }
  8504. inline void Response::set_header(const std::string &key,
  8505. const std::string &val) {
  8506. detail::set_header(headers, key, val);
  8507. }
  8508. inline bool Response::has_trailer(const std::string &key) const {
  8509. return trailers.find(key) != trailers.end();
  8510. }
  8511. inline std::string Response::get_trailer_value(const std::string &key,
  8512. size_t id) const {
  8513. return detail::get_multimap_value(trailers, key, id);
  8514. }
  8515. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8516. auto r = trailers.equal_range(key);
  8517. return static_cast<size_t>(std::distance(r.first, r.second));
  8518. }
  8519. inline void Response::set_redirect(const std::string &url, int stat) {
  8520. if (detail::fields::is_field_value(url)) {
  8521. set_header("Location", url);
  8522. if (300 <= stat && stat < 400) {
  8523. this->status = stat;
  8524. } else {
  8525. this->status = StatusCode::Found_302;
  8526. }
  8527. }
  8528. }
  8529. inline void Response::set_content(const char *s, size_t n,
  8530. const std::string &content_type) {
  8531. body.assign(s, n);
  8532. auto rng = headers.equal_range("Content-Type");
  8533. headers.erase(rng.first, rng.second);
  8534. set_header("Content-Type", content_type);
  8535. }
  8536. inline void Response::set_content(const std::string &s,
  8537. const std::string &content_type) {
  8538. set_content(s.data(), s.size(), content_type);
  8539. }
  8540. inline void Response::set_content(std::string &&s,
  8541. const std::string &content_type) {
  8542. body = std::move(s);
  8543. auto rng = headers.equal_range("Content-Type");
  8544. headers.erase(rng.first, rng.second);
  8545. set_header("Content-Type", content_type);
  8546. }
  8547. inline void Response::set_content_provider(
  8548. size_t in_length, const std::string &content_type, ContentProvider provider,
  8549. ContentProviderResourceReleaser resource_releaser) {
  8550. set_header("Content-Type", content_type);
  8551. content_length_ = in_length;
  8552. if (in_length > 0) { content_provider_ = std::move(provider); }
  8553. content_provider_resource_releaser_ = std::move(resource_releaser);
  8554. is_chunked_content_provider_ = false;
  8555. }
  8556. inline void Response::set_content_provider(
  8557. const std::string &content_type, ContentProviderWithoutLength provider,
  8558. ContentProviderResourceReleaser resource_releaser) {
  8559. set_header("Content-Type", content_type);
  8560. content_length_ = 0;
  8561. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8562. content_provider_resource_releaser_ = std::move(resource_releaser);
  8563. is_chunked_content_provider_ = false;
  8564. }
  8565. inline void Response::set_chunked_content_provider(
  8566. const std::string &content_type, ContentProviderWithoutLength provider,
  8567. ContentProviderResourceReleaser resource_releaser) {
  8568. set_header("Content-Type", content_type);
  8569. content_length_ = 0;
  8570. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8571. content_provider_resource_releaser_ = std::move(resource_releaser);
  8572. is_chunked_content_provider_ = true;
  8573. }
  8574. inline void Response::set_file_content(const std::string &path,
  8575. const std::string &content_type) {
  8576. file_content_path_ = path;
  8577. file_content_content_type_ = content_type;
  8578. }
  8579. inline void Response::set_file_content(const std::string &path) {
  8580. file_content_path_ = path;
  8581. }
  8582. // Result implementation
  8583. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8584. size_t def,
  8585. size_t id) const {
  8586. return detail::get_header_value_u64(request_headers_, key, def, id);
  8587. }
  8588. inline bool Result::has_request_header(const std::string &key) const {
  8589. return request_headers_.find(key) != request_headers_.end();
  8590. }
  8591. inline std::string Result::get_request_header_value(const std::string &key,
  8592. const char *def,
  8593. size_t id) const {
  8594. return detail::get_header_value(request_headers_, key, def, id);
  8595. }
  8596. inline size_t
  8597. Result::get_request_header_value_count(const std::string &key) const {
  8598. auto r = request_headers_.equal_range(key);
  8599. return static_cast<size_t>(std::distance(r.first, r.second));
  8600. }
  8601. // Stream implementation
  8602. inline ssize_t Stream::write(const char *ptr) {
  8603. return write(ptr, strlen(ptr));
  8604. }
  8605. inline ssize_t Stream::write(const std::string &s) {
  8606. return write(s.data(), s.size());
  8607. }
  8608. // BodyReader implementation
  8609. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8610. if (!stream) {
  8611. last_error = Error::Connection;
  8612. return -1;
  8613. }
  8614. if (eof) { return 0; }
  8615. if (!chunked) {
  8616. // Content-Length based reading
  8617. if (has_content_length && bytes_read >= content_length) {
  8618. eof = true;
  8619. return 0;
  8620. }
  8621. auto to_read = len;
  8622. if (has_content_length) {
  8623. auto remaining = content_length - bytes_read;
  8624. to_read = (std::min)(len, remaining);
  8625. }
  8626. auto n = stream->read(buf, to_read);
  8627. if (n < 0) {
  8628. last_error = stream->get_error();
  8629. if (last_error == Error::Success) { last_error = Error::Read; }
  8630. eof = true;
  8631. return n;
  8632. }
  8633. if (n == 0) {
  8634. // Unexpected EOF before content_length
  8635. last_error = stream->get_error();
  8636. if (last_error == Error::Success) { last_error = Error::Read; }
  8637. eof = true;
  8638. return 0;
  8639. }
  8640. bytes_read += static_cast<size_t>(n);
  8641. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8642. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8643. last_error = Error::ExceedMaxPayloadSize;
  8644. eof = true;
  8645. return -1;
  8646. }
  8647. return n;
  8648. }
  8649. // Chunked transfer encoding: delegate to shared decoder instance.
  8650. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8651. size_t chunk_offset = 0;
  8652. size_t chunk_total = 0;
  8653. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8654. if (n < 0) {
  8655. last_error = stream->get_error();
  8656. if (last_error == Error::Success) { last_error = Error::Read; }
  8657. eof = true;
  8658. return n;
  8659. }
  8660. if (n == 0) {
  8661. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8662. eof = true;
  8663. return 0;
  8664. }
  8665. bytes_read += static_cast<size_t>(n);
  8666. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8667. last_error = Error::ExceedMaxPayloadSize;
  8668. eof = true;
  8669. return -1;
  8670. }
  8671. return n;
  8672. }
  8673. // ThreadPool implementation
  8674. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8675. time_t idle_timeout_sec)
  8676. : base_thread_count_(n), max_queued_requests_(mqr),
  8677. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8678. shutdown_(false) {
  8679. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8680. if (max_n != 0 && max_n < n) {
  8681. std::string msg = "max_threads must be >= base_threads";
  8682. throw std::invalid_argument(msg);
  8683. }
  8684. #endif
  8685. max_thread_count_ = max_n == 0 ? n : max_n;
  8686. threads_.reserve(base_thread_count_);
  8687. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8688. try {
  8689. #endif
  8690. for (size_t i = 0; i < base_thread_count_; i++) {
  8691. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8692. }
  8693. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8694. } catch (...) {
  8695. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8696. // signal the workers we already spawned to exit and join them so the
  8697. // vector destructor does not see joinable threads (which would call
  8698. // std::terminate). Then rethrow so the caller learns of the failure.
  8699. {
  8700. std::unique_lock<std::mutex> lock(mutex_);
  8701. shutdown_ = true;
  8702. }
  8703. cond_.notify_all();
  8704. for (auto &t : threads_) {
  8705. if (t.joinable()) { t.join(); }
  8706. }
  8707. throw;
  8708. }
  8709. #endif
  8710. }
  8711. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8712. {
  8713. std::unique_lock<std::mutex> lock(mutex_);
  8714. if (shutdown_) { return false; }
  8715. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8716. return false;
  8717. }
  8718. jobs_.push_back(std::move(fn));
  8719. // Spawn a dynamic thread if no idle threads and under max
  8720. if (idle_thread_count_ == 0 &&
  8721. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8722. cleanup_finished_threads();
  8723. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8724. }
  8725. }
  8726. cond_.notify_one();
  8727. return true;
  8728. }
  8729. inline void ThreadPool::shutdown() {
  8730. {
  8731. std::unique_lock<std::mutex> lock(mutex_);
  8732. shutdown_ = true;
  8733. }
  8734. cond_.notify_all();
  8735. for (auto &t : threads_) {
  8736. if (t.joinable()) { t.join(); }
  8737. }
  8738. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8739. // with worker threads that call move_to_finished() concurrently.
  8740. std::list<std::thread> remaining_dynamic;
  8741. {
  8742. std::unique_lock<std::mutex> lock(mutex_);
  8743. remaining_dynamic = std::move(dynamic_threads_);
  8744. }
  8745. for (auto &t : remaining_dynamic) {
  8746. if (t.joinable()) { t.join(); }
  8747. }
  8748. std::unique_lock<std::mutex> lock(mutex_);
  8749. cleanup_finished_threads();
  8750. }
  8751. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8752. // Must be called with mutex_ held
  8753. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8754. if (it->get_id() == id) {
  8755. finished_threads_.push_back(std::move(*it));
  8756. dynamic_threads_.erase(it);
  8757. return;
  8758. }
  8759. }
  8760. }
  8761. inline void ThreadPool::cleanup_finished_threads() {
  8762. // Must be called with mutex_ held
  8763. for (auto &t : finished_threads_) {
  8764. if (t.joinable()) { t.join(); }
  8765. }
  8766. finished_threads_.clear();
  8767. }
  8768. inline void ThreadPool::worker(bool is_dynamic) {
  8769. for (;;) {
  8770. std::function<void()> fn;
  8771. {
  8772. std::unique_lock<std::mutex> lock(mutex_);
  8773. idle_thread_count_++;
  8774. if (is_dynamic) {
  8775. auto has_work =
  8776. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8777. [&] { return !jobs_.empty() || shutdown_; });
  8778. if (!has_work) {
  8779. // Timed out with no work - exit this dynamic thread
  8780. idle_thread_count_--;
  8781. move_to_finished(std::this_thread::get_id());
  8782. break;
  8783. }
  8784. } else {
  8785. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8786. }
  8787. idle_thread_count_--;
  8788. if (shutdown_ && jobs_.empty()) { break; }
  8789. fn = std::move(jobs_.front());
  8790. jobs_.pop_front();
  8791. }
  8792. assert(true == static_cast<bool>(fn));
  8793. fn();
  8794. }
  8795. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8796. !defined(LIBRESSL_VERSION_NUMBER)
  8797. OPENSSL_thread_stop();
  8798. #endif
  8799. }
  8800. /*
  8801. * Group 1 (continued): detail namespace - Stream implementations
  8802. */
  8803. namespace detail {
  8804. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8805. time_t timeout_sec, time_t timeout_usec,
  8806. time_t &actual_timeout_sec,
  8807. time_t &actual_timeout_usec) {
  8808. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8809. auto actual_timeout_msec =
  8810. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8811. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8812. actual_timeout_sec = actual_timeout_msec / 1000;
  8813. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8814. }
  8815. // Socket stream implementation
  8816. inline SocketStream::SocketStream(
  8817. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8818. time_t write_timeout_sec, time_t write_timeout_usec,
  8819. time_t max_timeout_msec,
  8820. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8821. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8822. read_timeout_usec_(read_timeout_usec),
  8823. write_timeout_sec_(write_timeout_sec),
  8824. write_timeout_usec_(write_timeout_usec),
  8825. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8826. read_buff_(read_buff_size_, 0) {}
  8827. inline SocketStream::~SocketStream() = default;
  8828. inline bool SocketStream::is_readable() const {
  8829. return read_buff_off_ < read_buff_content_size_;
  8830. }
  8831. inline bool SocketStream::wait_readable() const {
  8832. if (max_timeout_msec_ <= 0) {
  8833. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8834. }
  8835. time_t read_timeout_sec;
  8836. time_t read_timeout_usec;
  8837. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8838. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8839. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8840. }
  8841. inline bool SocketStream::wait_writable() const {
  8842. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8843. }
  8844. inline bool SocketStream::is_peer_alive() const {
  8845. return detail::is_socket_alive(sock_);
  8846. }
  8847. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8848. #ifdef _WIN32
  8849. size =
  8850. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8851. #else
  8852. size = (std::min)(size,
  8853. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8854. #endif
  8855. if (read_buff_off_ < read_buff_content_size_) {
  8856. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8857. if (size <= remaining_size) {
  8858. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8859. read_buff_off_ += size;
  8860. return static_cast<ssize_t>(size);
  8861. } else {
  8862. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8863. read_buff_off_ += remaining_size;
  8864. return static_cast<ssize_t>(remaining_size);
  8865. }
  8866. }
  8867. if (!wait_readable()) {
  8868. error_ = Error::Timeout;
  8869. return -1;
  8870. }
  8871. read_buff_off_ = 0;
  8872. read_buff_content_size_ = 0;
  8873. if (size < read_buff_size_) {
  8874. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8875. CPPHTTPLIB_RECV_FLAGS);
  8876. if (n <= 0) {
  8877. if (n == 0) {
  8878. error_ = Error::ConnectionClosed;
  8879. } else {
  8880. error_ = Error::Read;
  8881. }
  8882. return n;
  8883. } else if (n <= static_cast<ssize_t>(size)) {
  8884. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8885. return n;
  8886. } else {
  8887. memcpy(ptr, read_buff_.data(), size);
  8888. read_buff_off_ = size;
  8889. read_buff_content_size_ = static_cast<size_t>(n);
  8890. return static_cast<ssize_t>(size);
  8891. }
  8892. } else {
  8893. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8894. if (n <= 0) {
  8895. if (n == 0) {
  8896. error_ = Error::ConnectionClosed;
  8897. } else {
  8898. error_ = Error::Read;
  8899. }
  8900. }
  8901. return n;
  8902. }
  8903. }
  8904. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8905. if (!wait_writable()) { return -1; }
  8906. #if defined(_WIN32) && !defined(_WIN64)
  8907. size =
  8908. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8909. #endif
  8910. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8911. }
  8912. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8913. int &port) const {
  8914. return detail::get_remote_ip_and_port(sock_, ip, port);
  8915. }
  8916. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8917. int &port) const {
  8918. return detail::get_local_ip_and_port(sock_, ip, port);
  8919. }
  8920. inline socket_t SocketStream::socket() const { return sock_; }
  8921. inline time_t SocketStream::duration() const {
  8922. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8923. std::chrono::steady_clock::now() - start_time_)
  8924. .count();
  8925. }
  8926. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8927. read_timeout_sec_ = sec;
  8928. read_timeout_usec_ = usec;
  8929. }
  8930. // Buffer stream implementation
  8931. inline bool BufferStream::is_readable() const { return true; }
  8932. inline bool BufferStream::wait_readable() const { return true; }
  8933. inline bool BufferStream::wait_writable() const { return true; }
  8934. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8935. #if defined(_MSC_VER) && _MSC_VER < 1910
  8936. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8937. #else
  8938. auto len_read = buffer.copy(ptr, size, position);
  8939. #endif
  8940. position += static_cast<size_t>(len_read);
  8941. return static_cast<ssize_t>(len_read);
  8942. }
  8943. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8944. buffer.append(ptr, size);
  8945. return static_cast<ssize_t>(size);
  8946. }
  8947. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8948. int & /*port*/) const {}
  8949. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8950. int & /*port*/) const {}
  8951. inline socket_t BufferStream::socket() const { return 0; }
  8952. inline time_t BufferStream::duration() const { return 0; }
  8953. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8954. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8955. : MatcherBase(pattern) {
  8956. constexpr const char marker[] = "/:";
  8957. // One past the last ending position of a path param substring
  8958. std::size_t last_param_end = 0;
  8959. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8960. // Needed to ensure that parameter names are unique during matcher
  8961. // construction
  8962. // If exceptions are disabled, only last duplicate path
  8963. // parameter will be set
  8964. std::unordered_set<std::string> param_name_set;
  8965. #endif
  8966. while (true) {
  8967. const auto marker_pos = pattern.find(
  8968. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8969. if (marker_pos == std::string::npos) { break; }
  8970. static_fragments_.push_back(
  8971. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8972. const auto param_name_start = marker_pos + str_len(marker);
  8973. auto sep_pos = pattern.find(separator, param_name_start);
  8974. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8975. auto param_name =
  8976. pattern.substr(param_name_start, sep_pos - param_name_start);
  8977. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8978. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8979. std::string msg = "Encountered path parameter '" + param_name +
  8980. "' multiple times in route pattern '" + pattern + "'.";
  8981. throw std::invalid_argument(msg);
  8982. }
  8983. #endif
  8984. param_names_.push_back(std::move(param_name));
  8985. last_param_end = sep_pos + 1;
  8986. }
  8987. if (last_param_end < pattern.length()) {
  8988. static_fragments_.push_back(pattern.substr(last_param_end));
  8989. }
  8990. }
  8991. inline bool PathParamsMatcher::match(Request &request) const {
  8992. request.matches = std::smatch();
  8993. request.path_params.clear();
  8994. request.path_params.reserve(param_names_.size());
  8995. // One past the position at which the path matched the pattern last time
  8996. std::size_t starting_pos = 0;
  8997. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8998. const auto &fragment = static_fragments_[i];
  8999. if (starting_pos + fragment.length() > request.path.length()) {
  9000. return false;
  9001. }
  9002. // Avoid unnecessary allocation by using strncmp instead of substr +
  9003. // comparison
  9004. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  9005. fragment.length()) != 0) {
  9006. return false;
  9007. }
  9008. starting_pos += fragment.length();
  9009. // Should only happen when we have a static fragment after a param
  9010. // Example: '/users/:id/subscriptions'
  9011. // The 'subscriptions' fragment here does not have a corresponding param
  9012. if (i >= param_names_.size()) { continue; }
  9013. auto sep_pos = request.path.find(separator, starting_pos);
  9014. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  9015. const auto &param_name = param_names_[i];
  9016. request.path_params.emplace(
  9017. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  9018. // Mark everything up to '/' as matched
  9019. starting_pos = sep_pos + 1;
  9020. }
  9021. // Returns false if the path is longer than the pattern
  9022. return starting_pos >= request.path.length();
  9023. }
  9024. inline bool RegexMatcher::match(Request &request) const {
  9025. request.path_params.clear();
  9026. return std::regex_match(request.path, request.matches, regex_);
  9027. }
  9028. // Enclose IPv6 address in brackets if needed
  9029. inline std::string prepare_host_string(const std::string &host) {
  9030. // Enclose IPv6 address in brackets (but not if already enclosed)
  9031. if (host.find(':') == std::string::npos ||
  9032. (!host.empty() && host[0] == '[')) {
  9033. // IPv4, hostname, or already bracketed IPv6
  9034. return host;
  9035. } else {
  9036. // IPv6 address without brackets
  9037. return "[" + host + "]";
  9038. }
  9039. }
  9040. inline std::string make_host_and_port_string(const std::string &host, int port,
  9041. bool is_ssl) {
  9042. auto result = prepare_host_string(host);
  9043. // Append port if not default
  9044. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9045. ; // do nothing
  9046. } else {
  9047. result += ":" + std::to_string(port);
  9048. }
  9049. return result;
  9050. }
  9051. // Create "host:port" string always including port number (for CONNECT method)
  9052. inline std::string
  9053. make_host_and_port_string_always_port(const std::string &host, int port) {
  9054. return prepare_host_string(host) + ":" + std::to_string(port);
  9055. }
  9056. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9057. NormalizedTarget normalize_target(const std::string &host);
  9058. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9059. bool host_matches_no_proxy(const NormalizedTarget &target,
  9060. const std::vector<NoProxyEntry> &entries);
  9061. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9062. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9063. if (prefix_bits == 0) { return true; }
  9064. int full_bytes = prefix_bits / 8;
  9065. int rem_bits = prefix_bits % 8;
  9066. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9067. static_cast<size_t>(full_bytes)) != 0) {
  9068. return false;
  9069. }
  9070. if (rem_bits == 0) { return true; }
  9071. auto i = static_cast<size_t>(full_bytes);
  9072. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9073. return (ip[i] & mask) == (net[i] & mask);
  9074. }
  9075. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9076. if (token.empty()) { return false; }
  9077. if (token == "*") {
  9078. out.kind = NoProxyKind::Wildcard;
  9079. return true;
  9080. }
  9081. auto slash = token.find('/');
  9082. std::string addr_part =
  9083. (slash == std::string::npos) ? token : token.substr(0, slash);
  9084. std::string prefix_part =
  9085. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9086. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9087. // don't silently treat it as a /32 (or /128).
  9088. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9089. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9090. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9091. // when brackets are present.
  9092. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9093. addr_part.back() == ']';
  9094. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9095. if (!bracketed) {
  9096. struct in_addr v4;
  9097. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9098. int prefix = 32;
  9099. if (!prefix_part.empty()) {
  9100. auto r = from_chars(prefix_part.data(),
  9101. prefix_part.data() + prefix_part.size(), prefix);
  9102. if (r.ec != std::errc{} ||
  9103. r.ptr != prefix_part.data() + prefix_part.size()) {
  9104. return false;
  9105. }
  9106. if (prefix < 0 || prefix > 32) { return false; }
  9107. }
  9108. out.kind = NoProxyKind::IPv4Cidr;
  9109. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9110. out.prefix_bits = prefix;
  9111. return true;
  9112. }
  9113. }
  9114. struct in6_addr v6;
  9115. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9116. int prefix = 128;
  9117. if (!prefix_part.empty()) {
  9118. auto r = from_chars(prefix_part.data(),
  9119. prefix_part.data() + prefix_part.size(), prefix);
  9120. if (r.ec != std::errc{} ||
  9121. r.ptr != prefix_part.data() + prefix_part.size()) {
  9122. return false;
  9123. }
  9124. if (prefix < 0 || prefix > 128) { return false; }
  9125. }
  9126. out.kind = NoProxyKind::IPv6Cidr;
  9127. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9128. out.prefix_bits = prefix;
  9129. return true;
  9130. }
  9131. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9132. // the entry is malformed — don't fall through to the hostname branch.
  9133. if (bracketed) { return false; }
  9134. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9135. if (slash != std::string::npos) { return false; }
  9136. // Port-specific entries (host:port) are not supported.
  9137. if (token.find(':') != std::string::npos) { return false; }
  9138. std::string hostname = case_ignore::to_lower(token);
  9139. while (!hostname.empty() && hostname.front() == '.') {
  9140. hostname.erase(hostname.begin());
  9141. }
  9142. while (!hostname.empty() && hostname.back() == '.') {
  9143. hostname.pop_back();
  9144. }
  9145. if (hostname.empty()) { return false; }
  9146. out.kind = NoProxyKind::HostnameSuffix;
  9147. out.hostname_pattern = std::move(hostname);
  9148. return true;
  9149. }
  9150. inline NormalizedTarget normalize_target(const std::string &host) {
  9151. NormalizedTarget t;
  9152. std::string h = host;
  9153. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9154. h = h.substr(1, h.size() - 2);
  9155. }
  9156. // Strip a single trailing dot so "example.com." canonicalizes to
  9157. // "example.com".
  9158. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9159. t.hostname = case_ignore::to_lower(h);
  9160. if (!t.hostname.empty()) {
  9161. struct in_addr v4;
  9162. struct in6_addr v6;
  9163. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9164. t.is_ipv4 = true;
  9165. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9166. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9167. t.is_ipv6 = true;
  9168. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9169. }
  9170. }
  9171. return t;
  9172. }
  9173. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9174. const std::vector<NoProxyEntry> &entries) {
  9175. if (target.hostname.empty()) { return false; }
  9176. for (const auto &e : entries) {
  9177. switch (e.kind) {
  9178. case NoProxyKind::Wildcard: return true;
  9179. case NoProxyKind::IPv4Cidr:
  9180. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9181. return true;
  9182. }
  9183. break;
  9184. case NoProxyKind::IPv6Cidr:
  9185. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9186. return true;
  9187. }
  9188. break;
  9189. case NoProxyKind::HostnameSuffix:
  9190. if (target.is_ipv4 || target.is_ipv6) { break; }
  9191. if (target.hostname == e.hostname_pattern) { return true; }
  9192. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9193. // an entry of "example.com".
  9194. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9195. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9196. if (target.hostname[offset - 1] == '.' &&
  9197. target.hostname.compare(offset, e.hostname_pattern.size(),
  9198. e.hostname_pattern) == 0) {
  9199. return true;
  9200. }
  9201. }
  9202. break;
  9203. }
  9204. }
  9205. return false;
  9206. }
  9207. template <typename T>
  9208. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9209. T header_writer, Error &error) {
  9210. for (const auto &h : headers) {
  9211. if (!detail::fields::is_field_name(h.first) ||
  9212. !detail::fields::is_field_value(h.second)) {
  9213. error = Error::InvalidHeaders;
  9214. return false;
  9215. }
  9216. }
  9217. if (header_writer(strm, headers) <= 0) {
  9218. error = Error::Write;
  9219. return false;
  9220. }
  9221. return true;
  9222. }
  9223. } // namespace detail
  9224. /*
  9225. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9226. */
  9227. #ifdef CPPHTTPLIB_SSL_ENABLED
  9228. namespace detail {
  9229. // SSL socket stream implementation
  9230. inline SSLSocketStream::SSLSocketStream(
  9231. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9232. time_t read_timeout_usec, time_t write_timeout_sec,
  9233. time_t write_timeout_usec, time_t max_timeout_msec,
  9234. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9235. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9236. read_timeout_usec_(read_timeout_usec),
  9237. write_timeout_sec_(write_timeout_sec),
  9238. write_timeout_usec_(write_timeout_usec),
  9239. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9241. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9242. // Note: create_session() also clears this, but SSLClient currently
  9243. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9244. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9245. // SSL session was created.
  9246. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9247. #endif
  9248. }
  9249. inline SSLSocketStream::~SSLSocketStream() = default;
  9250. inline bool SSLSocketStream::is_readable() const {
  9251. return tls::pending(session_) > 0;
  9252. }
  9253. inline bool SSLSocketStream::wait_readable() const {
  9254. if (max_timeout_msec_ <= 0) {
  9255. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9256. }
  9257. time_t read_timeout_sec;
  9258. time_t read_timeout_usec;
  9259. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9260. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9261. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9262. }
  9263. inline bool SSLSocketStream::wait_writable() const {
  9264. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9265. !tls::is_peer_closed(session_, sock_);
  9266. }
  9267. inline bool SSLSocketStream::is_peer_alive() const {
  9268. return !tls::is_peer_closed(session_, sock_);
  9269. }
  9270. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9271. if (tls::pending(session_) > 0) {
  9272. tls::TlsError err;
  9273. auto ret = tls::read(session_, ptr, size, err);
  9274. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9275. error_ = Error::ConnectionClosed;
  9276. }
  9277. return ret;
  9278. } else if (wait_readable()) {
  9279. tls::TlsError err;
  9280. auto ret = tls::read(session_, ptr, size, err);
  9281. if (ret < 0) {
  9282. auto n = 1000;
  9283. #ifdef _WIN32
  9284. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9285. (err.code == tls::ErrorCode::SyscallError &&
  9286. WSAGetLastError() == WSAETIMEDOUT))) {
  9287. #else
  9288. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9289. #endif
  9290. if (tls::pending(session_) > 0) {
  9291. return tls::read(session_, ptr, size, err);
  9292. } else if (wait_readable()) {
  9293. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9294. ret = tls::read(session_, ptr, size, err);
  9295. if (ret >= 0) { return ret; }
  9296. } else {
  9297. break;
  9298. }
  9299. }
  9300. assert(ret < 0);
  9301. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9302. error_ = Error::ConnectionClosed;
  9303. }
  9304. return ret;
  9305. } else {
  9306. error_ = Error::Timeout;
  9307. return -1;
  9308. }
  9309. }
  9310. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9311. if (wait_writable()) {
  9312. auto handle_size =
  9313. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9314. tls::TlsError err;
  9315. auto ret = tls::write(session_, ptr, handle_size, err);
  9316. if (ret < 0) {
  9317. auto n = 1000;
  9318. #ifdef _WIN32
  9319. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9320. (err.code == tls::ErrorCode::SyscallError &&
  9321. WSAGetLastError() == WSAETIMEDOUT))) {
  9322. #else
  9323. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9324. #endif
  9325. if (wait_writable()) {
  9326. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9327. ret = tls::write(session_, ptr, handle_size, err);
  9328. if (ret >= 0) { return ret; }
  9329. } else {
  9330. break;
  9331. }
  9332. }
  9333. assert(ret < 0);
  9334. }
  9335. return ret;
  9336. }
  9337. return -1;
  9338. }
  9339. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9340. int &port) const {
  9341. detail::get_remote_ip_and_port(sock_, ip, port);
  9342. }
  9343. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9344. int &port) const {
  9345. detail::get_local_ip_and_port(sock_, ip, port);
  9346. }
  9347. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9348. inline time_t SSLSocketStream::duration() const {
  9349. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9350. std::chrono::steady_clock::now() - start_time_)
  9351. .count();
  9352. }
  9353. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9354. read_timeout_sec_ = sec;
  9355. read_timeout_usec_ = usec;
  9356. }
  9357. } // namespace detail
  9358. #endif // CPPHTTPLIB_SSL_ENABLED
  9359. /*
  9360. * Group 4: Server implementation
  9361. */
  9362. // HTTP server implementation
  9363. inline Server::Server()
  9364. : new_task_queue([] {
  9365. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9366. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9367. }) {
  9368. #ifndef _WIN32
  9369. signal(SIGPIPE, SIG_IGN);
  9370. #endif
  9371. }
  9372. inline Server::~Server() = default;
  9373. inline std::unique_ptr<detail::MatcherBase>
  9374. Server::make_matcher(const std::string &pattern) {
  9375. if (pattern.find("/:") != std::string::npos) {
  9376. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9377. } else {
  9378. return detail::make_unique<detail::RegexMatcher>(pattern);
  9379. }
  9380. }
  9381. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9382. return add_handler(get_handlers_, pattern, std::move(handler));
  9383. }
  9384. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9385. return add_handler(post_handlers_, pattern, std::move(handler));
  9386. }
  9387. inline Server &Server::Post(const std::string &pattern,
  9388. HandlerWithContentReader handler) {
  9389. return add_handler(post_handlers_for_content_reader_, pattern,
  9390. std::move(handler));
  9391. }
  9392. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9393. return add_handler(put_handlers_, pattern, std::move(handler));
  9394. }
  9395. inline Server &Server::Put(const std::string &pattern,
  9396. HandlerWithContentReader handler) {
  9397. return add_handler(put_handlers_for_content_reader_, pattern,
  9398. std::move(handler));
  9399. }
  9400. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9401. return add_handler(patch_handlers_, pattern, std::move(handler));
  9402. }
  9403. inline Server &Server::Patch(const std::string &pattern,
  9404. HandlerWithContentReader handler) {
  9405. return add_handler(patch_handlers_for_content_reader_, pattern,
  9406. std::move(handler));
  9407. }
  9408. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9409. return add_handler(delete_handlers_, pattern, std::move(handler));
  9410. }
  9411. inline Server &Server::Delete(const std::string &pattern,
  9412. HandlerWithContentReader handler) {
  9413. return add_handler(delete_handlers_for_content_reader_, pattern,
  9414. std::move(handler));
  9415. }
  9416. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9417. return add_handler(options_handlers_, pattern, std::move(handler));
  9418. }
  9419. inline Server &Server::WebSocket(const std::string &pattern,
  9420. WebSocketHandler handler) {
  9421. websocket_handlers_.push_back(
  9422. {make_matcher(pattern), std::move(handler), nullptr});
  9423. return *this;
  9424. }
  9425. inline Server &Server::WebSocket(const std::string &pattern,
  9426. WebSocketHandler handler,
  9427. SubProtocolSelector sub_protocol_selector) {
  9428. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9429. std::move(sub_protocol_selector)});
  9430. return *this;
  9431. }
  9432. inline bool Server::set_base_dir(const std::string &dir,
  9433. const std::string &mount_point) {
  9434. return set_mount_point(mount_point, dir);
  9435. }
  9436. inline bool Server::set_mount_point(const std::string &mount_point,
  9437. const std::string &dir, Headers headers) {
  9438. detail::FileStat stat(dir);
  9439. if (stat.is_dir()) {
  9440. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9441. if (!mnt.empty() && mnt[0] == '/') {
  9442. std::string resolved_base;
  9443. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9444. #if defined(_WIN32)
  9445. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9446. resolved_base += '\\';
  9447. }
  9448. #else
  9449. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9450. #endif
  9451. }
  9452. base_dirs_.push_back(
  9453. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9454. return true;
  9455. }
  9456. }
  9457. return false;
  9458. }
  9459. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9460. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9461. if (it->mount_point == mount_point) {
  9462. base_dirs_.erase(it);
  9463. return true;
  9464. }
  9465. }
  9466. return false;
  9467. }
  9468. inline Server &
  9469. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9470. const std::string &mime) {
  9471. file_extension_and_mimetype_map_[ext] = mime;
  9472. return *this;
  9473. }
  9474. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9475. default_file_mimetype_ = mime;
  9476. return *this;
  9477. }
  9478. inline Server &Server::set_file_request_handler(Handler handler) {
  9479. file_request_handler_ = std::move(handler);
  9480. return *this;
  9481. }
  9482. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9483. std::true_type) {
  9484. error_handler_ = std::move(handler);
  9485. return *this;
  9486. }
  9487. inline Server &Server::set_error_handler_core(Handler handler,
  9488. std::false_type) {
  9489. error_handler_ = [handler](const Request &req, Response &res) {
  9490. handler(req, res);
  9491. return HandlerResponse::Handled;
  9492. };
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9496. exception_handler_ = std::move(handler);
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9500. pre_routing_handler_ = std::move(handler);
  9501. return *this;
  9502. }
  9503. inline Server &Server::set_post_routing_handler(Handler handler) {
  9504. post_routing_handler_ = std::move(handler);
  9505. return *this;
  9506. }
  9507. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9508. pre_request_handler_ = std::move(handler);
  9509. return *this;
  9510. }
  9511. inline Server &Server::set_logger(Logger logger) {
  9512. logger_ = std::move(logger);
  9513. return *this;
  9514. }
  9515. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9516. error_logger_ = std::move(error_logger);
  9517. return *this;
  9518. }
  9519. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9520. pre_compression_logger_ = std::move(logger);
  9521. return *this;
  9522. }
  9523. inline Server &
  9524. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9525. expect_100_continue_handler_ = std::move(handler);
  9526. return *this;
  9527. }
  9528. inline Server &Server::set_start_handler(StartHandler handler) {
  9529. start_handler_ = std::move(handler);
  9530. return *this;
  9531. }
  9532. inline Server &Server::set_address_family(int family) {
  9533. address_family_ = family;
  9534. return *this;
  9535. }
  9536. inline Server &Server::set_tcp_nodelay(bool on) {
  9537. tcp_nodelay_ = on;
  9538. return *this;
  9539. }
  9540. inline Server &Server::set_ipv6_v6only(bool on) {
  9541. ipv6_v6only_ = on;
  9542. return *this;
  9543. }
  9544. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9545. socket_options_ = std::move(socket_options);
  9546. return *this;
  9547. }
  9548. inline Server &Server::set_default_headers(Headers headers) {
  9549. default_headers_ = std::move(headers);
  9550. return *this;
  9551. }
  9552. inline Server &Server::set_header_writer(
  9553. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9554. header_writer_ = writer;
  9555. return *this;
  9556. }
  9557. inline Server &
  9558. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9559. trusted_proxies_ = proxies;
  9560. return *this;
  9561. }
  9562. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9563. keep_alive_max_count_ = count;
  9564. return *this;
  9565. }
  9566. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9567. keep_alive_timeout_sec_ = sec;
  9568. return *this;
  9569. }
  9570. template <class Rep, class Period>
  9571. inline Server &Server::set_keep_alive_timeout(
  9572. const std::chrono::duration<Rep, Period> &duration) {
  9573. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9574. set_keep_alive_timeout(sec);
  9575. });
  9576. return *this;
  9577. }
  9578. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9579. read_timeout_sec_ = sec;
  9580. read_timeout_usec_ = usec;
  9581. return *this;
  9582. }
  9583. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9584. write_timeout_sec_ = sec;
  9585. write_timeout_usec_ = usec;
  9586. return *this;
  9587. }
  9588. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9589. idle_interval_sec_ = sec;
  9590. idle_interval_usec_ = usec;
  9591. return *this;
  9592. }
  9593. inline Server &Server::set_payload_max_length(size_t length) {
  9594. payload_max_length_ = length;
  9595. return *this;
  9596. }
  9597. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9598. websocket_max_missed_pongs_ = count;
  9599. return *this;
  9600. }
  9601. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9602. websocket_ping_interval_sec_ = sec;
  9603. return *this;
  9604. }
  9605. template <class Rep, class Period>
  9606. inline Server &Server::set_websocket_ping_interval(
  9607. const std::chrono::duration<Rep, Period> &duration) {
  9608. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9609. set_websocket_ping_interval(sec);
  9610. });
  9611. return *this;
  9612. }
  9613. inline bool Server::bind_to_port(const std::string &host, int port,
  9614. int socket_flags) {
  9615. auto ret = bind_internal(host, port, socket_flags);
  9616. if (ret == -1) { is_decommissioned = true; }
  9617. return ret >= 0;
  9618. }
  9619. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9620. auto ret = bind_internal(host, 0, socket_flags);
  9621. if (ret == -1) { is_decommissioned = true; }
  9622. return ret;
  9623. }
  9624. inline bool Server::listen_after_bind() { return listen_internal(); }
  9625. inline bool Server::listen(const std::string &host, int port,
  9626. int socket_flags) {
  9627. return bind_to_port(host, port, socket_flags) && listen_internal();
  9628. }
  9629. inline bool Server::is_running() const { return is_running_; }
  9630. inline void Server::wait_until_ready() const {
  9631. while (!is_running_ && !is_decommissioned) {
  9632. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9633. }
  9634. }
  9635. inline void Server::stop() noexcept {
  9636. if (is_running_) {
  9637. assert(svr_sock_ != INVALID_SOCKET);
  9638. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9639. detail::shutdown_socket(sock);
  9640. detail::close_socket(sock);
  9641. }
  9642. is_decommissioned = false;
  9643. }
  9644. inline void Server::decommission() { is_decommissioned = true; }
  9645. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9646. auto len = strlen(s);
  9647. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9648. len -= 2;
  9649. {
  9650. size_t count = 0;
  9651. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9652. switch (count) {
  9653. case 0: req.method = std::string(b, e); break;
  9654. case 1: req.target = std::string(b, e); break;
  9655. case 2: req.version = std::string(b, e); break;
  9656. default: break;
  9657. }
  9658. count++;
  9659. });
  9660. if (count != 3) { return false; }
  9661. }
  9662. thread_local const std::set<std::string> methods{
  9663. "GET", "HEAD", "POST", "PUT", "DELETE",
  9664. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9665. if (methods.find(req.method) == methods.end()) {
  9666. output_error_log(Error::InvalidHTTPMethod, &req);
  9667. return false;
  9668. }
  9669. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9670. output_error_log(Error::InvalidHTTPVersion, &req);
  9671. return false;
  9672. }
  9673. {
  9674. // Skip URL fragment
  9675. for (size_t i = 0; i < req.target.size(); i++) {
  9676. if (req.target[i] == '#') {
  9677. req.target.erase(i);
  9678. break;
  9679. }
  9680. }
  9681. detail::divide(req.target, '?',
  9682. [&](const char *lhs_data, std::size_t lhs_size,
  9683. const char *rhs_data, std::size_t rhs_size) {
  9684. req.path =
  9685. decode_path_component(std::string(lhs_data, lhs_size));
  9686. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9687. });
  9688. }
  9689. return true;
  9690. }
  9691. inline bool Server::write_response(Stream &strm, bool close_connection,
  9692. Request &req, Response &res) {
  9693. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9694. // incorrectly to the error content.
  9695. req.ranges.clear();
  9696. return write_response_core(strm, close_connection, req, res, false);
  9697. }
  9698. inline bool Server::write_response_with_content(Stream &strm,
  9699. bool close_connection,
  9700. const Request &req,
  9701. Response &res) {
  9702. return write_response_core(strm, close_connection, req, res, true);
  9703. }
  9704. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9705. const Request &req, Response &res,
  9706. bool need_apply_ranges) {
  9707. assert(res.status != -1);
  9708. if (400 <= res.status && error_handler_ &&
  9709. error_handler_(req, res) == HandlerResponse::Handled) {
  9710. need_apply_ranges = true;
  9711. }
  9712. std::string content_type;
  9713. std::string boundary;
  9714. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9715. // Prepare additional headers
  9716. if (close_connection || req.get_header_value("Connection") == "close" ||
  9717. 400 <= res.status) { // Don't leave connections open after errors
  9718. res.set_header("Connection", "close");
  9719. } else {
  9720. std::string s = "timeout=";
  9721. s += std::to_string(keep_alive_timeout_sec_);
  9722. s += ", max=";
  9723. s += std::to_string(keep_alive_max_count_);
  9724. res.set_header("Keep-Alive", s);
  9725. }
  9726. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9727. !res.has_header("Content-Type")) {
  9728. res.set_header("Content-Type", "text/plain");
  9729. }
  9730. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9731. !res.has_header("Content-Length")) {
  9732. res.set_header("Content-Length", "0");
  9733. }
  9734. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9735. res.set_header("Accept-Ranges", "bytes");
  9736. }
  9737. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9738. // Response line and headers
  9739. detail::BufferStream bstrm;
  9740. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9741. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9742. // Combine small body with headers to reduce write syscalls
  9743. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9744. bstrm.write(res.body.data(), res.body.size());
  9745. }
  9746. // Log before writing to avoid race condition with client-side code that
  9747. // accesses logger-captured data immediately after receiving the response.
  9748. output_log(req, res);
  9749. // Flush buffer
  9750. auto &data = bstrm.get_buffer();
  9751. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9752. // Streaming body
  9753. auto ret = true;
  9754. if (req.method != "HEAD" && res.content_provider_) {
  9755. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9756. res.content_provider_success_ = true;
  9757. } else {
  9758. ret = false;
  9759. }
  9760. }
  9761. return ret;
  9762. }
  9763. inline bool
  9764. Server::write_content_with_provider(Stream &strm, const Request &req,
  9765. Response &res, const std::string &boundary,
  9766. const std::string &content_type) {
  9767. auto is_shutting_down = [this]() {
  9768. return this->svr_sock_ == INVALID_SOCKET;
  9769. };
  9770. if (res.content_length_ > 0) {
  9771. if (req.ranges.empty()) {
  9772. return detail::write_content(strm, res.content_provider_, 0,
  9773. res.content_length_, is_shutting_down);
  9774. } else if (req.ranges.size() == 1) {
  9775. auto offset_and_length = detail::get_range_offset_and_length(
  9776. req.ranges[0], res.content_length_);
  9777. return detail::write_content(strm, res.content_provider_,
  9778. offset_and_length.first,
  9779. offset_and_length.second, is_shutting_down);
  9780. } else {
  9781. return detail::write_multipart_ranges_data(
  9782. strm, req, res, boundary, content_type, res.content_length_,
  9783. is_shutting_down);
  9784. }
  9785. } else {
  9786. if (res.is_chunked_content_provider_) {
  9787. auto type = detail::encoding_type(req, res);
  9788. auto compressor = detail::make_compressor(type);
  9789. if (!compressor) {
  9790. compressor = detail::make_unique<detail::nocompressor>();
  9791. }
  9792. return detail::write_content_chunked(strm, res.content_provider_,
  9793. is_shutting_down, *compressor);
  9794. } else {
  9795. return detail::write_content_without_length(strm, res.content_provider_,
  9796. is_shutting_down);
  9797. }
  9798. }
  9799. }
  9800. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9801. FormFields::iterator cur_field;
  9802. FormFiles::iterator cur_file;
  9803. auto is_text_field = false;
  9804. size_t count = 0;
  9805. if (read_content_core(
  9806. strm, req, res,
  9807. // Regular
  9808. [&](const char *buf, size_t n) {
  9809. // Prevent arithmetic overflow when checking sizes.
  9810. // Avoid computing (req.body.size() + n) directly because
  9811. // adding two unsigned `size_t` values can wrap around and
  9812. // produce a small result instead of indicating overflow.
  9813. // Instead, check using subtraction: ensure `n` does not
  9814. // exceed the remaining capacity `max_size() - size()`.
  9815. if (req.body.size() >= req.body.max_size() ||
  9816. n > req.body.max_size() - req.body.size()) {
  9817. return false;
  9818. }
  9819. // Limit decompressed body size to payload_max_length_ to protect
  9820. // against "zip bomb" attacks where a small compressed payload
  9821. // decompresses to a massive size.
  9822. if (payload_max_length_ > 0 &&
  9823. (req.body.size() >= payload_max_length_ ||
  9824. n > payload_max_length_ - req.body.size())) {
  9825. return false;
  9826. }
  9827. req.body.append(buf, n);
  9828. return true;
  9829. },
  9830. // Multipart FormData
  9831. [&](const FormData &file) {
  9832. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9833. output_error_log(Error::TooManyFormDataFiles, &req);
  9834. return false;
  9835. }
  9836. if (file.filename.empty()) {
  9837. cur_field = req.form.fields.emplace(
  9838. file.name, FormField{file.name, file.content, file.headers});
  9839. is_text_field = true;
  9840. } else {
  9841. cur_file = req.form.files.emplace(file.name, file);
  9842. is_text_field = false;
  9843. }
  9844. return true;
  9845. },
  9846. [&](const char *buf, size_t n) {
  9847. if (is_text_field) {
  9848. auto &content = cur_field->second.content;
  9849. if (content.size() + n > content.max_size()) { return false; }
  9850. content.append(buf, n);
  9851. } else {
  9852. auto &content = cur_file->second.content;
  9853. if (content.size() + n > content.max_size()) { return false; }
  9854. content.append(buf, n);
  9855. }
  9856. return true;
  9857. })) {
  9858. const auto &content_type = req.get_header_value("Content-Type");
  9859. if (detail::extract_media_type(content_type) ==
  9860. "application/x-www-form-urlencoded") {
  9861. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9862. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9863. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9864. return false;
  9865. }
  9866. detail::parse_query_text(req.body, req.params);
  9867. }
  9868. return true;
  9869. }
  9870. return false;
  9871. }
  9872. inline bool Server::read_content_with_content_receiver(
  9873. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9874. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9875. return read_content_core(strm, req, res, std::move(receiver),
  9876. std::move(multipart_header),
  9877. std::move(multipart_receiver));
  9878. }
  9879. inline bool Server::read_content_core(
  9880. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9881. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9882. detail::FormDataParser multipart_form_data_parser;
  9883. ContentReceiverWithProgress out;
  9884. if (req.is_multipart_form_data()) {
  9885. const auto &content_type = req.get_header_value("Content-Type");
  9886. std::string boundary;
  9887. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9888. res.status = StatusCode::BadRequest_400;
  9889. output_error_log(Error::MultipartParsing, &req);
  9890. return false;
  9891. }
  9892. multipart_form_data_parser.set_boundary(std::move(boundary));
  9893. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9894. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9895. multipart_receiver);
  9896. };
  9897. } else {
  9898. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9899. size_t /*len*/) { return receiver(buf, n); };
  9900. }
  9901. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9902. // For non-SSL builds we still scan non-persistent connections for stray
  9903. // body bytes so the payload limit is enforced (413). On keep-alive,
  9904. // pending bytes may be the next request (issue #2450), so skip.
  9905. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9906. if (!req.has_header("Content-Length") &&
  9907. !detail::is_chunked_transfer_encoding(req.headers)) {
  9908. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9909. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9910. auto has_data = strm.is_readable();
  9911. if (!has_data) {
  9912. auto s = strm.socket();
  9913. if (s != INVALID_SOCKET) {
  9914. has_data = detail::select_read(s, 0, 0) > 0;
  9915. }
  9916. }
  9917. if (has_data) {
  9918. auto result =
  9919. detail::read_content_without_length(strm, payload_max_length_, out);
  9920. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9921. res.status = StatusCode::PayloadTooLarge_413;
  9922. return false;
  9923. } else if (result != detail::ReadContentResult::Success) {
  9924. return false;
  9925. }
  9926. return true;
  9927. }
  9928. }
  9929. return true;
  9930. }
  9931. #else
  9932. if (!req.has_header("Content-Length") &&
  9933. !detail::is_chunked_transfer_encoding(req.headers)) {
  9934. return true;
  9935. }
  9936. #endif
  9937. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9938. out, true)) {
  9939. return false;
  9940. }
  9941. req.body_consumed_ = true;
  9942. if (req.is_multipart_form_data()) {
  9943. if (!multipart_form_data_parser.is_valid()) {
  9944. res.status = StatusCode::BadRequest_400;
  9945. output_error_log(Error::MultipartParsing, &req);
  9946. return false;
  9947. }
  9948. }
  9949. return true;
  9950. }
  9951. inline bool Server::handle_file_request(Request &req, Response &res) {
  9952. for (const auto &entry : base_dirs_) {
  9953. // Prefix match
  9954. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9955. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9956. if (detail::is_valid_path(sub_path)) {
  9957. auto path = entry.base_dir + sub_path;
  9958. if (path.back() == '/') { path += "index.html"; }
  9959. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9960. // but symlinks/junctions can still escape the base directory.
  9961. if (!entry.resolved_base_dir.empty()) {
  9962. std::string resolved_path;
  9963. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9964. !detail::is_path_within_base(resolved_path,
  9965. entry.resolved_base_dir)) {
  9966. res.status = StatusCode::Forbidden_403;
  9967. return true;
  9968. }
  9969. }
  9970. detail::FileStat stat(path);
  9971. if (stat.is_dir()) {
  9972. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9973. return true;
  9974. }
  9975. if (stat.is_file()) {
  9976. for (const auto &kv : entry.headers) {
  9977. res.set_header(kv.first, kv.second);
  9978. }
  9979. auto etag = detail::compute_etag(stat);
  9980. if (!etag.empty()) { res.set_header("ETag", etag); }
  9981. auto mtime = stat.mtime();
  9982. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9983. if (!last_modified.empty()) {
  9984. res.set_header("Last-Modified", last_modified);
  9985. }
  9986. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9987. check_if_range(req, etag, mtime);
  9988. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9989. if (!mm->is_open()) {
  9990. output_error_log(Error::OpenFile, &req);
  9991. return false;
  9992. }
  9993. res.set_content_provider(
  9994. mm->size(),
  9995. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9996. default_file_mimetype_),
  9997. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9998. sink.write(mm->data() + offset, length);
  9999. return true;
  10000. });
  10001. if (req.method != "HEAD" && file_request_handler_) {
  10002. file_request_handler_(req, res);
  10003. }
  10004. return true;
  10005. } else {
  10006. output_error_log(Error::OpenFile, &req);
  10007. }
  10008. }
  10009. }
  10010. }
  10011. return false;
  10012. }
  10013. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  10014. const std::string &etag,
  10015. time_t mtime) const {
  10016. // Handle conditional GET:
  10017. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  10018. // 2. If-Modified-Since is checked only when If-None-Match is absent
  10019. if (req.has_header("If-None-Match")) {
  10020. if (!etag.empty()) {
  10021. auto val = req.get_header_value("If-None-Match");
  10022. // NOTE: We use exact string matching here. This works correctly
  10023. // because our server always generates weak ETags (W/"..."), and
  10024. // clients typically send back the same ETag they received.
  10025. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  10026. // If-None-Match, where W/"x" and "x" would match, but this
  10027. // simplified implementation requires exact matches.
  10028. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  10029. [&](const char *b, const char *e) {
  10030. auto seg_len = static_cast<size_t>(e - b);
  10031. return (seg_len == 1 && *b == '*') ||
  10032. (seg_len == etag.size() &&
  10033. std::equal(b, e, etag.begin()));
  10034. });
  10035. if (ret) {
  10036. res.status = StatusCode::NotModified_304;
  10037. return true;
  10038. }
  10039. }
  10040. } else if (req.has_header("If-Modified-Since")) {
  10041. auto val = req.get_header_value("If-Modified-Since");
  10042. auto t = detail::parse_http_date(val);
  10043. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10044. res.status = StatusCode::NotModified_304;
  10045. return true;
  10046. }
  10047. }
  10048. return false;
  10049. }
  10050. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10051. time_t mtime) const {
  10052. // Handle If-Range for partial content requests (RFC 9110
  10053. // Section 13.1.5). If-Range is only evaluated when Range header is
  10054. // present. If the validator matches, serve partial content; otherwise
  10055. // serve full content.
  10056. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10057. auto val = req.get_header_value("If-Range");
  10058. auto is_valid_range = [&]() {
  10059. if (detail::is_strong_etag(val)) {
  10060. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10061. // comparison.
  10062. return (!etag.empty() && val == etag);
  10063. } else if (detail::is_weak_etag(val)) {
  10064. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10065. return false;
  10066. } else {
  10067. // HTTP-date comparison
  10068. auto t = detail::parse_http_date(val);
  10069. return (t != static_cast<time_t>(-1) && mtime <= t);
  10070. }
  10071. };
  10072. if (!is_valid_range()) {
  10073. // Validator doesn't match: ignore Range and serve full content
  10074. req.ranges.clear();
  10075. return false;
  10076. }
  10077. }
  10078. return true;
  10079. }
  10080. inline socket_t
  10081. Server::create_server_socket(const std::string &host, int port,
  10082. int socket_flags,
  10083. SocketOptions socket_options) const {
  10084. return detail::create_socket(
  10085. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10086. ipv6_v6only_, std::move(socket_options),
  10087. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10088. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10089. output_error_log(Error::BindIPAddress, nullptr);
  10090. return false;
  10091. }
  10092. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10093. output_error_log(Error::Listen, nullptr);
  10094. return false;
  10095. }
  10096. return true;
  10097. });
  10098. }
  10099. inline int Server::bind_internal(const std::string &host, int port,
  10100. int socket_flags) {
  10101. if (is_decommissioned) { return -1; }
  10102. if (!is_valid()) { return -1; }
  10103. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10104. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10105. if (port == 0) {
  10106. struct sockaddr_storage addr;
  10107. socklen_t addr_len = sizeof(addr);
  10108. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10109. &addr_len) == -1) {
  10110. output_error_log(Error::GetSockName, nullptr);
  10111. return -1;
  10112. }
  10113. if (addr.ss_family == AF_INET) {
  10114. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10115. } else if (addr.ss_family == AF_INET6) {
  10116. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10117. } else {
  10118. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10119. return -1;
  10120. }
  10121. } else {
  10122. return port;
  10123. }
  10124. }
  10125. inline bool Server::listen_internal() {
  10126. if (is_decommissioned) { return false; }
  10127. auto ret = true;
  10128. is_running_ = true;
  10129. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10130. if (start_handler_) { start_handler_(); }
  10131. {
  10132. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10133. while (svr_sock_ != INVALID_SOCKET) {
  10134. #ifndef _WIN32
  10135. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10136. #endif
  10137. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10138. idle_interval_usec_);
  10139. if (val == 0) { // Timeout
  10140. task_queue->on_idle();
  10141. continue;
  10142. }
  10143. #ifndef _WIN32
  10144. }
  10145. #endif
  10146. #if defined _WIN32
  10147. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10148. // OVERLAPPED
  10149. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10150. #elif defined SOCK_CLOEXEC
  10151. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10152. #else
  10153. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10154. #endif
  10155. if (sock == INVALID_SOCKET) {
  10156. if (errno == EMFILE) {
  10157. // The per-process limit of open file descriptors has been reached.
  10158. // Try to accept new connections after a short sleep.
  10159. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10160. continue;
  10161. } else if (errno == EINTR || errno == EAGAIN) {
  10162. continue;
  10163. }
  10164. if (svr_sock_ != INVALID_SOCKET) {
  10165. detail::close_socket(svr_sock_);
  10166. ret = false;
  10167. output_error_log(Error::Connection, nullptr);
  10168. } else {
  10169. ; // The server socket was closed by user.
  10170. }
  10171. break;
  10172. }
  10173. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10174. read_timeout_sec_, read_timeout_usec_);
  10175. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10176. write_timeout_sec_, write_timeout_usec_);
  10177. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10178. if (!task_queue->enqueue(
  10179. [this, sock]() { process_and_close_socket(sock); })) {
  10180. output_error_log(Error::ResourceExhaustion, nullptr);
  10181. detail::shutdown_socket(sock);
  10182. detail::close_socket(sock);
  10183. }
  10184. }
  10185. task_queue->shutdown();
  10186. }
  10187. is_decommissioned = !ret;
  10188. return ret;
  10189. }
  10190. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10191. if (pre_routing_handler_ &&
  10192. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10193. return true;
  10194. }
  10195. // File handler
  10196. if ((req.method == "GET" || req.method == "HEAD") &&
  10197. handle_file_request(req, res)) {
  10198. return true;
  10199. }
  10200. if (detail::expect_content(req)) {
  10201. // Content reader handler
  10202. {
  10203. // Track whether the ContentReader was aborted due to the decompressed
  10204. // payload exceeding `payload_max_length_`.
  10205. // The user handler runs after the lambda returns, so we must restore the
  10206. // 413 status if the handler overwrites it.
  10207. bool content_reader_payload_too_large = false;
  10208. ContentReader reader(
  10209. [&](ContentReceiver receiver) {
  10210. auto result = read_content_with_content_receiver(
  10211. strm, req, res, std::move(receiver), nullptr, nullptr);
  10212. if (!result) {
  10213. output_error_log(Error::Read, &req);
  10214. if (res.status == StatusCode::PayloadTooLarge_413) {
  10215. content_reader_payload_too_large = true;
  10216. }
  10217. }
  10218. return result;
  10219. },
  10220. [&](FormDataHeader header, ContentReceiver receiver) {
  10221. auto result = read_content_with_content_receiver(
  10222. strm, req, res, nullptr, std::move(header),
  10223. std::move(receiver));
  10224. if (!result) {
  10225. output_error_log(Error::Read, &req);
  10226. if (res.status == StatusCode::PayloadTooLarge_413) {
  10227. content_reader_payload_too_large = true;
  10228. }
  10229. }
  10230. return result;
  10231. });
  10232. bool dispatched = false;
  10233. if (req.method == "POST") {
  10234. dispatched = dispatch_request_for_content_reader(
  10235. req, res, std::move(reader), post_handlers_for_content_reader_);
  10236. } else if (req.method == "PUT") {
  10237. dispatched = dispatch_request_for_content_reader(
  10238. req, res, std::move(reader), put_handlers_for_content_reader_);
  10239. } else if (req.method == "PATCH") {
  10240. dispatched = dispatch_request_for_content_reader(
  10241. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10242. } else if (req.method == "DELETE") {
  10243. dispatched = dispatch_request_for_content_reader(
  10244. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10245. }
  10246. if (dispatched) {
  10247. if (content_reader_payload_too_large) {
  10248. // Enforce the limit: override any status the handler may have set
  10249. // and return false so the error path sends a plain 413 response.
  10250. res.status = StatusCode::PayloadTooLarge_413;
  10251. res.body.clear();
  10252. res.content_length_ = 0;
  10253. res.content_provider_ = nullptr;
  10254. return false;
  10255. }
  10256. return true;
  10257. }
  10258. }
  10259. // NOTE: `req.body` is not read here. For a regular handler the body is
  10260. // read inside dispatch_request(), after the route has matched and the
  10261. // pre-request handler has approved the request, so that a rejected
  10262. // request (e.g. failed authentication) never forces us to buffer a
  10263. // potentially large body.
  10264. }
  10265. // Regular handler
  10266. if (req.method == "GET" || req.method == "HEAD") {
  10267. return dispatch_request(req, res, get_handlers_, strm);
  10268. } else if (req.method == "POST") {
  10269. return dispatch_request(req, res, post_handlers_, strm);
  10270. } else if (req.method == "PUT") {
  10271. return dispatch_request(req, res, put_handlers_, strm);
  10272. } else if (req.method == "DELETE") {
  10273. return dispatch_request(req, res, delete_handlers_, strm);
  10274. } else if (req.method == "OPTIONS") {
  10275. return dispatch_request(req, res, options_handlers_, strm);
  10276. } else if (req.method == "PATCH") {
  10277. return dispatch_request(req, res, patch_handlers_, strm);
  10278. }
  10279. res.status = StatusCode::BadRequest_400;
  10280. return false;
  10281. }
  10282. inline bool Server::dispatch_request(Request &req, Response &res,
  10283. const Handlers &handlers, Stream &strm) {
  10284. for (const auto &x : handlers) {
  10285. const auto &matcher = x.first;
  10286. const auto &handler = x.second;
  10287. if (matcher->match(req)) {
  10288. req.matched_route = matcher->pattern();
  10289. // Run the pre-request handler before reading the body so a rejected
  10290. // request (e.g. failed authentication) never forces us to buffer a
  10291. // potentially large body. `req.matched_route` is available here.
  10292. if (pre_request_handler_ &&
  10293. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10294. return true;
  10295. }
  10296. // The route matched and the request was approved; read the body now.
  10297. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10298. output_error_log(Error::Read, &req);
  10299. return false;
  10300. }
  10301. handler(req, res);
  10302. return true;
  10303. }
  10304. }
  10305. return false;
  10306. }
  10307. inline void Server::apply_ranges(const Request &req, Response &res,
  10308. std::string &content_type,
  10309. std::string &boundary) const {
  10310. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10311. auto it = res.headers.find("Content-Type");
  10312. if (it != res.headers.end()) {
  10313. content_type = it->second;
  10314. res.headers.erase(it);
  10315. }
  10316. boundary = detail::make_multipart_data_boundary();
  10317. res.set_header("Content-Type",
  10318. "multipart/byteranges; boundary=" + boundary);
  10319. }
  10320. auto type = detail::encoding_type(req, res);
  10321. if (res.body.empty()) {
  10322. if (res.content_length_ > 0) {
  10323. size_t length = 0;
  10324. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10325. length = res.content_length_;
  10326. } else if (req.ranges.size() == 1) {
  10327. auto offset_and_length = detail::get_range_offset_and_length(
  10328. req.ranges[0], res.content_length_);
  10329. length = offset_and_length.second;
  10330. auto content_range = detail::make_content_range_header_field(
  10331. offset_and_length, res.content_length_);
  10332. res.set_header("Content-Range", content_range);
  10333. } else {
  10334. length = detail::get_multipart_ranges_data_length(
  10335. req, boundary, content_type, res.content_length_);
  10336. }
  10337. res.set_header("Content-Length", std::to_string(length));
  10338. } else {
  10339. if (res.content_provider_) {
  10340. if (res.is_chunked_content_provider_) {
  10341. res.set_header("Transfer-Encoding", "chunked");
  10342. if (type != detail::EncodingType::None) {
  10343. res.set_header("Content-Encoding", detail::encoding_name(type));
  10344. res.set_header("Vary", "Accept-Encoding");
  10345. }
  10346. }
  10347. }
  10348. }
  10349. } else {
  10350. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10351. ;
  10352. } else if (req.ranges.size() == 1) {
  10353. auto offset_and_length =
  10354. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10355. auto offset = offset_and_length.first;
  10356. auto length = offset_and_length.second;
  10357. auto content_range = detail::make_content_range_header_field(
  10358. offset_and_length, res.body.size());
  10359. res.set_header("Content-Range", content_range);
  10360. assert(offset + length <= res.body.size());
  10361. res.body = res.body.substr(offset, length);
  10362. } else {
  10363. std::string data;
  10364. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10365. res.body.size(), data);
  10366. res.body.swap(data);
  10367. }
  10368. if (type != detail::EncodingType::None) {
  10369. output_pre_compression_log(req, res);
  10370. if (auto compressor = detail::make_compressor(type)) {
  10371. std::string compressed;
  10372. if (compressor->compress(res.body.data(), res.body.size(), true,
  10373. [&](const char *data, size_t data_len) {
  10374. compressed.append(data, data_len);
  10375. return true;
  10376. })) {
  10377. res.body.swap(compressed);
  10378. res.set_header("Content-Encoding", detail::encoding_name(type));
  10379. res.set_header("Vary", "Accept-Encoding");
  10380. }
  10381. }
  10382. }
  10383. res.content_length_ = res.body.size();
  10384. res.set_header("Content-Length", std::to_string(res.content_length_));
  10385. }
  10386. }
  10387. inline bool Server::dispatch_request_for_content_reader(
  10388. Request &req, Response &res, ContentReader content_reader,
  10389. const HandlersForContentReader &handlers) const {
  10390. for (const auto &x : handlers) {
  10391. const auto &matcher = x.first;
  10392. const auto &handler = x.second;
  10393. if (matcher->match(req)) {
  10394. req.matched_route = matcher->pattern();
  10395. if (!pre_request_handler_ ||
  10396. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10397. handler(req, res, content_reader);
  10398. }
  10399. return true;
  10400. }
  10401. }
  10402. return false;
  10403. }
  10404. inline std::string
  10405. get_client_ip(const std::string &x_forwarded_for,
  10406. const std::vector<std::string> &trusted_proxies) {
  10407. // X-Forwarded-For is a comma-separated list per RFC 7239
  10408. std::vector<std::string> ip_list;
  10409. detail::split(x_forwarded_for.data(),
  10410. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10411. [&](const char *b, const char *e) {
  10412. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10413. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10414. });
  10415. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10416. // no segments. Signal "no client IP derived" with an empty string so the
  10417. // caller can fall back to the connection-level remote address.
  10418. if (ip_list.empty()) { return std::string(); }
  10419. for (size_t i = 0; i < ip_list.size(); ++i) {
  10420. auto ip = ip_list[i];
  10421. auto is_trusted_proxy =
  10422. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10423. [&](const std::string &proxy) { return ip == proxy; });
  10424. if (is_trusted_proxy) {
  10425. if (i == 0) {
  10426. // If the trusted proxy is the first IP, there's no preceding client IP
  10427. return ip;
  10428. } else {
  10429. // Return the IP immediately before the trusted proxy
  10430. return ip_list[i - 1];
  10431. }
  10432. }
  10433. }
  10434. // If no trusted proxy is found, return the first IP in the list
  10435. return ip_list.front();
  10436. }
  10437. inline bool
  10438. Server::process_request(Stream &strm, const std::string &remote_addr,
  10439. int remote_port, const std::string &local_addr,
  10440. int local_port, bool close_connection,
  10441. bool &connection_closed,
  10442. const std::function<void(Request &)> &setup_request,
  10443. bool *websocket_upgraded) {
  10444. std::array<char, 2048> buf{};
  10445. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10446. // Connection has been closed on client
  10447. if (!line_reader.getline()) { return false; }
  10448. Request req;
  10449. req.start_time_ = std::chrono::steady_clock::now();
  10450. req.remote_addr = remote_addr;
  10451. req.remote_port = remote_port;
  10452. req.local_addr = local_addr;
  10453. req.local_port = local_port;
  10454. Response res;
  10455. res.version = "HTTP/1.1";
  10456. res.headers = default_headers_;
  10457. // Request line and headers
  10458. if (!parse_request_line(line_reader.ptr(), req)) {
  10459. res.status = StatusCode::BadRequest_400;
  10460. output_error_log(Error::InvalidRequestLine, &req);
  10461. return write_response(strm, close_connection, req, res);
  10462. }
  10463. // Request headers
  10464. if (!detail::read_headers(strm, req.headers)) {
  10465. res.status = StatusCode::BadRequest_400;
  10466. output_error_log(Error::InvalidHeaders, &req);
  10467. return write_response(strm, close_connection, req, res);
  10468. }
  10469. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10470. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10471. // tolerated for compatibility with existing clients.
  10472. if (req.get_header_value_u64("Content-Length") > 0 &&
  10473. req.has_header("Transfer-Encoding")) {
  10474. connection_closed = true;
  10475. res.status = StatusCode::BadRequest_400;
  10476. return write_response(strm, close_connection, req, res);
  10477. }
  10478. // Check if the request URI doesn't exceed the limit
  10479. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10480. connection_closed = true;
  10481. res.status = StatusCode::UriTooLong_414;
  10482. output_error_log(Error::ExceedUriMaxLength, &req);
  10483. return write_response(strm, close_connection, req, res);
  10484. }
  10485. if (req.get_header_value("Connection") == "close") {
  10486. connection_closed = true;
  10487. }
  10488. if (req.version == "HTTP/1.0" &&
  10489. req.get_header_value("Connection") != "Keep-Alive") {
  10490. connection_closed = true;
  10491. }
  10492. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10493. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10494. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10495. req.remote_addr = derived.empty() ? remote_addr : derived;
  10496. } else {
  10497. req.remote_addr = remote_addr;
  10498. }
  10499. req.remote_port = remote_port;
  10500. req.local_addr = local_addr;
  10501. req.local_port = local_port;
  10502. if (req.has_header("Accept")) {
  10503. const auto &accept_header = req.get_header_value("Accept");
  10504. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10505. connection_closed = true;
  10506. res.status = StatusCode::BadRequest_400;
  10507. output_error_log(Error::HTTPParsing, &req);
  10508. return write_response(strm, close_connection, req, res);
  10509. }
  10510. }
  10511. if (req.has_header("Range")) {
  10512. const auto &range_header_value = req.get_header_value("Range");
  10513. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10514. connection_closed = true;
  10515. res.status = StatusCode::RangeNotSatisfiable_416;
  10516. output_error_log(Error::InvalidRangeHeader, &req);
  10517. return write_response(strm, close_connection, req, res);
  10518. }
  10519. }
  10520. if (setup_request) { setup_request(req); }
  10521. if (req.get_header_value("Expect") == "100-continue") {
  10522. int status = StatusCode::Continue_100;
  10523. if (expect_100_continue_handler_) {
  10524. status = expect_100_continue_handler_(req, res);
  10525. }
  10526. switch (status) {
  10527. case StatusCode::Continue_100:
  10528. case StatusCode::ExpectationFailed_417:
  10529. detail::write_response_line(strm, status);
  10530. strm.write("\r\n");
  10531. break;
  10532. default:
  10533. connection_closed = true;
  10534. return write_response(strm, true, req, res);
  10535. }
  10536. }
  10537. // Setup `is_connection_closed` method
  10538. auto sock = strm.socket();
  10539. req.is_connection_closed = [sock]() {
  10540. return !detail::is_socket_alive(sock);
  10541. };
  10542. // WebSocket upgrade
  10543. // Check pre_routing_handler_ before upgrading so that authentication
  10544. // and other middleware can reject the request with an HTTP response
  10545. // (e.g., 401) before the protocol switches.
  10546. if (detail::is_websocket_upgrade(req)) {
  10547. if (pre_routing_handler_ &&
  10548. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10549. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10550. return write_response(strm, close_connection, req, res);
  10551. }
  10552. // Find matching WebSocket handler
  10553. for (const auto &entry : websocket_handlers_) {
  10554. if (entry.matcher->match(req)) {
  10555. // Compute accept key
  10556. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10557. auto accept_key = detail::websocket_accept_key(client_key);
  10558. // Negotiate subprotocol
  10559. std::string selected_subprotocol;
  10560. if (entry.sub_protocol_selector) {
  10561. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10562. if (!protocol_header.empty()) {
  10563. std::vector<std::string> protocols;
  10564. std::istringstream iss(protocol_header);
  10565. std::string token;
  10566. while (std::getline(iss, token, ',')) {
  10567. // Trim whitespace
  10568. auto start = token.find_first_not_of(' ');
  10569. auto end = token.find_last_not_of(' ');
  10570. if (start != std::string::npos) {
  10571. protocols.push_back(token.substr(start, end - start + 1));
  10572. }
  10573. }
  10574. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10575. }
  10576. }
  10577. // Send 101 Switching Protocols
  10578. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10579. "Upgrade: websocket\r\n"
  10580. "Connection: Upgrade\r\n"
  10581. "Sec-WebSocket-Accept: " +
  10582. accept_key + "\r\n";
  10583. if (!selected_subprotocol.empty()) {
  10584. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10585. return false;
  10586. }
  10587. handshake_response +=
  10588. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10589. }
  10590. handshake_response += "\r\n";
  10591. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10592. 0) {
  10593. return false;
  10594. }
  10595. connection_closed = true;
  10596. if (websocket_upgraded) { *websocket_upgraded = true; }
  10597. {
  10598. // Use WebSocket-specific read timeout instead of HTTP timeout
  10599. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10600. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10601. websocket_max_missed_pongs_);
  10602. entry.handler(req, ws);
  10603. }
  10604. return true;
  10605. }
  10606. }
  10607. // No matching handler - fall through to 404
  10608. }
  10609. // Routing
  10610. auto routed = false;
  10611. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10612. routed = routing(req, res, strm);
  10613. #else
  10614. try {
  10615. routed = routing(req, res, strm);
  10616. } catch (std::exception &) {
  10617. if (exception_handler_) {
  10618. auto ep = std::current_exception();
  10619. exception_handler_(req, res, ep);
  10620. routed = true;
  10621. } else {
  10622. res.status = StatusCode::InternalServerError_500;
  10623. }
  10624. } catch (...) {
  10625. if (exception_handler_) {
  10626. auto ep = std::current_exception();
  10627. exception_handler_(req, res, ep);
  10628. routed = true;
  10629. } else {
  10630. res.status = StatusCode::InternalServerError_500;
  10631. }
  10632. }
  10633. #endif
  10634. auto ret = false;
  10635. if (routed) {
  10636. if (res.status == -1) {
  10637. res.status = req.ranges.empty() ? StatusCode::OK_200
  10638. : StatusCode::PartialContent_206;
  10639. }
  10640. // Serve file content by using a content provider
  10641. auto file_open_error = false;
  10642. if (!res.file_content_path_.empty()) {
  10643. const auto &path = res.file_content_path_;
  10644. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10645. if (!mm->is_open()) {
  10646. res.body.clear();
  10647. res.content_length_ = 0;
  10648. res.content_provider_ = nullptr;
  10649. res.status = StatusCode::NotFound_404;
  10650. output_error_log(Error::OpenFile, &req);
  10651. file_open_error = true;
  10652. } else {
  10653. auto content_type = res.file_content_content_type_;
  10654. if (content_type.empty()) {
  10655. content_type = detail::find_content_type(
  10656. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10657. }
  10658. res.set_content_provider(
  10659. mm->size(), content_type,
  10660. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10661. sink.write(mm->data() + offset, length);
  10662. return true;
  10663. });
  10664. }
  10665. }
  10666. if (file_open_error) {
  10667. ret = write_response(strm, close_connection, req, res);
  10668. } else if (detail::range_error(req, res)) {
  10669. res.body.clear();
  10670. res.content_length_ = 0;
  10671. res.content_provider_ = nullptr;
  10672. res.status = StatusCode::RangeNotSatisfiable_416;
  10673. ret = write_response(strm, close_connection, req, res);
  10674. } else {
  10675. ret = write_response_with_content(strm, close_connection, req, res);
  10676. }
  10677. } else {
  10678. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10679. ret = write_response(strm, close_connection, req, res);
  10680. }
  10681. // Drain any unconsumed framed body to prevent request smuggling on
  10682. // keep-alive. Without framing there is no body to drain — reading would
  10683. // consume the next request (issue #2450).
  10684. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10685. int dummy_status;
  10686. if (!detail::read_content(
  10687. strm, req, payload_max_length_, dummy_status, nullptr,
  10688. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10689. connection_closed = true;
  10690. }
  10691. }
  10692. return ret;
  10693. }
  10694. inline bool Server::is_valid() const { return true; }
  10695. inline bool Server::process_and_close_socket(socket_t sock) {
  10696. std::string remote_addr;
  10697. int remote_port = 0;
  10698. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10699. std::string local_addr;
  10700. int local_port = 0;
  10701. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10702. bool websocket_upgraded = false;
  10703. auto ret = detail::process_server_socket(
  10704. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10705. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10706. write_timeout_usec_,
  10707. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10708. return process_request(strm, remote_addr, remote_port, local_addr,
  10709. local_port, close_connection, connection_closed,
  10710. nullptr, &websocket_upgraded);
  10711. });
  10712. detail::shutdown_socket(sock);
  10713. detail::close_socket(sock);
  10714. return ret;
  10715. }
  10716. inline void Server::output_log(const Request &req, const Response &res) const {
  10717. if (logger_) {
  10718. std::lock_guard<std::mutex> guard(logger_mutex_);
  10719. logger_(req, res);
  10720. }
  10721. }
  10722. inline void Server::output_pre_compression_log(const Request &req,
  10723. const Response &res) const {
  10724. if (pre_compression_logger_) {
  10725. std::lock_guard<std::mutex> guard(logger_mutex_);
  10726. pre_compression_logger_(req, res);
  10727. }
  10728. }
  10729. inline void Server::output_error_log(const Error &err,
  10730. const Request *req) const {
  10731. if (error_logger_) {
  10732. std::lock_guard<std::mutex> guard(logger_mutex_);
  10733. error_logger_(err, req);
  10734. }
  10735. }
  10736. /*
  10737. * Group 5: ClientImpl and Client (Universal) implementation
  10738. */
  10739. // HTTP client implementation
  10740. inline ClientImpl::ClientImpl(const std::string &host)
  10741. : ClientImpl(host, 80, std::string(), std::string()) {}
  10742. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10743. : ClientImpl(host, port, std::string(), std::string()) {}
  10744. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10745. const std::string &client_cert_path,
  10746. const std::string &client_key_path)
  10747. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10748. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10749. inline ClientImpl::~ClientImpl() {
  10750. // Wait until all the requests in flight are handled.
  10751. size_t retry_count = 10;
  10752. while (retry_count-- > 0) {
  10753. {
  10754. std::lock_guard<std::mutex> guard(socket_mutex_);
  10755. if (socket_requests_in_flight_ == 0) { break; }
  10756. }
  10757. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10758. }
  10759. std::lock_guard<std::mutex> guard(socket_mutex_);
  10760. shutdown_socket(socket_);
  10761. close_socket(socket_);
  10762. }
  10763. inline bool ClientImpl::is_valid() const { return true; }
  10764. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10765. client_cert_path_ = rhs.client_cert_path_;
  10766. client_key_path_ = rhs.client_key_path_;
  10767. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10768. read_timeout_sec_ = rhs.read_timeout_sec_;
  10769. read_timeout_usec_ = rhs.read_timeout_usec_;
  10770. write_timeout_sec_ = rhs.write_timeout_sec_;
  10771. write_timeout_usec_ = rhs.write_timeout_usec_;
  10772. max_timeout_msec_ = rhs.max_timeout_msec_;
  10773. basic_auth_username_ = rhs.basic_auth_username_;
  10774. basic_auth_password_ = rhs.basic_auth_password_;
  10775. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10776. keep_alive_ = rhs.keep_alive_;
  10777. follow_location_ = rhs.follow_location_;
  10778. path_encode_ = rhs.path_encode_;
  10779. address_family_ = rhs.address_family_;
  10780. tcp_nodelay_ = rhs.tcp_nodelay_;
  10781. ipv6_v6only_ = rhs.ipv6_v6only_;
  10782. socket_options_ = rhs.socket_options_;
  10783. compress_ = rhs.compress_;
  10784. decompress_ = rhs.decompress_;
  10785. payload_max_length_ = rhs.payload_max_length_;
  10786. has_payload_max_length_ = rhs.has_payload_max_length_;
  10787. interface_ = rhs.interface_;
  10788. proxy_host_ = rhs.proxy_host_;
  10789. proxy_port_ = rhs.proxy_port_;
  10790. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10791. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10792. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10793. no_proxy_entries_ = rhs.no_proxy_entries_;
  10794. logger_ = rhs.logger_;
  10795. error_logger_ = rhs.error_logger_;
  10796. #ifdef CPPHTTPLIB_SSL_ENABLED
  10797. digest_auth_username_ = rhs.digest_auth_username_;
  10798. digest_auth_password_ = rhs.digest_auth_password_;
  10799. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10800. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10801. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10802. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10803. server_certificate_verification_ = rhs.server_certificate_verification_;
  10804. server_hostname_verification_ = rhs.server_hostname_verification_;
  10805. system_ca_mode_ = rhs.system_ca_mode_;
  10806. #endif
  10807. }
  10808. inline bool
  10809. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10810. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10811. if (no_proxy_entries_.empty()) { return true; }
  10812. // host_ is const so its normalized form is invariant; cache it. The
  10813. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10814. if (host == host_) {
  10815. if (!host_normalized_valid_) {
  10816. host_normalized_ = detail::normalize_target(host_);
  10817. host_normalized_valid_ = true;
  10818. }
  10819. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10820. }
  10821. auto target = detail::normalize_target(host);
  10822. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10823. }
  10824. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10825. if (is_proxy_enabled_for_host(host_)) {
  10826. return detail::create_client_socket(
  10827. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10828. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10829. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10830. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10831. }
  10832. // Check is custom IP specified for host_
  10833. std::string ip;
  10834. auto it = addr_map_.find(host_);
  10835. if (it != addr_map_.end()) { ip = it->second; }
  10836. return detail::create_client_socket(
  10837. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10838. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10839. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10840. write_timeout_usec_, interface_, error);
  10841. }
  10842. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10843. Error &error) {
  10844. auto sock = create_client_socket(error);
  10845. if (sock == INVALID_SOCKET) { return false; }
  10846. socket.sock = sock;
  10847. return true;
  10848. }
  10849. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10850. return create_and_connect_socket(socket, error);
  10851. }
  10852. inline bool ClientImpl::setup_proxy_connection(
  10853. Socket & /*socket*/,
  10854. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10855. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10856. return true;
  10857. }
  10858. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10859. bool /*shutdown_gracefully*/) {
  10860. // If there are any requests in flight from threads other than us, then it's
  10861. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10862. assert(socket_requests_in_flight_ == 0 ||
  10863. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10864. }
  10865. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10866. if (socket.sock == INVALID_SOCKET) { return; }
  10867. detail::shutdown_socket(socket.sock);
  10868. }
  10869. inline void ClientImpl::close_socket(Socket &socket) {
  10870. // If there are requests in flight in another thread, usually closing
  10871. // the socket will be fine and they will simply receive an error when
  10872. // using the closed socket, but it is still a bug since rarely the OS
  10873. // may reassign the socket id to be used for a new socket, and then
  10874. // suddenly they will be operating on a live socket that is different
  10875. // than the one they intended!
  10876. assert(socket_requests_in_flight_ == 0 ||
  10877. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10878. // It is also a bug if this happens while SSL is still active
  10879. #ifdef CPPHTTPLIB_SSL_ENABLED
  10880. assert(socket.ssl == nullptr);
  10881. #endif
  10882. if (socket.sock == INVALID_SOCKET) { return; }
  10883. detail::close_socket(socket.sock);
  10884. socket.sock = INVALID_SOCKET;
  10885. }
  10886. inline void ClientImpl::disconnect(bool gracefully) {
  10887. shutdown_ssl(socket_, gracefully);
  10888. shutdown_socket(socket_);
  10889. close_socket(socket_);
  10890. }
  10891. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10892. Response &res,
  10893. bool skip_100_continue) const {
  10894. std::array<char, 2048> buf{};
  10895. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10896. if (!line_reader.getline()) { return false; }
  10897. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10898. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10899. #else
  10900. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10901. #endif
  10902. std::cmatch m;
  10903. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10904. return req.method == "CONNECT";
  10905. }
  10906. res.version = std::string(m[1]);
  10907. res.status = std::stoi(std::string(m[2]));
  10908. res.reason = std::string(m[3]);
  10909. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10910. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10911. if (!line_reader.getline()) { return false; } // CRLF
  10912. if (!line_reader.getline()) { return false; } // next response line
  10913. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10914. res.version = std::string(m[1]);
  10915. res.status = std::stoi(std::string(m[2]));
  10916. res.reason = std::string(m[3]);
  10917. }
  10918. return true;
  10919. }
  10920. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10921. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10922. auto ret = send_(req, res, error);
  10923. if (error == Error::SSLPeerCouldBeClosed_) {
  10924. assert(!ret);
  10925. ret = send_(req, res, error);
  10926. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10927. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10928. }
  10929. return ret;
  10930. }
  10931. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10932. {
  10933. std::lock_guard<std::mutex> guard(socket_mutex_);
  10934. // Set this to false immediately - if it ever gets set to true by the end
  10935. // of the request, we know another thread instructed us to close the
  10936. // socket.
  10937. socket_should_be_closed_when_request_is_done_ = false;
  10938. auto is_alive = false;
  10939. if (socket_.is_open()) {
  10940. is_alive = detail::is_socket_alive(socket_.sock);
  10941. #ifdef CPPHTTPLIB_SSL_ENABLED
  10942. if (is_alive && is_ssl()) {
  10943. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10944. is_alive = false;
  10945. }
  10946. }
  10947. #endif
  10948. if (!is_alive) {
  10949. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10950. disconnect(/*gracefully=*/false);
  10951. }
  10952. }
  10953. if (!is_alive) {
  10954. if (!ensure_socket_connection(socket_, error)) {
  10955. output_error_log(error, &req);
  10956. return false;
  10957. }
  10958. {
  10959. auto success = true;
  10960. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10961. error)) {
  10962. if (!success) { output_error_log(error, &req); }
  10963. return success;
  10964. }
  10965. }
  10966. }
  10967. // Mark the current socket as being in use so that it cannot be closed by
  10968. // anyone else while this request is ongoing, even though we will be
  10969. // releasing the mutex.
  10970. if (socket_requests_in_flight_ > 1) {
  10971. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10972. }
  10973. socket_requests_in_flight_ += 1;
  10974. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10975. }
  10976. for (const auto &header : default_headers_) {
  10977. if (req.headers.find(header.first) == req.headers.end()) {
  10978. req.headers.insert(header);
  10979. }
  10980. }
  10981. auto ret = false;
  10982. auto close_connection = !keep_alive_;
  10983. auto se = detail::scope_exit([&]() {
  10984. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10985. std::lock_guard<std::mutex> guard(socket_mutex_);
  10986. socket_requests_in_flight_ -= 1;
  10987. if (socket_requests_in_flight_ <= 0) {
  10988. assert(socket_requests_in_flight_ == 0);
  10989. socket_requests_are_from_thread_ = std::thread::id();
  10990. }
  10991. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10992. !ret) {
  10993. disconnect(/*gracefully=*/true);
  10994. }
  10995. });
  10996. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10997. return handle_request(strm, req, res, close_connection, error);
  10998. });
  10999. if (!ret) {
  11000. if (error == Error::Success) {
  11001. error = Error::Unknown;
  11002. output_error_log(error, &req);
  11003. }
  11004. }
  11005. return ret;
  11006. }
  11007. inline Result ClientImpl::send(const Request &req) {
  11008. auto req2 = req;
  11009. return send_(std::move(req2));
  11010. }
  11011. inline Result ClientImpl::send_(Request &&req) {
  11012. auto res = detail::make_unique<Response>();
  11013. auto error = Error::Success;
  11014. auto ret = send(req, *res, error);
  11015. #ifdef CPPHTTPLIB_SSL_ENABLED
  11016. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  11017. last_ssl_error_, last_backend_error_};
  11018. #else
  11019. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  11020. #endif
  11021. }
  11022. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  11023. const std::string &ct) {
  11024. (void)for_stream;
  11025. for (const auto &header : default_headers_) {
  11026. if (!r.has_header(header.first)) { r.headers.insert(header); }
  11027. }
  11028. if (!r.has_header("Host")) {
  11029. if (address_family_ == AF_UNIX) {
  11030. r.headers.emplace("Host", "localhost");
  11031. } else {
  11032. r.headers.emplace(
  11033. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  11034. }
  11035. }
  11036. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  11037. if (!r.content_receiver) {
  11038. if (!r.has_header("Accept-Encoding")) {
  11039. std::string accept_encoding;
  11040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11041. accept_encoding = "br";
  11042. #endif
  11043. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11044. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11045. accept_encoding += "gzip, deflate";
  11046. #endif
  11047. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11048. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11049. accept_encoding += "zstd";
  11050. #endif
  11051. r.set_header("Accept-Encoding", accept_encoding);
  11052. }
  11053. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11054. if (!r.has_header("User-Agent")) {
  11055. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11056. r.set_header("User-Agent", agent);
  11057. }
  11058. #endif
  11059. }
  11060. if (!r.body.empty()) {
  11061. if (!ct.empty() && !r.has_header("Content-Type")) {
  11062. r.headers.emplace("Content-Type", ct);
  11063. }
  11064. if (!r.has_header("Content-Length")) {
  11065. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11066. }
  11067. }
  11068. }
  11069. inline ClientImpl::StreamHandle
  11070. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11071. const Params &params, const Headers &headers,
  11072. const std::string &body,
  11073. const std::string &content_type) {
  11074. StreamHandle handle;
  11075. handle.response = detail::make_unique<Response>();
  11076. handle.error = Error::Success;
  11077. auto query_path = params.empty() ? path : append_query_params(path, params);
  11078. handle.connection_ = detail::make_unique<ClientConnection>();
  11079. {
  11080. std::lock_guard<std::mutex> guard(socket_mutex_);
  11081. auto is_alive = false;
  11082. if (socket_.is_open()) {
  11083. is_alive = detail::is_socket_alive(socket_.sock);
  11084. #ifdef CPPHTTPLIB_SSL_ENABLED
  11085. if (is_alive && is_ssl()) {
  11086. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11087. is_alive = false;
  11088. }
  11089. }
  11090. #endif
  11091. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11092. }
  11093. if (!is_alive) {
  11094. if (!ensure_socket_connection(socket_, handle.error)) {
  11095. handle.response.reset();
  11096. return handle;
  11097. }
  11098. {
  11099. auto success = true;
  11100. auto start_time = std::chrono::steady_clock::now();
  11101. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11102. success, handle.error)) {
  11103. if (!success) { handle.response.reset(); }
  11104. return handle;
  11105. }
  11106. }
  11107. }
  11108. transfer_socket_ownership_to_handle(handle);
  11109. }
  11110. #ifdef CPPHTTPLIB_SSL_ENABLED
  11111. if (is_ssl() && handle.connection_->session) {
  11112. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11113. handle.connection_->sock, handle.connection_->session,
  11114. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11115. write_timeout_usec_);
  11116. } else {
  11117. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11118. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11119. write_timeout_sec_, write_timeout_usec_);
  11120. }
  11121. #else
  11122. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11123. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11124. write_timeout_sec_, write_timeout_usec_);
  11125. #endif
  11126. handle.stream_ = handle.socket_stream_.get();
  11127. Request req;
  11128. req.method = method;
  11129. req.path = query_path;
  11130. req.headers = headers;
  11131. req.body = body;
  11132. prepare_default_headers(req, true, content_type);
  11133. auto &strm = *handle.stream_;
  11134. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11135. handle.error = Error::Write;
  11136. handle.response.reset();
  11137. return handle;
  11138. }
  11139. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11140. handle.error)) {
  11141. handle.response.reset();
  11142. return handle;
  11143. }
  11144. if (!body.empty()) {
  11145. if (strm.write(body.data(), body.size()) < 0) {
  11146. handle.error = Error::Write;
  11147. handle.response.reset();
  11148. return handle;
  11149. }
  11150. }
  11151. if (!read_response_line(strm, req, *handle.response) ||
  11152. !detail::read_headers(strm, handle.response->headers)) {
  11153. handle.error = Error::Read;
  11154. handle.response.reset();
  11155. return handle;
  11156. }
  11157. handle.body_reader_.stream = handle.stream_;
  11158. handle.body_reader_.payload_max_length = payload_max_length_;
  11159. if (handle.response->has_header("Content-Length")) {
  11160. bool is_invalid = false;
  11161. auto content_length = detail::get_header_value_u64(
  11162. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11163. if (is_invalid) {
  11164. handle.error = Error::Read;
  11165. handle.response.reset();
  11166. return handle;
  11167. }
  11168. handle.body_reader_.has_content_length = true;
  11169. handle.body_reader_.content_length = content_length;
  11170. }
  11171. handle.body_reader_.chunked =
  11172. detail::is_chunked_transfer_encoding(handle.response->headers);
  11173. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11174. if (!content_encoding.empty()) {
  11175. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11176. }
  11177. return handle;
  11178. }
  11179. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11180. if (!is_valid() || !response) { return -1; }
  11181. if (decompressor_) { return read_with_decompression(buf, len); }
  11182. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11183. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11184. trailers_parsed_ = true;
  11185. if (body_reader_.chunked_decoder) {
  11186. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11187. response->trailers, response->headers)) {
  11188. return n;
  11189. }
  11190. } else {
  11191. detail::ChunkedDecoder dec(*stream_);
  11192. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11193. return n;
  11194. }
  11195. }
  11196. }
  11197. return n;
  11198. }
  11199. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11200. size_t len) {
  11201. if (decompress_offset_ < decompress_buffer_.size()) {
  11202. auto available = decompress_buffer_.size() - decompress_offset_;
  11203. auto to_copy = (std::min)(len, available);
  11204. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11205. decompress_offset_ += to_copy;
  11206. decompressed_bytes_read_ += to_copy;
  11207. return static_cast<ssize_t>(to_copy);
  11208. }
  11209. decompress_buffer_.clear();
  11210. decompress_offset_ = 0;
  11211. constexpr size_t kDecompressionBufferSize = 8192;
  11212. char compressed_buf[kDecompressionBufferSize];
  11213. while (true) {
  11214. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11215. sizeof(compressed_buf));
  11216. if (n <= 0) { return n; }
  11217. bool decompress_ok = decompressor_->decompress(
  11218. compressed_buf, static_cast<size_t>(n),
  11219. [this](const char *data, size_t data_len) {
  11220. decompress_buffer_.append(data, data_len);
  11221. auto limit = body_reader_.payload_max_length;
  11222. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11223. return false;
  11224. }
  11225. return true;
  11226. });
  11227. if (!decompress_ok) {
  11228. body_reader_.last_error = Error::Read;
  11229. return -1;
  11230. }
  11231. if (!decompress_buffer_.empty()) { break; }
  11232. }
  11233. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11234. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11235. decompress_offset_ = to_copy;
  11236. decompressed_bytes_read_ += to_copy;
  11237. return static_cast<ssize_t>(to_copy);
  11238. }
  11239. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11240. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11241. return;
  11242. }
  11243. trailers_parsed_ = true;
  11244. const auto bufsiz = 128;
  11245. char line_buf[bufsiz];
  11246. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11247. if (!line_reader.getline()) { return; }
  11248. if (!detail::parse_trailers(line_reader, response->trailers,
  11249. response->headers)) {
  11250. return;
  11251. }
  11252. }
  11253. namespace detail {
  11254. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11255. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11256. size_t &out_chunk_offset,
  11257. size_t &out_chunk_total) {
  11258. if (finished) { return 0; }
  11259. if (chunk_remaining == 0) {
  11260. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11261. if (!lr.getline()) { return -1; }
  11262. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11263. const char *p = lr.ptr();
  11264. int v = 0;
  11265. if (!is_hex(*p, v)) { return -1; }
  11266. size_t chunk_len = 0;
  11267. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11268. for (; is_hex(*p, v); ++p) {
  11269. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11270. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11271. }
  11272. while (is_space_or_tab(*p)) {
  11273. ++p;
  11274. }
  11275. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11276. if (chunk_len == 0) {
  11277. chunk_remaining = 0;
  11278. finished = true;
  11279. out_chunk_offset = 0;
  11280. out_chunk_total = 0;
  11281. return 0;
  11282. }
  11283. chunk_remaining = chunk_len;
  11284. last_chunk_total = chunk_remaining;
  11285. last_chunk_offset = 0;
  11286. }
  11287. auto to_read = (std::min)(chunk_remaining, len);
  11288. auto n = strm.read(buf, to_read);
  11289. if (n <= 0) { return -1; }
  11290. auto offset_before = last_chunk_offset;
  11291. last_chunk_offset += static_cast<size_t>(n);
  11292. chunk_remaining -= static_cast<size_t>(n);
  11293. out_chunk_offset = offset_before;
  11294. out_chunk_total = last_chunk_total;
  11295. if (chunk_remaining == 0) {
  11296. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11297. if (!lr.getline()) { return -1; }
  11298. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11299. }
  11300. return n;
  11301. }
  11302. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11303. const Headers &src_headers) {
  11304. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11305. if (!lr.getline()) { return false; }
  11306. return parse_trailers(lr, dest, src_headers);
  11307. }
  11308. } // namespace detail
  11309. inline void
  11310. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11311. handle.connection_->sock = socket_.sock;
  11312. #ifdef CPPHTTPLIB_SSL_ENABLED
  11313. handle.connection_->session = socket_.ssl;
  11314. socket_.ssl = nullptr;
  11315. #endif
  11316. socket_.sock = INVALID_SOCKET;
  11317. }
  11318. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11319. Response &res, bool close_connection,
  11320. Error &error) {
  11321. if (req.path.empty()) {
  11322. error = Error::Connection;
  11323. output_error_log(error, &req);
  11324. return false;
  11325. }
  11326. auto req_save = req;
  11327. bool ret;
  11328. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11329. auto req2 = req;
  11330. req2.path = "http://" +
  11331. detail::make_host_and_port_string(host_, port_, false) +
  11332. req.path;
  11333. ret = process_request(strm, req2, res, close_connection, error);
  11334. req = std::move(req2);
  11335. req.path = req_save.path;
  11336. } else {
  11337. ret = process_request(strm, req, res, close_connection, error);
  11338. }
  11339. if (!ret) { return false; }
  11340. if (res.get_header_value("Connection") == "close" ||
  11341. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11342. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11343. // for this to be safe.
  11344. // This is safe to call because handle_request is only called by send_
  11345. // which locks the request mutex during the process. It would be a bug
  11346. // to call it from a different thread since it's a thread-safety issue
  11347. // to do these things to the socket if another thread is using the socket.
  11348. std::lock_guard<std::mutex> guard(socket_mutex_);
  11349. disconnect(/*gracefully=*/true);
  11350. }
  11351. if (300 < res.status && res.status < 400 && follow_location_) {
  11352. req = std::move(req_save);
  11353. ret = redirect(req, res, error);
  11354. }
  11355. #ifdef CPPHTTPLIB_SSL_ENABLED
  11356. if ((res.status == StatusCode::Unauthorized_401 ||
  11357. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11358. req.authorization_count_ < 5) {
  11359. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11360. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11361. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11362. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11363. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11364. return ret;
  11365. }
  11366. const auto &username =
  11367. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11368. const auto &password =
  11369. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11370. if (!username.empty() && !password.empty()) {
  11371. std::map<std::string, std::string> auth;
  11372. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11373. Request new_req = req;
  11374. new_req.authorization_count_ += 1;
  11375. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11376. : "Authorization");
  11377. new_req.headers.insert(detail::make_digest_authentication_header(
  11378. req, auth, new_req.authorization_count_, detail::random_string(10),
  11379. username, password, is_proxy));
  11380. Response new_res;
  11381. ret = send(new_req, new_res, error);
  11382. if (ret) { res = std::move(new_res); }
  11383. }
  11384. }
  11385. }
  11386. #endif
  11387. return ret;
  11388. }
  11389. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11390. if (req.redirect_count_ == 0) {
  11391. error = Error::ExceedRedirectCount;
  11392. output_error_log(error, &req);
  11393. return false;
  11394. }
  11395. auto location = res.get_header_value("location");
  11396. if (location.empty()) { return false; }
  11397. detail::UrlComponents uc;
  11398. if (!detail::parse_url(location, uc)) { return false; }
  11399. // Only follow http/https redirects
  11400. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11401. return false;
  11402. }
  11403. auto scheme = is_ssl() ? "https" : "http";
  11404. auto next_scheme = std::move(uc.scheme);
  11405. auto next_host = std::move(uc.host);
  11406. auto port_str = std::move(uc.port);
  11407. auto next_path = std::move(uc.path);
  11408. auto next_query = std::move(uc.query);
  11409. auto next_port = port_;
  11410. if (!port_str.empty()) {
  11411. if (!detail::parse_port(port_str, next_port)) { return false; }
  11412. } else if (!next_scheme.empty()) {
  11413. next_port = next_scheme == "https" ? 443 : 80;
  11414. }
  11415. if (next_scheme.empty()) { next_scheme = scheme; }
  11416. if (next_host.empty()) { next_host = host_; }
  11417. if (next_path.empty()) { next_path = "/"; }
  11418. auto path = decode_path_component(next_path) + next_query;
  11419. // Same host redirect - use current client
  11420. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11421. return detail::redirect(*this, req, res, path, location, error);
  11422. }
  11423. // Cross-host/scheme redirect - create new client with robust setup
  11424. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11425. path, location, error);
  11426. }
  11427. // New method for robust redirect client creation
  11428. inline bool ClientImpl::create_redirect_client(
  11429. const std::string &scheme, const std::string &host, int port, Request &req,
  11430. Response &res, const std::string &path, const std::string &location,
  11431. Error &error) {
  11432. // Determine if we need SSL
  11433. auto need_ssl = (scheme == "https");
  11434. // Clean up request headers that are host/client specific
  11435. // Remove headers that should not be carried over to new host
  11436. auto headers_to_remove = std::vector<std::string>{
  11437. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  11438. for (const auto &header_name : headers_to_remove) {
  11439. auto it = req.headers.find(header_name);
  11440. while (it != req.headers.end()) {
  11441. it = req.headers.erase(it);
  11442. it = req.headers.find(header_name);
  11443. }
  11444. }
  11445. // Create appropriate client type and handle redirect
  11446. if (need_ssl) {
  11447. #ifdef CPPHTTPLIB_SSL_ENABLED
  11448. // Create SSL client for HTTPS redirect
  11449. SSLClient redirect_client(host, port);
  11450. // Setup basic client configuration first
  11451. setup_redirect_client(redirect_client);
  11452. redirect_client.enable_server_certificate_verification(
  11453. server_certificate_verification_);
  11454. redirect_client.enable_server_hostname_verification(
  11455. server_hostname_verification_);
  11456. redirect_client.system_ca_mode_ = system_ca_mode_;
  11457. // Transfer CA certificate to redirect client
  11458. if (!ca_cert_pem_.empty()) {
  11459. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11460. ca_cert_pem_.size());
  11461. }
  11462. if (!ca_cert_file_path_.empty()) {
  11463. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11464. }
  11465. // Client certificates are set through constructor for SSLClient
  11466. // NOTE: SSLClient constructor already takes client_cert_path and
  11467. // client_key_path so we need to create it properly if client certs are
  11468. // needed
  11469. // Execute the redirect
  11470. return detail::redirect(redirect_client, req, res, path, location, error);
  11471. #else
  11472. // SSL not supported - set appropriate error
  11473. error = Error::SSLConnection;
  11474. output_error_log(error, &req);
  11475. return false;
  11476. #endif
  11477. } else {
  11478. // HTTP redirect
  11479. ClientImpl redirect_client(host, port);
  11480. // Setup client with robust configuration
  11481. setup_redirect_client(redirect_client);
  11482. // Execute the redirect
  11483. return detail::redirect(redirect_client, req, res, path, location, error);
  11484. }
  11485. }
  11486. // New method for robust client setup (based on basic_manual_redirect.cpp
  11487. // logic)
  11488. template <typename ClientType>
  11489. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11490. // Copy basic settings first
  11491. client.set_connection_timeout(connection_timeout_sec_);
  11492. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11493. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11494. client.set_keep_alive(keep_alive_);
  11495. client.set_follow_location(
  11496. true); // Enable redirects to handle multi-step redirects
  11497. client.set_path_encode(path_encode_);
  11498. client.set_compress(compress_);
  11499. client.set_decompress(decompress_);
  11500. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11501. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11502. // 15.4, credentials must not be forwarded when redirecting to a different
  11503. // host. This function is only called for cross-host redirects; same-host
  11504. // redirects are handled directly in ClientImpl::redirect().
  11505. // Copy the proxy configuration unconditionally; the per-target bypass is
  11506. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11507. // still use the proxy.
  11508. client.no_proxy_entries_ = no_proxy_entries_;
  11509. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11510. client.set_proxy(proxy_host_, proxy_port_);
  11511. if (!proxy_basic_auth_username_.empty()) {
  11512. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11513. proxy_basic_auth_password_);
  11514. }
  11515. if (!proxy_bearer_token_auth_token_.empty()) {
  11516. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11517. }
  11518. #ifdef CPPHTTPLIB_SSL_ENABLED
  11519. if (!proxy_digest_auth_username_.empty()) {
  11520. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11521. proxy_digest_auth_password_);
  11522. }
  11523. #endif
  11524. }
  11525. // Copy network and socket settings
  11526. client.set_address_family(address_family_);
  11527. client.set_tcp_nodelay(tcp_nodelay_);
  11528. client.set_ipv6_v6only(ipv6_v6only_);
  11529. if (socket_options_) { client.set_socket_options(socket_options_); }
  11530. if (!interface_.empty()) { client.set_interface(interface_); }
  11531. // Copy logging and headers
  11532. if (logger_) { client.set_logger(logger_); }
  11533. if (error_logger_) { client.set_error_logger(error_logger_); }
  11534. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11535. // Each new client should generate its own headers based on its target host
  11536. }
  11537. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11538. const Request &req,
  11539. Error &error) const {
  11540. auto is_shutting_down = []() { return false; };
  11541. if (req.is_chunked_content_provider_) {
  11542. auto compressor = compress_ ? detail::create_compressor().first
  11543. : std::unique_ptr<detail::compressor>();
  11544. if (!compressor) {
  11545. compressor = detail::make_unique<detail::nocompressor>();
  11546. }
  11547. return detail::write_content_chunked(strm, req.content_provider_,
  11548. is_shutting_down, *compressor, error);
  11549. } else {
  11550. return detail::write_content_with_progress(
  11551. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11552. req.upload_progress, error);
  11553. }
  11554. }
  11555. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11556. bool close_connection, Error &error,
  11557. bool skip_body) {
  11558. // Prepare additional headers
  11559. if (close_connection) {
  11560. if (!req.has_header("Connection")) {
  11561. req.set_header("Connection", "close");
  11562. }
  11563. }
  11564. std::string ct_for_defaults;
  11565. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11566. ct_for_defaults = "text/plain";
  11567. }
  11568. prepare_default_headers(req, false, ct_for_defaults);
  11569. if (req.body.empty()) {
  11570. if (req.content_provider_) {
  11571. if (!req.is_chunked_content_provider_) {
  11572. if (!req.has_header("Content-Length")) {
  11573. auto length = std::to_string(req.content_length_);
  11574. req.set_header("Content-Length", length);
  11575. }
  11576. }
  11577. } else {
  11578. if (req.method == "POST" || req.method == "PUT" ||
  11579. req.method == "PATCH") {
  11580. req.set_header("Content-Length", "0");
  11581. }
  11582. }
  11583. }
  11584. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11585. if (!req.has_header("Authorization")) {
  11586. req.headers.insert(make_basic_authentication_header(
  11587. basic_auth_username_, basic_auth_password_, false));
  11588. }
  11589. }
  11590. if (!bearer_token_auth_token_.empty()) {
  11591. if (!req.has_header("Authorization")) {
  11592. req.headers.insert(make_bearer_token_authentication_header(
  11593. bearer_token_auth_token_, false));
  11594. }
  11595. }
  11596. // Proxy-Authorization is only sent when the proxy is actually used for
  11597. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11598. // credentials directly to the destination server.
  11599. if (is_proxy_enabled_for_host(host_)) {
  11600. if (!proxy_basic_auth_username_.empty() &&
  11601. !proxy_basic_auth_password_.empty() &&
  11602. !req.has_header("Proxy-Authorization")) {
  11603. req.headers.insert(make_basic_authentication_header(
  11604. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11605. }
  11606. if (!proxy_bearer_token_auth_token_.empty() &&
  11607. !req.has_header("Proxy-Authorization")) {
  11608. req.headers.insert(make_bearer_token_authentication_header(
  11609. proxy_bearer_token_auth_token_, true));
  11610. }
  11611. }
  11612. // Request line and headers
  11613. {
  11614. detail::BufferStream bstrm;
  11615. // Extract path and query from req.path
  11616. std::string path_part, query_part;
  11617. auto query_pos = req.path.find('?');
  11618. if (query_pos != std::string::npos) {
  11619. path_part = req.path.substr(0, query_pos);
  11620. query_part = req.path.substr(query_pos + 1);
  11621. } else {
  11622. path_part = req.path;
  11623. query_part = "";
  11624. }
  11625. // Encode path part. If the original `req.path` already contained a
  11626. // query component, preserve its raw query string (including parameter
  11627. // order) instead of reparsing and reassembling it which may reorder
  11628. // parameters due to container ordering (e.g. `Params` uses
  11629. // `std::multimap`). When there is no query in `req.path`, fall back to
  11630. // building a query from `req.params` so existing callers that pass
  11631. // `Params` continue to work.
  11632. auto path_with_query =
  11633. path_encode_ ? detail::encode_path(path_part) : path_part;
  11634. if (!query_part.empty()) {
  11635. // Normalize the query string (decode then re-encode) while preserving
  11636. // the original parameter order. When path encoding is disabled the
  11637. // caller has supplied an already-encoded target and expects the exact
  11638. // bytes to be sent on the wire, so skip normalization for the query
  11639. // too. Normalizing here would decode-then-re-encode the query and
  11640. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11641. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11642. if (path_encode_) {
  11643. auto normalized = detail::normalize_query_string(query_part);
  11644. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11645. } else {
  11646. path_with_query += '?' + query_part;
  11647. }
  11648. // Still populate req.params for handlers/users who read them.
  11649. detail::parse_query_text(query_part, req.params);
  11650. } else {
  11651. // No query in path; parse any query_part (empty) and append params
  11652. // from `req.params` when present (preserves prior behavior for
  11653. // callers who provide Params separately).
  11654. detail::parse_query_text(query_part, req.params);
  11655. if (!req.params.empty()) {
  11656. path_with_query = append_query_params(path_with_query, req.params);
  11657. }
  11658. }
  11659. // Write request line and headers
  11660. detail::write_request_line(bstrm, req.method, path_with_query);
  11661. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11662. error)) {
  11663. output_error_log(error, &req);
  11664. return false;
  11665. }
  11666. // Flush buffer
  11667. auto &data = bstrm.get_buffer();
  11668. if (!detail::write_data(strm, data.data(), data.size())) {
  11669. error = Error::Write;
  11670. output_error_log(error, &req);
  11671. return false;
  11672. }
  11673. }
  11674. // After sending request line and headers, wait briefly for an early server
  11675. // response (e.g. 4xx) and avoid sending a potentially large request body
  11676. // unnecessarily. This workaround is only enabled on Windows because Unix
  11677. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11678. // buffering can accept large writes even when the peer already responded.
  11679. // Check the stream first (which covers SSL via `is_readable()`), then
  11680. // fall back to select on the socket. Only perform the wait for very large
  11681. // request bodies to avoid interfering with normal small requests and
  11682. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11683. // response. Skip this check when using Expect: 100-continue, as the protocol
  11684. // handles early responses properly.
  11685. #if defined(_WIN32)
  11686. if (!skip_body &&
  11687. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11688. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11689. auto start = std::chrono::high_resolution_clock::now();
  11690. for (;;) {
  11691. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11692. // from SSL internals. If the underlying socket is readable, assume an
  11693. // early response may be present.
  11694. auto sock = strm.socket();
  11695. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11696. return false;
  11697. }
  11698. // Fallback to stream-level check for non-socket streams or when the
  11699. // socket isn't reporting readable. Avoid using `is_readable()` for
  11700. // SSL, since `SSL_pending()` may report buffered records that do not
  11701. // indicate a complete application-level response yet.
  11702. if (!is_ssl() && strm.is_readable()) { return false; }
  11703. auto now = std::chrono::high_resolution_clock::now();
  11704. auto elapsed =
  11705. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11706. .count();
  11707. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11708. break;
  11709. }
  11710. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11711. }
  11712. }
  11713. #endif
  11714. // Body
  11715. if (skip_body) { return true; }
  11716. return write_request_body(strm, req, error);
  11717. }
  11718. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11719. Error &error) {
  11720. if (req.body.empty()) {
  11721. return write_content_with_provider(strm, req, error);
  11722. }
  11723. if (req.upload_progress) {
  11724. auto body_size = req.body.size();
  11725. size_t written = 0;
  11726. auto data = req.body.data();
  11727. while (written < body_size) {
  11728. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11729. if (!detail::write_data(strm, data + written, to_write)) {
  11730. error = Error::Write;
  11731. output_error_log(error, &req);
  11732. return false;
  11733. }
  11734. written += to_write;
  11735. if (!req.upload_progress(written, body_size)) {
  11736. error = Error::Canceled;
  11737. output_error_log(error, &req);
  11738. return false;
  11739. }
  11740. }
  11741. } else {
  11742. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11743. error = Error::Write;
  11744. output_error_log(error, &req);
  11745. return false;
  11746. }
  11747. }
  11748. return true;
  11749. }
  11750. inline std::unique_ptr<Response>
  11751. ClientImpl::send_with_content_provider_and_receiver(
  11752. Request &req, const char *body, size_t content_length,
  11753. ContentProvider content_provider,
  11754. ContentProviderWithoutLength content_provider_without_length,
  11755. const std::string &content_type, ContentReceiver content_receiver,
  11756. Error &error) {
  11757. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11758. auto enc = compress_
  11759. ? detail::create_compressor()
  11760. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11761. nullptr, nullptr);
  11762. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11763. if (enc.first && !content_provider_without_length) {
  11764. auto &compressor = enc.first;
  11765. if (content_provider) {
  11766. auto ok = true;
  11767. size_t offset = 0;
  11768. DataSink data_sink;
  11769. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11770. if (ok) {
  11771. auto last = offset + data_len == content_length;
  11772. auto ret = compressor->compress(
  11773. data, data_len, last,
  11774. [&](const char *compressed_data, size_t compressed_data_len) {
  11775. req.body.append(compressed_data, compressed_data_len);
  11776. return true;
  11777. });
  11778. if (ret) {
  11779. offset += data_len;
  11780. } else {
  11781. ok = false;
  11782. }
  11783. }
  11784. return ok;
  11785. };
  11786. while (ok && offset < content_length) {
  11787. if (!content_provider(offset, content_length - offset, data_sink)) {
  11788. error = Error::Canceled;
  11789. output_error_log(error, &req);
  11790. return nullptr;
  11791. }
  11792. }
  11793. } else {
  11794. if (!compressor->compress(body, content_length, true,
  11795. [&](const char *data, size_t data_len) {
  11796. req.body.append(data, data_len);
  11797. return true;
  11798. })) {
  11799. error = Error::Compression;
  11800. output_error_log(error, &req);
  11801. return nullptr;
  11802. }
  11803. }
  11804. } else {
  11805. if (content_provider) {
  11806. req.content_length_ = content_length;
  11807. req.content_provider_ = std::move(content_provider);
  11808. req.is_chunked_content_provider_ = false;
  11809. } else if (content_provider_without_length) {
  11810. req.content_length_ = 0;
  11811. req.content_provider_ = detail::ContentProviderAdapter(
  11812. std::move(content_provider_without_length));
  11813. req.is_chunked_content_provider_ = true;
  11814. req.set_header("Transfer-Encoding", "chunked");
  11815. } else {
  11816. req.body.assign(body, content_length);
  11817. }
  11818. }
  11819. if (content_receiver) {
  11820. req.content_receiver =
  11821. [content_receiver](const char *data, size_t data_length,
  11822. size_t /*offset*/, size_t /*total_length*/) {
  11823. return content_receiver(data, data_length);
  11824. };
  11825. }
  11826. auto res = detail::make_unique<Response>();
  11827. return send(req, *res, error) ? std::move(res) : nullptr;
  11828. }
  11829. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11830. const std::string &method, const std::string &path, const Headers &headers,
  11831. const char *body, size_t content_length, ContentProvider content_provider,
  11832. ContentProviderWithoutLength content_provider_without_length,
  11833. const std::string &content_type, ContentReceiver content_receiver,
  11834. UploadProgress progress) {
  11835. Request req;
  11836. req.method = method;
  11837. req.headers = headers;
  11838. req.path = path;
  11839. req.upload_progress = std::move(progress);
  11840. if (max_timeout_msec_ > 0) {
  11841. req.start_time_ = std::chrono::steady_clock::now();
  11842. }
  11843. auto error = Error::Success;
  11844. auto res = send_with_content_provider_and_receiver(
  11845. req, body, content_length, std::move(content_provider),
  11846. std::move(content_provider_without_length), content_type,
  11847. std::move(content_receiver), error);
  11848. #ifdef CPPHTTPLIB_SSL_ENABLED
  11849. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11850. last_backend_error_};
  11851. #else
  11852. return Result{std::move(res), error, std::move(req.headers)};
  11853. #endif
  11854. }
  11855. inline void ClientImpl::output_log(const Request &req,
  11856. const Response &res) const {
  11857. if (logger_) {
  11858. std::lock_guard<std::mutex> guard(logger_mutex_);
  11859. logger_(req, res);
  11860. }
  11861. }
  11862. inline void ClientImpl::output_error_log(const Error &err,
  11863. const Request *req) const {
  11864. if (error_logger_) {
  11865. std::lock_guard<std::mutex> guard(logger_mutex_);
  11866. error_logger_(err, req);
  11867. }
  11868. }
  11869. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11870. Response &res, bool close_connection,
  11871. Error &error) {
  11872. // Auto-add Expect: 100-continue for large bodies
  11873. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11874. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11875. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11876. req.set_header("Expect", "100-continue");
  11877. }
  11878. }
  11879. // Check for Expect: 100-continue
  11880. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11881. // Send request (skip body if using Expect: 100-continue)
  11882. auto write_request_success =
  11883. write_request(strm, req, close_connection, error, expect_100_continue);
  11884. #ifdef CPPHTTPLIB_SSL_ENABLED
  11885. if (is_ssl() && !expect_100_continue) {
  11886. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11887. if (!is_proxy_enabled) {
  11888. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11889. error = Error::SSLPeerCouldBeClosed_;
  11890. output_error_log(error, &req);
  11891. return false;
  11892. }
  11893. }
  11894. }
  11895. #endif
  11896. // Handle Expect: 100-continue.
  11897. //
  11898. // Wait for an interim/early response by attempting to read the status line
  11899. // under a short timeout, instead of trusting raw socket readability. Over
  11900. // TLS, post-handshake records (e.g. session tickets) make the socket
  11901. // readable without any HTTP response being available; relying on
  11902. // `select_read` there caused the body to be withheld forever and the
  11903. // request to fail with `Read` (#2458). If no status line arrives within the
  11904. // timeout, send the body anyway (matching curl's behavior).
  11905. auto status_line_read = false;
  11906. if (expect_100_continue && write_request_success) {
  11907. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11908. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11909. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11910. strm.set_read_timeout(sec, usec);
  11911. status_line_read = read_response_line(strm, req, res, false);
  11912. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11913. }
  11914. if (!status_line_read) {
  11915. // No interim response within the timeout: send the body and handle the
  11916. // response as usual.
  11917. if (!write_request_body(strm, req, error)) { return false; }
  11918. expect_100_continue = false; // Switch to normal response handling
  11919. }
  11920. }
  11921. // Receive response and headers
  11922. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11923. if ((!status_line_read &&
  11924. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11925. !detail::read_headers(strm, res.headers)) {
  11926. if (write_request_success) { error = Error::Read; }
  11927. output_error_log(error, &req);
  11928. return false;
  11929. }
  11930. if (!write_request_success) { return false; }
  11931. // Handle Expect: 100-continue response
  11932. if (expect_100_continue) {
  11933. if (res.status == StatusCode::Continue_100) {
  11934. // Server accepted, send the body
  11935. if (!write_request_body(strm, req, error)) { return false; }
  11936. // Read the actual response
  11937. res.headers.clear();
  11938. res.body.clear();
  11939. if (!read_response_line(strm, req, res) ||
  11940. !detail::read_headers(strm, res.headers)) {
  11941. error = Error::Read;
  11942. output_error_log(error, &req);
  11943. return false;
  11944. }
  11945. }
  11946. // If not 100 Continue, server returned an error; proceed with that response
  11947. }
  11948. // Body
  11949. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11950. req.method != "CONNECT") {
  11951. auto redirect = 300 < res.status && res.status < 400 &&
  11952. res.status != StatusCode::NotModified_304 &&
  11953. follow_location_;
  11954. if (req.response_handler && !redirect) {
  11955. if (!req.response_handler(res)) {
  11956. error = Error::Canceled;
  11957. output_error_log(error, &req);
  11958. return false;
  11959. }
  11960. }
  11961. auto out =
  11962. req.content_receiver
  11963. ? static_cast<ContentReceiverWithProgress>(
  11964. [&](const char *buf, size_t n, size_t off, size_t len) {
  11965. if (redirect) { return true; }
  11966. auto ret = req.content_receiver(buf, n, off, len);
  11967. if (!ret) {
  11968. error = Error::Canceled;
  11969. output_error_log(error, &req);
  11970. }
  11971. return ret;
  11972. })
  11973. : static_cast<ContentReceiverWithProgress>(
  11974. [&](const char *buf, size_t n, size_t /*off*/,
  11975. size_t /*len*/) {
  11976. assert(res.body.size() + n <= res.body.max_size());
  11977. if (payload_max_length_ > 0 &&
  11978. (res.body.size() >= payload_max_length_ ||
  11979. n > payload_max_length_ - res.body.size())) {
  11980. return false;
  11981. }
  11982. res.body.append(buf, n);
  11983. return true;
  11984. });
  11985. auto progress = [&](size_t current, size_t total) {
  11986. if (!req.download_progress || redirect) { return true; }
  11987. auto ret = req.download_progress(current, total);
  11988. if (!ret) {
  11989. error = Error::Canceled;
  11990. output_error_log(error, &req);
  11991. }
  11992. return ret;
  11993. };
  11994. if (res.has_header("Content-Length")) {
  11995. if (!req.content_receiver) {
  11996. auto len = res.get_header_value_u64("Content-Length");
  11997. if (len > res.body.max_size()) {
  11998. error = Error::Read;
  11999. output_error_log(error, &req);
  12000. return false;
  12001. }
  12002. // Cap the reservation by payload_max_length_ to avoid OOM when a
  12003. // hostile or malformed server sends an enormous Content-Length.
  12004. // The actual body read below is bounded by payload_max_length_,
  12005. // so reserving more than that is never useful.
  12006. auto reserve_len = static_cast<size_t>(len);
  12007. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  12008. reserve_len = payload_max_length_;
  12009. }
  12010. res.body.reserve(reserve_len);
  12011. }
  12012. }
  12013. if (res.status != StatusCode::NotModified_304) {
  12014. int dummy_status;
  12015. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  12016. ? (std::numeric_limits<size_t>::max)()
  12017. : payload_max_length_;
  12018. if (!detail::read_content(strm, res, max_length, dummy_status,
  12019. std::move(progress), std::move(out),
  12020. decompress_)) {
  12021. if (error != Error::Canceled) { error = Error::Read; }
  12022. output_error_log(error, &req);
  12023. return false;
  12024. }
  12025. }
  12026. }
  12027. // Log
  12028. output_log(req, res);
  12029. return true;
  12030. }
  12031. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  12032. const std::string &boundary, const UploadFormDataItems &items,
  12033. const FormDataProviderItems &provider_items) const {
  12034. size_t cur_item = 0;
  12035. size_t cur_start = 0;
  12036. // cur_item and cur_start are copied to within the std::function and
  12037. // maintain state between successive calls
  12038. return [&, cur_item, cur_start](size_t offset,
  12039. DataSink &sink) mutable -> bool {
  12040. if (!offset && !items.empty()) {
  12041. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12042. return true;
  12043. } else if (cur_item < provider_items.size()) {
  12044. if (!cur_start) {
  12045. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12046. provider_items[cur_item], boundary);
  12047. offset += begin.size();
  12048. cur_start = offset;
  12049. sink.os << begin;
  12050. }
  12051. DataSink cur_sink;
  12052. auto has_data = true;
  12053. cur_sink.write = sink.write;
  12054. cur_sink.done = [&]() { has_data = false; };
  12055. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12056. return false;
  12057. }
  12058. if (!has_data) {
  12059. sink.os << detail::serialize_multipart_formdata_item_end();
  12060. cur_item++;
  12061. cur_start = 0;
  12062. }
  12063. return true;
  12064. } else {
  12065. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12066. sink.done();
  12067. return true;
  12068. }
  12069. };
  12070. }
  12071. inline bool ClientImpl::process_socket(
  12072. const Socket &socket,
  12073. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12074. std::function<bool(Stream &strm)> callback) {
  12075. return detail::process_client_socket(
  12076. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12077. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12078. }
  12079. inline bool ClientImpl::is_ssl() const { return false; }
  12080. inline Result ClientImpl::Get(const std::string &path,
  12081. DownloadProgress progress) {
  12082. return Get(path, Headers(), std::move(progress));
  12083. }
  12084. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12085. DownloadProgress progress) {
  12086. return Get(path, params, Headers(), std::move(progress));
  12087. }
  12088. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12089. const Headers &headers,
  12090. DownloadProgress progress) {
  12091. if (params.empty()) { return Get(path, headers); }
  12092. std::string path_with_query = append_query_params(path, params);
  12093. return Get(path_with_query, headers, std::move(progress));
  12094. }
  12095. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12096. DownloadProgress progress) {
  12097. Request req;
  12098. req.method = "GET";
  12099. req.path = path;
  12100. req.headers = headers;
  12101. req.download_progress = std::move(progress);
  12102. if (max_timeout_msec_ > 0) {
  12103. req.start_time_ = std::chrono::steady_clock::now();
  12104. }
  12105. return send_(std::move(req));
  12106. }
  12107. inline Result ClientImpl::Get(const std::string &path,
  12108. ContentReceiver content_receiver,
  12109. DownloadProgress progress) {
  12110. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12111. std::move(progress));
  12112. }
  12113. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12114. ContentReceiver content_receiver,
  12115. DownloadProgress progress) {
  12116. return Get(path, headers, nullptr, std::move(content_receiver),
  12117. std::move(progress));
  12118. }
  12119. inline Result ClientImpl::Get(const std::string &path,
  12120. ResponseHandler response_handler,
  12121. ContentReceiver content_receiver,
  12122. DownloadProgress progress) {
  12123. return Get(path, Headers(), std::move(response_handler),
  12124. std::move(content_receiver), std::move(progress));
  12125. }
  12126. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12127. ResponseHandler response_handler,
  12128. ContentReceiver content_receiver,
  12129. DownloadProgress progress) {
  12130. Request req;
  12131. req.method = "GET";
  12132. req.path = path;
  12133. req.headers = headers;
  12134. req.response_handler = std::move(response_handler);
  12135. req.content_receiver =
  12136. [content_receiver](const char *data, size_t data_length,
  12137. size_t /*offset*/, size_t /*total_length*/) {
  12138. return content_receiver(data, data_length);
  12139. };
  12140. req.download_progress = std::move(progress);
  12141. if (max_timeout_msec_ > 0) {
  12142. req.start_time_ = std::chrono::steady_clock::now();
  12143. }
  12144. return send_(std::move(req));
  12145. }
  12146. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12147. const Headers &headers,
  12148. ContentReceiver content_receiver,
  12149. DownloadProgress progress) {
  12150. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12151. std::move(progress));
  12152. }
  12153. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12154. const Headers &headers,
  12155. ResponseHandler response_handler,
  12156. ContentReceiver content_receiver,
  12157. DownloadProgress progress) {
  12158. if (params.empty()) {
  12159. return Get(path, headers, std::move(response_handler),
  12160. std::move(content_receiver), std::move(progress));
  12161. }
  12162. std::string path_with_query = append_query_params(path, params);
  12163. return Get(path_with_query, headers, std::move(response_handler),
  12164. std::move(content_receiver), std::move(progress));
  12165. }
  12166. inline Result ClientImpl::Head(const std::string &path) {
  12167. return Head(path, Headers());
  12168. }
  12169. inline Result ClientImpl::Head(const std::string &path,
  12170. const Headers &headers) {
  12171. Request req;
  12172. req.method = "HEAD";
  12173. req.headers = headers;
  12174. req.path = path;
  12175. if (max_timeout_msec_ > 0) {
  12176. req.start_time_ = std::chrono::steady_clock::now();
  12177. }
  12178. return send_(std::move(req));
  12179. }
  12180. inline Result ClientImpl::Post(const std::string &path) {
  12181. return Post(path, std::string(), std::string());
  12182. }
  12183. inline Result ClientImpl::Post(const std::string &path,
  12184. const Headers &headers) {
  12185. return Post(path, headers, nullptr, 0, std::string());
  12186. }
  12187. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12188. size_t content_length,
  12189. const std::string &content_type,
  12190. UploadProgress progress) {
  12191. return Post(path, Headers(), body, content_length, content_type, progress);
  12192. }
  12193. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12194. const std::string &content_type,
  12195. UploadProgress progress) {
  12196. return Post(path, Headers(), body, content_type, progress);
  12197. }
  12198. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12199. return Post(path, Headers(), params);
  12200. }
  12201. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12202. ContentProvider content_provider,
  12203. const std::string &content_type,
  12204. UploadProgress progress) {
  12205. return Post(path, Headers(), content_length, std::move(content_provider),
  12206. content_type, progress);
  12207. }
  12208. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12209. ContentProvider content_provider,
  12210. const std::string &content_type,
  12211. ContentReceiver content_receiver,
  12212. UploadProgress progress) {
  12213. return Post(path, Headers(), content_length, std::move(content_provider),
  12214. content_type, std::move(content_receiver), progress);
  12215. }
  12216. inline Result ClientImpl::Post(const std::string &path,
  12217. ContentProviderWithoutLength content_provider,
  12218. const std::string &content_type,
  12219. UploadProgress progress) {
  12220. return Post(path, Headers(), std::move(content_provider), content_type,
  12221. progress);
  12222. }
  12223. inline Result ClientImpl::Post(const std::string &path,
  12224. ContentProviderWithoutLength content_provider,
  12225. const std::string &content_type,
  12226. ContentReceiver content_receiver,
  12227. UploadProgress progress) {
  12228. return Post(path, Headers(), std::move(content_provider), content_type,
  12229. std::move(content_receiver), progress);
  12230. }
  12231. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12232. const Params &params) {
  12233. auto query = detail::params_to_query_str(params);
  12234. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12235. }
  12236. inline Result ClientImpl::Post(const std::string &path,
  12237. const UploadFormDataItems &items,
  12238. UploadProgress progress) {
  12239. return Post(path, Headers(), items, progress);
  12240. }
  12241. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12242. const UploadFormDataItems &items,
  12243. UploadProgress progress) {
  12244. const auto &boundary = detail::make_multipart_data_boundary();
  12245. const auto &content_type =
  12246. detail::serialize_multipart_formdata_get_content_type(boundary);
  12247. auto content_length = detail::get_multipart_content_length(items, boundary);
  12248. return Post(path, headers, content_length,
  12249. detail::make_multipart_content_provider(items, boundary),
  12250. content_type, progress);
  12251. }
  12252. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12253. const UploadFormDataItems &items,
  12254. const std::string &boundary,
  12255. UploadProgress progress) {
  12256. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12257. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12258. }
  12259. const auto &content_type =
  12260. detail::serialize_multipart_formdata_get_content_type(boundary);
  12261. auto content_length = detail::get_multipart_content_length(items, boundary);
  12262. return Post(path, headers, content_length,
  12263. detail::make_multipart_content_provider(items, boundary),
  12264. content_type, progress);
  12265. }
  12266. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12267. const char *body, size_t content_length,
  12268. const std::string &content_type,
  12269. UploadProgress progress) {
  12270. return send_with_content_provider_and_receiver(
  12271. "POST", path, headers, body, content_length, nullptr, nullptr,
  12272. content_type, nullptr, progress);
  12273. }
  12274. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12275. const std::string &body,
  12276. const std::string &content_type,
  12277. UploadProgress progress) {
  12278. return send_with_content_provider_and_receiver(
  12279. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12280. content_type, nullptr, progress);
  12281. }
  12282. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12283. size_t content_length,
  12284. ContentProvider content_provider,
  12285. const std::string &content_type,
  12286. UploadProgress progress) {
  12287. return send_with_content_provider_and_receiver(
  12288. "POST", path, headers, nullptr, content_length,
  12289. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12290. }
  12291. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12292. size_t content_length,
  12293. ContentProvider content_provider,
  12294. const std::string &content_type,
  12295. ContentReceiver content_receiver,
  12296. DownloadProgress progress) {
  12297. return send_with_content_provider_and_receiver(
  12298. "POST", path, headers, nullptr, content_length,
  12299. std::move(content_provider), nullptr, content_type,
  12300. std::move(content_receiver), std::move(progress));
  12301. }
  12302. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12303. ContentProviderWithoutLength content_provider,
  12304. const std::string &content_type,
  12305. UploadProgress progress) {
  12306. return send_with_content_provider_and_receiver(
  12307. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12308. content_type, nullptr, progress);
  12309. }
  12310. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12311. ContentProviderWithoutLength content_provider,
  12312. const std::string &content_type,
  12313. ContentReceiver content_receiver,
  12314. DownloadProgress progress) {
  12315. return send_with_content_provider_and_receiver(
  12316. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12317. content_type, std::move(content_receiver), std::move(progress));
  12318. }
  12319. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12320. const UploadFormDataItems &items,
  12321. const FormDataProviderItems &provider_items,
  12322. UploadProgress progress) {
  12323. const auto &boundary = detail::make_multipart_data_boundary();
  12324. const auto &content_type =
  12325. detail::serialize_multipart_formdata_get_content_type(boundary);
  12326. return send_with_content_provider_and_receiver(
  12327. "POST", path, headers, nullptr, 0, nullptr,
  12328. get_multipart_content_provider(boundary, items, provider_items),
  12329. content_type, nullptr, progress);
  12330. }
  12331. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12332. const std::string &body,
  12333. const std::string &content_type,
  12334. ContentReceiver content_receiver,
  12335. DownloadProgress progress) {
  12336. Request req;
  12337. req.method = "POST";
  12338. req.path = path;
  12339. req.headers = headers;
  12340. req.body = body;
  12341. req.content_receiver =
  12342. [content_receiver](const char *data, size_t data_length,
  12343. size_t /*offset*/, size_t /*total_length*/) {
  12344. return content_receiver(data, data_length);
  12345. };
  12346. req.download_progress = std::move(progress);
  12347. if (max_timeout_msec_ > 0) {
  12348. req.start_time_ = std::chrono::steady_clock::now();
  12349. }
  12350. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12351. return send_(std::move(req));
  12352. }
  12353. inline Result ClientImpl::Put(const std::string &path) {
  12354. return Put(path, std::string(), std::string());
  12355. }
  12356. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12357. return Put(path, headers, nullptr, 0, std::string());
  12358. }
  12359. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12360. size_t content_length,
  12361. const std::string &content_type,
  12362. UploadProgress progress) {
  12363. return Put(path, Headers(), body, content_length, content_type, progress);
  12364. }
  12365. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12366. const std::string &content_type,
  12367. UploadProgress progress) {
  12368. return Put(path, Headers(), body, content_type, progress);
  12369. }
  12370. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12371. return Put(path, Headers(), params);
  12372. }
  12373. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12374. ContentProvider content_provider,
  12375. const std::string &content_type,
  12376. UploadProgress progress) {
  12377. return Put(path, Headers(), content_length, std::move(content_provider),
  12378. content_type, progress);
  12379. }
  12380. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12381. ContentProvider content_provider,
  12382. const std::string &content_type,
  12383. ContentReceiver content_receiver,
  12384. UploadProgress progress) {
  12385. return Put(path, Headers(), content_length, std::move(content_provider),
  12386. content_type, std::move(content_receiver), progress);
  12387. }
  12388. inline Result ClientImpl::Put(const std::string &path,
  12389. ContentProviderWithoutLength content_provider,
  12390. const std::string &content_type,
  12391. UploadProgress progress) {
  12392. return Put(path, Headers(), std::move(content_provider), content_type,
  12393. progress);
  12394. }
  12395. inline Result ClientImpl::Put(const std::string &path,
  12396. ContentProviderWithoutLength content_provider,
  12397. const std::string &content_type,
  12398. ContentReceiver content_receiver,
  12399. UploadProgress progress) {
  12400. return Put(path, Headers(), std::move(content_provider), content_type,
  12401. std::move(content_receiver), progress);
  12402. }
  12403. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12404. const Params &params) {
  12405. auto query = detail::params_to_query_str(params);
  12406. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12407. }
  12408. inline Result ClientImpl::Put(const std::string &path,
  12409. const UploadFormDataItems &items,
  12410. UploadProgress progress) {
  12411. return Put(path, Headers(), items, progress);
  12412. }
  12413. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12414. const UploadFormDataItems &items,
  12415. UploadProgress progress) {
  12416. const auto &boundary = detail::make_multipart_data_boundary();
  12417. const auto &content_type =
  12418. detail::serialize_multipart_formdata_get_content_type(boundary);
  12419. auto content_length = detail::get_multipart_content_length(items, boundary);
  12420. return Put(path, headers, content_length,
  12421. detail::make_multipart_content_provider(items, boundary),
  12422. content_type, progress);
  12423. }
  12424. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12425. const UploadFormDataItems &items,
  12426. const std::string &boundary,
  12427. UploadProgress progress) {
  12428. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12429. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12430. }
  12431. const auto &content_type =
  12432. detail::serialize_multipart_formdata_get_content_type(boundary);
  12433. auto content_length = detail::get_multipart_content_length(items, boundary);
  12434. return Put(path, headers, content_length,
  12435. detail::make_multipart_content_provider(items, boundary),
  12436. content_type, progress);
  12437. }
  12438. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12439. const char *body, size_t content_length,
  12440. const std::string &content_type,
  12441. UploadProgress progress) {
  12442. return send_with_content_provider_and_receiver(
  12443. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12444. content_type, nullptr, progress);
  12445. }
  12446. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12447. const std::string &body,
  12448. const std::string &content_type,
  12449. UploadProgress progress) {
  12450. return send_with_content_provider_and_receiver(
  12451. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12452. content_type, nullptr, progress);
  12453. }
  12454. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12455. size_t content_length,
  12456. ContentProvider content_provider,
  12457. const std::string &content_type,
  12458. UploadProgress progress) {
  12459. return send_with_content_provider_and_receiver(
  12460. "PUT", path, headers, nullptr, content_length,
  12461. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12462. }
  12463. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12464. size_t content_length,
  12465. ContentProvider content_provider,
  12466. const std::string &content_type,
  12467. ContentReceiver content_receiver,
  12468. UploadProgress progress) {
  12469. return send_with_content_provider_and_receiver(
  12470. "PUT", path, headers, nullptr, content_length,
  12471. std::move(content_provider), nullptr, content_type,
  12472. std::move(content_receiver), progress);
  12473. }
  12474. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12475. ContentProviderWithoutLength content_provider,
  12476. const std::string &content_type,
  12477. UploadProgress progress) {
  12478. return send_with_content_provider_and_receiver(
  12479. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12480. content_type, nullptr, progress);
  12481. }
  12482. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12483. ContentProviderWithoutLength content_provider,
  12484. const std::string &content_type,
  12485. ContentReceiver content_receiver,
  12486. UploadProgress progress) {
  12487. return send_with_content_provider_and_receiver(
  12488. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12489. content_type, std::move(content_receiver), progress);
  12490. }
  12491. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12492. const UploadFormDataItems &items,
  12493. const FormDataProviderItems &provider_items,
  12494. UploadProgress progress) {
  12495. const auto &boundary = detail::make_multipart_data_boundary();
  12496. const auto &content_type =
  12497. detail::serialize_multipart_formdata_get_content_type(boundary);
  12498. return send_with_content_provider_and_receiver(
  12499. "PUT", path, headers, nullptr, 0, nullptr,
  12500. get_multipart_content_provider(boundary, items, provider_items),
  12501. content_type, nullptr, progress);
  12502. }
  12503. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12504. const std::string &body,
  12505. const std::string &content_type,
  12506. ContentReceiver content_receiver,
  12507. DownloadProgress progress) {
  12508. Request req;
  12509. req.method = "PUT";
  12510. req.path = path;
  12511. req.headers = headers;
  12512. req.body = body;
  12513. req.content_receiver =
  12514. [content_receiver](const char *data, size_t data_length,
  12515. size_t /*offset*/, size_t /*total_length*/) {
  12516. return content_receiver(data, data_length);
  12517. };
  12518. req.download_progress = std::move(progress);
  12519. if (max_timeout_msec_ > 0) {
  12520. req.start_time_ = std::chrono::steady_clock::now();
  12521. }
  12522. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12523. return send_(std::move(req));
  12524. }
  12525. inline Result ClientImpl::Patch(const std::string &path) {
  12526. return Patch(path, std::string(), std::string());
  12527. }
  12528. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12529. UploadProgress progress) {
  12530. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12531. }
  12532. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12533. size_t content_length,
  12534. const std::string &content_type,
  12535. UploadProgress progress) {
  12536. return Patch(path, Headers(), body, content_length, content_type, progress);
  12537. }
  12538. inline Result ClientImpl::Patch(const std::string &path,
  12539. const std::string &body,
  12540. const std::string &content_type,
  12541. UploadProgress progress) {
  12542. return Patch(path, Headers(), body, content_type, progress);
  12543. }
  12544. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12545. return Patch(path, Headers(), params);
  12546. }
  12547. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12548. ContentProvider content_provider,
  12549. const std::string &content_type,
  12550. UploadProgress progress) {
  12551. return Patch(path, Headers(), content_length, std::move(content_provider),
  12552. content_type, progress);
  12553. }
  12554. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12555. ContentProvider content_provider,
  12556. const std::string &content_type,
  12557. ContentReceiver content_receiver,
  12558. UploadProgress progress) {
  12559. return Patch(path, Headers(), content_length, std::move(content_provider),
  12560. content_type, std::move(content_receiver), progress);
  12561. }
  12562. inline Result ClientImpl::Patch(const std::string &path,
  12563. ContentProviderWithoutLength content_provider,
  12564. const std::string &content_type,
  12565. UploadProgress progress) {
  12566. return Patch(path, Headers(), std::move(content_provider), content_type,
  12567. progress);
  12568. }
  12569. inline Result ClientImpl::Patch(const std::string &path,
  12570. ContentProviderWithoutLength content_provider,
  12571. const std::string &content_type,
  12572. ContentReceiver content_receiver,
  12573. UploadProgress progress) {
  12574. return Patch(path, Headers(), std::move(content_provider), content_type,
  12575. std::move(content_receiver), progress);
  12576. }
  12577. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12578. const Params &params) {
  12579. auto query = detail::params_to_query_str(params);
  12580. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12581. }
  12582. inline Result ClientImpl::Patch(const std::string &path,
  12583. const UploadFormDataItems &items,
  12584. UploadProgress progress) {
  12585. return Patch(path, Headers(), items, progress);
  12586. }
  12587. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12588. const UploadFormDataItems &items,
  12589. UploadProgress progress) {
  12590. const auto &boundary = detail::make_multipart_data_boundary();
  12591. const auto &content_type =
  12592. detail::serialize_multipart_formdata_get_content_type(boundary);
  12593. auto content_length = detail::get_multipart_content_length(items, boundary);
  12594. return Patch(path, headers, content_length,
  12595. detail::make_multipart_content_provider(items, boundary),
  12596. content_type, progress);
  12597. }
  12598. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12599. const UploadFormDataItems &items,
  12600. const std::string &boundary,
  12601. UploadProgress progress) {
  12602. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12603. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12604. }
  12605. const auto &content_type =
  12606. detail::serialize_multipart_formdata_get_content_type(boundary);
  12607. auto content_length = detail::get_multipart_content_length(items, boundary);
  12608. return Patch(path, headers, content_length,
  12609. detail::make_multipart_content_provider(items, boundary),
  12610. content_type, progress);
  12611. }
  12612. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12613. const char *body, size_t content_length,
  12614. const std::string &content_type,
  12615. UploadProgress progress) {
  12616. return send_with_content_provider_and_receiver(
  12617. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12618. content_type, nullptr, progress);
  12619. }
  12620. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12621. const std::string &body,
  12622. const std::string &content_type,
  12623. UploadProgress progress) {
  12624. return send_with_content_provider_and_receiver(
  12625. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12626. content_type, nullptr, progress);
  12627. }
  12628. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12629. size_t content_length,
  12630. ContentProvider content_provider,
  12631. const std::string &content_type,
  12632. UploadProgress progress) {
  12633. return send_with_content_provider_and_receiver(
  12634. "PATCH", path, headers, nullptr, content_length,
  12635. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12636. }
  12637. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12638. size_t content_length,
  12639. ContentProvider content_provider,
  12640. const std::string &content_type,
  12641. ContentReceiver content_receiver,
  12642. UploadProgress progress) {
  12643. return send_with_content_provider_and_receiver(
  12644. "PATCH", path, headers, nullptr, content_length,
  12645. std::move(content_provider), nullptr, content_type,
  12646. std::move(content_receiver), progress);
  12647. }
  12648. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12649. ContentProviderWithoutLength content_provider,
  12650. const std::string &content_type,
  12651. UploadProgress progress) {
  12652. return send_with_content_provider_and_receiver(
  12653. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12654. content_type, nullptr, progress);
  12655. }
  12656. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12657. ContentProviderWithoutLength content_provider,
  12658. const std::string &content_type,
  12659. ContentReceiver content_receiver,
  12660. UploadProgress progress) {
  12661. return send_with_content_provider_and_receiver(
  12662. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12663. content_type, std::move(content_receiver), progress);
  12664. }
  12665. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12666. const UploadFormDataItems &items,
  12667. const FormDataProviderItems &provider_items,
  12668. UploadProgress progress) {
  12669. const auto &boundary = detail::make_multipart_data_boundary();
  12670. const auto &content_type =
  12671. detail::serialize_multipart_formdata_get_content_type(boundary);
  12672. return send_with_content_provider_and_receiver(
  12673. "PATCH", path, headers, nullptr, 0, nullptr,
  12674. get_multipart_content_provider(boundary, items, provider_items),
  12675. content_type, nullptr, progress);
  12676. }
  12677. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12678. const std::string &body,
  12679. const std::string &content_type,
  12680. ContentReceiver content_receiver,
  12681. DownloadProgress progress) {
  12682. Request req;
  12683. req.method = "PATCH";
  12684. req.path = path;
  12685. req.headers = headers;
  12686. req.body = body;
  12687. req.content_receiver =
  12688. [content_receiver](const char *data, size_t data_length,
  12689. size_t /*offset*/, size_t /*total_length*/) {
  12690. return content_receiver(data, data_length);
  12691. };
  12692. req.download_progress = std::move(progress);
  12693. if (max_timeout_msec_ > 0) {
  12694. req.start_time_ = std::chrono::steady_clock::now();
  12695. }
  12696. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12697. return send_(std::move(req));
  12698. }
  12699. inline Result ClientImpl::Delete(const std::string &path,
  12700. DownloadProgress progress) {
  12701. return Delete(path, Headers(), std::string(), std::string(), progress);
  12702. }
  12703. inline Result ClientImpl::Delete(const std::string &path,
  12704. const Headers &headers,
  12705. DownloadProgress progress) {
  12706. return Delete(path, headers, std::string(), std::string(), progress);
  12707. }
  12708. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12709. size_t content_length,
  12710. const std::string &content_type,
  12711. DownloadProgress progress) {
  12712. return Delete(path, Headers(), body, content_length, content_type, progress);
  12713. }
  12714. inline Result ClientImpl::Delete(const std::string &path,
  12715. const std::string &body,
  12716. const std::string &content_type,
  12717. DownloadProgress progress) {
  12718. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12719. progress);
  12720. }
  12721. inline Result ClientImpl::Delete(const std::string &path,
  12722. const Headers &headers,
  12723. const std::string &body,
  12724. const std::string &content_type,
  12725. DownloadProgress progress) {
  12726. return Delete(path, headers, body.data(), body.size(), content_type,
  12727. progress);
  12728. }
  12729. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12730. DownloadProgress progress) {
  12731. return Delete(path, Headers(), params, progress);
  12732. }
  12733. inline Result ClientImpl::Delete(const std::string &path,
  12734. const Headers &headers, const Params &params,
  12735. DownloadProgress progress) {
  12736. auto query = detail::params_to_query_str(params);
  12737. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12738. progress);
  12739. }
  12740. inline Result ClientImpl::Delete(const std::string &path,
  12741. const Headers &headers, const char *body,
  12742. size_t content_length,
  12743. const std::string &content_type,
  12744. DownloadProgress progress) {
  12745. Request req;
  12746. req.method = "DELETE";
  12747. req.headers = headers;
  12748. req.path = path;
  12749. req.download_progress = std::move(progress);
  12750. if (max_timeout_msec_ > 0) {
  12751. req.start_time_ = std::chrono::steady_clock::now();
  12752. }
  12753. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12754. req.body.assign(body, content_length);
  12755. return send_(std::move(req));
  12756. }
  12757. inline Result ClientImpl::Options(const std::string &path) {
  12758. return Options(path, Headers());
  12759. }
  12760. inline Result ClientImpl::Options(const std::string &path,
  12761. const Headers &headers) {
  12762. Request req;
  12763. req.method = "OPTIONS";
  12764. req.headers = headers;
  12765. req.path = path;
  12766. if (max_timeout_msec_ > 0) {
  12767. req.start_time_ = std::chrono::steady_clock::now();
  12768. }
  12769. return send_(std::move(req));
  12770. }
  12771. inline void ClientImpl::stop() {
  12772. std::lock_guard<std::mutex> guard(socket_mutex_);
  12773. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12774. // do is to shutdown_socket, so that threads using this socket suddenly
  12775. // discover they can't read/write any more and error out. Everything else
  12776. // (closing the socket, shutting ssl down) is unsafe because these actions
  12777. // are not thread-safe.
  12778. if (socket_requests_in_flight_ > 0) {
  12779. shutdown_socket(socket_);
  12780. // Aside from that, we set a flag for the socket to be closed when we're
  12781. // done.
  12782. socket_should_be_closed_when_request_is_done_ = true;
  12783. return;
  12784. }
  12785. disconnect(/*gracefully=*/true);
  12786. }
  12787. inline std::string ClientImpl::host() const { return host_; }
  12788. inline int ClientImpl::port() const { return port_; }
  12789. inline size_t ClientImpl::is_socket_open() const {
  12790. std::lock_guard<std::mutex> guard(socket_mutex_);
  12791. return socket_.is_open();
  12792. }
  12793. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12794. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12795. connection_timeout_sec_ = sec;
  12796. connection_timeout_usec_ = usec;
  12797. }
  12798. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12799. read_timeout_sec_ = sec;
  12800. read_timeout_usec_ = usec;
  12801. }
  12802. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12803. write_timeout_sec_ = sec;
  12804. write_timeout_usec_ = usec;
  12805. }
  12806. inline void ClientImpl::set_max_timeout(time_t msec) {
  12807. max_timeout_msec_ = msec;
  12808. }
  12809. inline void ClientImpl::set_basic_auth(const std::string &username,
  12810. const std::string &password) {
  12811. basic_auth_username_ = username;
  12812. basic_auth_password_ = password;
  12813. }
  12814. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12815. bearer_token_auth_token_ = token;
  12816. }
  12817. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12818. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12819. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12820. inline void
  12821. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12822. addr_map_ = std::move(addr_map);
  12823. }
  12824. inline void ClientImpl::set_default_headers(Headers headers) {
  12825. default_headers_ = std::move(headers);
  12826. }
  12827. inline void ClientImpl::set_header_writer(
  12828. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12829. header_writer_ = writer;
  12830. }
  12831. inline void ClientImpl::set_address_family(int family) {
  12832. address_family_ = family;
  12833. }
  12834. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12835. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12836. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12837. socket_options_ = std::move(socket_options);
  12838. }
  12839. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12840. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12841. inline void ClientImpl::set_payload_max_length(size_t length) {
  12842. payload_max_length_ = length;
  12843. has_payload_max_length_ = true;
  12844. }
  12845. inline void ClientImpl::set_interface(const std::string &intf) {
  12846. interface_ = intf;
  12847. }
  12848. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12849. proxy_host_ = host;
  12850. proxy_port_ = port;
  12851. std::lock_guard<std::mutex> guard(socket_mutex_);
  12852. disconnect(/*gracefully=*/true);
  12853. }
  12854. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12855. const std::string &password) {
  12856. proxy_basic_auth_username_ = username;
  12857. proxy_basic_auth_password_ = password;
  12858. }
  12859. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12860. proxy_bearer_token_auth_token_ = token;
  12861. }
  12862. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12863. std::vector<detail::NoProxyEntry> parsed;
  12864. parsed.reserve(patterns.size());
  12865. for (const auto &p : patterns) {
  12866. auto trimmed = detail::trim_copy(p);
  12867. if (trimmed.empty()) { continue; }
  12868. detail::NoProxyEntry entry;
  12869. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12870. parsed.push_back(std::move(entry));
  12871. }
  12872. }
  12873. no_proxy_entries_ = std::move(parsed);
  12874. std::lock_guard<std::mutex> guard(socket_mutex_);
  12875. disconnect(/*gracefully=*/true);
  12876. }
  12877. #ifdef CPPHTTPLIB_SSL_ENABLED
  12878. inline void ClientImpl::set_digest_auth(const std::string &username,
  12879. const std::string &password) {
  12880. digest_auth_username_ = username;
  12881. digest_auth_password_ = password;
  12882. }
  12883. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12884. const std::string &ca_cert_dir_path) {
  12885. ca_cert_file_path_ = ca_cert_file_path;
  12886. ca_cert_dir_path_ = ca_cert_dir_path;
  12887. }
  12888. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12889. const std::string &password) {
  12890. proxy_digest_auth_username_ = username;
  12891. proxy_digest_auth_password_ = password;
  12892. }
  12893. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12894. server_certificate_verification_ = enabled;
  12895. }
  12896. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12897. server_hostname_verification_ = enabled;
  12898. }
  12899. inline void ClientImpl::enable_system_ca(bool enabled) {
  12900. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12901. }
  12902. #endif
  12903. inline void ClientImpl::set_logger(Logger logger) {
  12904. logger_ = std::move(logger);
  12905. }
  12906. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12907. error_logger_ = std::move(error_logger);
  12908. }
  12909. /*
  12910. * SSL/TLS Common Implementation
  12911. */
  12912. inline ClientConnection::~ClientConnection() {
  12913. #ifdef CPPHTTPLIB_SSL_ENABLED
  12914. if (session) {
  12915. tls::shutdown(session, true);
  12916. tls::free_session(session);
  12917. session = nullptr;
  12918. }
  12919. #endif
  12920. if (sock != INVALID_SOCKET) {
  12921. detail::close_socket(sock);
  12922. sock = INVALID_SOCKET;
  12923. }
  12924. }
  12925. // Universal client implementation
  12926. inline Client::Client(const std::string &scheme_host_port)
  12927. : Client(scheme_host_port, std::string(), std::string()) {}
  12928. inline Client::Client(const std::string &scheme_host_port,
  12929. const std::string &client_cert_path,
  12930. const std::string &client_key_path) {
  12931. detail::UrlComponents uc;
  12932. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12933. auto &scheme = uc.scheme;
  12934. #ifdef CPPHTTPLIB_SSL_ENABLED
  12935. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12936. #else
  12937. if (!scheme.empty() && scheme != "http") {
  12938. #endif
  12939. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12940. std::string msg = "'" + scheme + "' scheme is not supported.";
  12941. throw std::invalid_argument(msg);
  12942. #endif
  12943. return;
  12944. }
  12945. auto is_ssl = scheme == "https";
  12946. auto host = std::move(uc.host);
  12947. auto port = is_ssl ? 443 : 80;
  12948. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12949. if (is_ssl) {
  12950. #ifdef CPPHTTPLIB_SSL_ENABLED
  12951. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12952. client_key_path);
  12953. is_ssl_ = is_ssl;
  12954. #endif
  12955. } else {
  12956. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12957. client_key_path);
  12958. }
  12959. } else {
  12960. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12961. // if port param below changes.
  12962. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12963. client_cert_path, client_key_path);
  12964. }
  12965. }
  12966. inline Client::Client(const std::string &host, int port)
  12967. : Client(host, port, std::string(), std::string()) {}
  12968. inline Client::Client(const std::string &host, int port,
  12969. const std::string &client_cert_path,
  12970. const std::string &client_key_path)
  12971. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12972. client_key_path)) {}
  12973. inline Client::~Client() = default;
  12974. inline bool Client::is_valid() const {
  12975. return cli_ != nullptr && cli_->is_valid();
  12976. }
  12977. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12978. return cli_->Get(path, std::move(progress));
  12979. }
  12980. inline Result Client::Get(const std::string &path, const Headers &headers,
  12981. DownloadProgress progress) {
  12982. return cli_->Get(path, headers, std::move(progress));
  12983. }
  12984. inline Result Client::Get(const std::string &path,
  12985. ContentReceiver content_receiver,
  12986. DownloadProgress progress) {
  12987. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12988. }
  12989. inline Result Client::Get(const std::string &path, const Headers &headers,
  12990. ContentReceiver content_receiver,
  12991. DownloadProgress progress) {
  12992. return cli_->Get(path, headers, std::move(content_receiver),
  12993. std::move(progress));
  12994. }
  12995. inline Result Client::Get(const std::string &path,
  12996. ResponseHandler response_handler,
  12997. ContentReceiver content_receiver,
  12998. DownloadProgress progress) {
  12999. return cli_->Get(path, std::move(response_handler),
  13000. std::move(content_receiver), std::move(progress));
  13001. }
  13002. inline Result Client::Get(const std::string &path, const Headers &headers,
  13003. ResponseHandler response_handler,
  13004. ContentReceiver content_receiver,
  13005. DownloadProgress progress) {
  13006. return cli_->Get(path, headers, std::move(response_handler),
  13007. std::move(content_receiver), std::move(progress));
  13008. }
  13009. inline Result Client::Get(const std::string &path, const Params &params,
  13010. DownloadProgress progress) {
  13011. return cli_->Get(path, params, std::move(progress));
  13012. }
  13013. inline Result Client::Get(const std::string &path, const Params &params,
  13014. const Headers &headers, DownloadProgress progress) {
  13015. return cli_->Get(path, params, headers, std::move(progress));
  13016. }
  13017. inline Result Client::Get(const std::string &path, const Params &params,
  13018. const Headers &headers,
  13019. ContentReceiver content_receiver,
  13020. DownloadProgress progress) {
  13021. return cli_->Get(path, params, headers, std::move(content_receiver),
  13022. std::move(progress));
  13023. }
  13024. inline Result Client::Get(const std::string &path, const Params &params,
  13025. const Headers &headers,
  13026. ResponseHandler response_handler,
  13027. ContentReceiver content_receiver,
  13028. DownloadProgress progress) {
  13029. return cli_->Get(path, params, headers, std::move(response_handler),
  13030. std::move(content_receiver), std::move(progress));
  13031. }
  13032. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13033. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13034. return cli_->Head(path, headers);
  13035. }
  13036. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13037. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13038. return cli_->Post(path, headers);
  13039. }
  13040. inline Result Client::Post(const std::string &path, const char *body,
  13041. size_t content_length,
  13042. const std::string &content_type,
  13043. UploadProgress progress) {
  13044. return cli_->Post(path, body, content_length, content_type, progress);
  13045. }
  13046. inline Result Client::Post(const std::string &path, const Headers &headers,
  13047. const char *body, size_t content_length,
  13048. const std::string &content_type,
  13049. UploadProgress progress) {
  13050. return cli_->Post(path, headers, body, content_length, content_type,
  13051. progress);
  13052. }
  13053. inline Result Client::Post(const std::string &path, const std::string &body,
  13054. const std::string &content_type,
  13055. UploadProgress progress) {
  13056. return cli_->Post(path, body, content_type, progress);
  13057. }
  13058. inline Result Client::Post(const std::string &path, const Headers &headers,
  13059. const std::string &body,
  13060. const std::string &content_type,
  13061. UploadProgress progress) {
  13062. return cli_->Post(path, headers, body, content_type, progress);
  13063. }
  13064. inline Result Client::Post(const std::string &path, size_t content_length,
  13065. ContentProvider content_provider,
  13066. const std::string &content_type,
  13067. UploadProgress progress) {
  13068. return cli_->Post(path, content_length, std::move(content_provider),
  13069. content_type, progress);
  13070. }
  13071. inline Result Client::Post(const std::string &path, size_t content_length,
  13072. ContentProvider content_provider,
  13073. const std::string &content_type,
  13074. ContentReceiver content_receiver,
  13075. UploadProgress progress) {
  13076. return cli_->Post(path, content_length, std::move(content_provider),
  13077. content_type, std::move(content_receiver), progress);
  13078. }
  13079. inline Result Client::Post(const std::string &path,
  13080. ContentProviderWithoutLength content_provider,
  13081. const std::string &content_type,
  13082. UploadProgress progress) {
  13083. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13084. }
  13085. inline Result Client::Post(const std::string &path,
  13086. ContentProviderWithoutLength content_provider,
  13087. const std::string &content_type,
  13088. ContentReceiver content_receiver,
  13089. UploadProgress progress) {
  13090. return cli_->Post(path, std::move(content_provider), content_type,
  13091. std::move(content_receiver), progress);
  13092. }
  13093. inline Result Client::Post(const std::string &path, const Headers &headers,
  13094. size_t content_length,
  13095. ContentProvider content_provider,
  13096. const std::string &content_type,
  13097. UploadProgress progress) {
  13098. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13099. content_type, progress);
  13100. }
  13101. inline Result Client::Post(const std::string &path, const Headers &headers,
  13102. size_t content_length,
  13103. ContentProvider content_provider,
  13104. const std::string &content_type,
  13105. ContentReceiver content_receiver,
  13106. DownloadProgress progress) {
  13107. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13108. content_type, std::move(content_receiver), progress);
  13109. }
  13110. inline Result Client::Post(const std::string &path, const Headers &headers,
  13111. ContentProviderWithoutLength content_provider,
  13112. const std::string &content_type,
  13113. UploadProgress progress) {
  13114. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13115. progress);
  13116. }
  13117. inline Result Client::Post(const std::string &path, const Headers &headers,
  13118. ContentProviderWithoutLength content_provider,
  13119. const std::string &content_type,
  13120. ContentReceiver content_receiver,
  13121. DownloadProgress progress) {
  13122. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13123. std::move(content_receiver), progress);
  13124. }
  13125. inline Result Client::Post(const std::string &path, const Params &params) {
  13126. return cli_->Post(path, params);
  13127. }
  13128. inline Result Client::Post(const std::string &path, const Headers &headers,
  13129. const Params &params) {
  13130. return cli_->Post(path, headers, params);
  13131. }
  13132. inline Result Client::Post(const std::string &path,
  13133. const UploadFormDataItems &items,
  13134. UploadProgress progress) {
  13135. return cli_->Post(path, items, progress);
  13136. }
  13137. inline Result Client::Post(const std::string &path, const Headers &headers,
  13138. const UploadFormDataItems &items,
  13139. UploadProgress progress) {
  13140. return cli_->Post(path, headers, items, progress);
  13141. }
  13142. inline Result Client::Post(const std::string &path, const Headers &headers,
  13143. const UploadFormDataItems &items,
  13144. const std::string &boundary,
  13145. UploadProgress progress) {
  13146. return cli_->Post(path, headers, items, boundary, progress);
  13147. }
  13148. inline Result Client::Post(const std::string &path, const Headers &headers,
  13149. const UploadFormDataItems &items,
  13150. const FormDataProviderItems &provider_items,
  13151. UploadProgress progress) {
  13152. return cli_->Post(path, headers, items, provider_items, progress);
  13153. }
  13154. inline Result Client::Post(const std::string &path, const Headers &headers,
  13155. const std::string &body,
  13156. const std::string &content_type,
  13157. ContentReceiver content_receiver,
  13158. DownloadProgress progress) {
  13159. return cli_->Post(path, headers, body, content_type,
  13160. std::move(content_receiver), progress);
  13161. }
  13162. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13163. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13164. return cli_->Put(path, headers);
  13165. }
  13166. inline Result Client::Put(const std::string &path, const char *body,
  13167. size_t content_length,
  13168. const std::string &content_type,
  13169. UploadProgress progress) {
  13170. return cli_->Put(path, body, content_length, content_type, progress);
  13171. }
  13172. inline Result Client::Put(const std::string &path, const Headers &headers,
  13173. const char *body, size_t content_length,
  13174. const std::string &content_type,
  13175. UploadProgress progress) {
  13176. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13177. }
  13178. inline Result Client::Put(const std::string &path, const std::string &body,
  13179. const std::string &content_type,
  13180. UploadProgress progress) {
  13181. return cli_->Put(path, body, content_type, progress);
  13182. }
  13183. inline Result Client::Put(const std::string &path, const Headers &headers,
  13184. const std::string &body,
  13185. const std::string &content_type,
  13186. UploadProgress progress) {
  13187. return cli_->Put(path, headers, body, content_type, progress);
  13188. }
  13189. inline Result Client::Put(const std::string &path, size_t content_length,
  13190. ContentProvider content_provider,
  13191. const std::string &content_type,
  13192. UploadProgress progress) {
  13193. return cli_->Put(path, content_length, std::move(content_provider),
  13194. content_type, progress);
  13195. }
  13196. inline Result Client::Put(const std::string &path, size_t content_length,
  13197. ContentProvider content_provider,
  13198. const std::string &content_type,
  13199. ContentReceiver content_receiver,
  13200. UploadProgress progress) {
  13201. return cli_->Put(path, content_length, std::move(content_provider),
  13202. content_type, std::move(content_receiver), progress);
  13203. }
  13204. inline Result Client::Put(const std::string &path,
  13205. ContentProviderWithoutLength content_provider,
  13206. const std::string &content_type,
  13207. UploadProgress progress) {
  13208. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13209. }
  13210. inline Result Client::Put(const std::string &path,
  13211. ContentProviderWithoutLength content_provider,
  13212. const std::string &content_type,
  13213. ContentReceiver content_receiver,
  13214. UploadProgress progress) {
  13215. return cli_->Put(path, std::move(content_provider), content_type,
  13216. std::move(content_receiver), progress);
  13217. }
  13218. inline Result Client::Put(const std::string &path, const Headers &headers,
  13219. size_t content_length,
  13220. ContentProvider content_provider,
  13221. const std::string &content_type,
  13222. UploadProgress progress) {
  13223. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13224. content_type, progress);
  13225. }
  13226. inline Result Client::Put(const std::string &path, const Headers &headers,
  13227. size_t content_length,
  13228. ContentProvider content_provider,
  13229. const std::string &content_type,
  13230. ContentReceiver content_receiver,
  13231. UploadProgress progress) {
  13232. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13233. content_type, std::move(content_receiver), progress);
  13234. }
  13235. inline Result Client::Put(const std::string &path, const Headers &headers,
  13236. ContentProviderWithoutLength content_provider,
  13237. const std::string &content_type,
  13238. UploadProgress progress) {
  13239. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13240. progress);
  13241. }
  13242. inline Result Client::Put(const std::string &path, const Headers &headers,
  13243. ContentProviderWithoutLength content_provider,
  13244. const std::string &content_type,
  13245. ContentReceiver content_receiver,
  13246. UploadProgress progress) {
  13247. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13248. std::move(content_receiver), progress);
  13249. }
  13250. inline Result Client::Put(const std::string &path, const Params &params) {
  13251. return cli_->Put(path, params);
  13252. }
  13253. inline Result Client::Put(const std::string &path, const Headers &headers,
  13254. const Params &params) {
  13255. return cli_->Put(path, headers, params);
  13256. }
  13257. inline Result Client::Put(const std::string &path,
  13258. const UploadFormDataItems &items,
  13259. UploadProgress progress) {
  13260. return cli_->Put(path, items, progress);
  13261. }
  13262. inline Result Client::Put(const std::string &path, const Headers &headers,
  13263. const UploadFormDataItems &items,
  13264. UploadProgress progress) {
  13265. return cli_->Put(path, headers, items, progress);
  13266. }
  13267. inline Result Client::Put(const std::string &path, const Headers &headers,
  13268. const UploadFormDataItems &items,
  13269. const std::string &boundary,
  13270. UploadProgress progress) {
  13271. return cli_->Put(path, headers, items, boundary, progress);
  13272. }
  13273. inline Result Client::Put(const std::string &path, const Headers &headers,
  13274. const UploadFormDataItems &items,
  13275. const FormDataProviderItems &provider_items,
  13276. UploadProgress progress) {
  13277. return cli_->Put(path, headers, items, provider_items, progress);
  13278. }
  13279. inline Result Client::Put(const std::string &path, const Headers &headers,
  13280. const std::string &body,
  13281. const std::string &content_type,
  13282. ContentReceiver content_receiver,
  13283. DownloadProgress progress) {
  13284. return cli_->Put(path, headers, body, content_type, content_receiver,
  13285. progress);
  13286. }
  13287. inline Result Client::Patch(const std::string &path) {
  13288. return cli_->Patch(path);
  13289. }
  13290. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13291. return cli_->Patch(path, headers);
  13292. }
  13293. inline Result Client::Patch(const std::string &path, const char *body,
  13294. size_t content_length,
  13295. const std::string &content_type,
  13296. UploadProgress progress) {
  13297. return cli_->Patch(path, body, content_length, content_type, progress);
  13298. }
  13299. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13300. const char *body, size_t content_length,
  13301. const std::string &content_type,
  13302. UploadProgress progress) {
  13303. return cli_->Patch(path, headers, body, content_length, content_type,
  13304. progress);
  13305. }
  13306. inline Result Client::Patch(const std::string &path, const std::string &body,
  13307. const std::string &content_type,
  13308. UploadProgress progress) {
  13309. return cli_->Patch(path, body, content_type, progress);
  13310. }
  13311. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13312. const std::string &body,
  13313. const std::string &content_type,
  13314. UploadProgress progress) {
  13315. return cli_->Patch(path, headers, body, content_type, progress);
  13316. }
  13317. inline Result Client::Patch(const std::string &path, size_t content_length,
  13318. ContentProvider content_provider,
  13319. const std::string &content_type,
  13320. UploadProgress progress) {
  13321. return cli_->Patch(path, content_length, std::move(content_provider),
  13322. content_type, progress);
  13323. }
  13324. inline Result Client::Patch(const std::string &path, size_t content_length,
  13325. ContentProvider content_provider,
  13326. const std::string &content_type,
  13327. ContentReceiver content_receiver,
  13328. UploadProgress progress) {
  13329. return cli_->Patch(path, content_length, std::move(content_provider),
  13330. content_type, std::move(content_receiver), progress);
  13331. }
  13332. inline Result Client::Patch(const std::string &path,
  13333. ContentProviderWithoutLength content_provider,
  13334. const std::string &content_type,
  13335. UploadProgress progress) {
  13336. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13337. }
  13338. inline Result Client::Patch(const std::string &path,
  13339. ContentProviderWithoutLength content_provider,
  13340. const std::string &content_type,
  13341. ContentReceiver content_receiver,
  13342. UploadProgress progress) {
  13343. return cli_->Patch(path, std::move(content_provider), content_type,
  13344. std::move(content_receiver), progress);
  13345. }
  13346. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13347. size_t content_length,
  13348. ContentProvider content_provider,
  13349. const std::string &content_type,
  13350. UploadProgress progress) {
  13351. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13352. content_type, progress);
  13353. }
  13354. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13355. size_t content_length,
  13356. ContentProvider content_provider,
  13357. const std::string &content_type,
  13358. ContentReceiver content_receiver,
  13359. UploadProgress progress) {
  13360. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13361. content_type, std::move(content_receiver), progress);
  13362. }
  13363. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13364. ContentProviderWithoutLength content_provider,
  13365. const std::string &content_type,
  13366. UploadProgress progress) {
  13367. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13368. progress);
  13369. }
  13370. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13371. ContentProviderWithoutLength content_provider,
  13372. const std::string &content_type,
  13373. ContentReceiver content_receiver,
  13374. UploadProgress progress) {
  13375. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13376. std::move(content_receiver), progress);
  13377. }
  13378. inline Result Client::Patch(const std::string &path, const Params &params) {
  13379. return cli_->Patch(path, params);
  13380. }
  13381. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13382. const Params &params) {
  13383. return cli_->Patch(path, headers, params);
  13384. }
  13385. inline Result Client::Patch(const std::string &path,
  13386. const UploadFormDataItems &items,
  13387. UploadProgress progress) {
  13388. return cli_->Patch(path, items, progress);
  13389. }
  13390. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13391. const UploadFormDataItems &items,
  13392. UploadProgress progress) {
  13393. return cli_->Patch(path, headers, items, progress);
  13394. }
  13395. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13396. const UploadFormDataItems &items,
  13397. const std::string &boundary,
  13398. UploadProgress progress) {
  13399. return cli_->Patch(path, headers, items, boundary, progress);
  13400. }
  13401. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13402. const UploadFormDataItems &items,
  13403. const FormDataProviderItems &provider_items,
  13404. UploadProgress progress) {
  13405. return cli_->Patch(path, headers, items, provider_items, progress);
  13406. }
  13407. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13408. const std::string &body,
  13409. const std::string &content_type,
  13410. ContentReceiver content_receiver,
  13411. DownloadProgress progress) {
  13412. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13413. progress);
  13414. }
  13415. inline Result Client::Delete(const std::string &path,
  13416. DownloadProgress progress) {
  13417. return cli_->Delete(path, progress);
  13418. }
  13419. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13420. DownloadProgress progress) {
  13421. return cli_->Delete(path, headers, progress);
  13422. }
  13423. inline Result Client::Delete(const std::string &path, const char *body,
  13424. size_t content_length,
  13425. const std::string &content_type,
  13426. DownloadProgress progress) {
  13427. return cli_->Delete(path, body, content_length, content_type, progress);
  13428. }
  13429. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13430. const char *body, size_t content_length,
  13431. const std::string &content_type,
  13432. DownloadProgress progress) {
  13433. return cli_->Delete(path, headers, body, content_length, content_type,
  13434. progress);
  13435. }
  13436. inline Result Client::Delete(const std::string &path, const std::string &body,
  13437. const std::string &content_type,
  13438. DownloadProgress progress) {
  13439. return cli_->Delete(path, body, content_type, progress);
  13440. }
  13441. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13442. const std::string &body,
  13443. const std::string &content_type,
  13444. DownloadProgress progress) {
  13445. return cli_->Delete(path, headers, body, content_type, progress);
  13446. }
  13447. inline Result Client::Delete(const std::string &path, const Params &params,
  13448. DownloadProgress progress) {
  13449. return cli_->Delete(path, params, progress);
  13450. }
  13451. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13452. const Params &params, DownloadProgress progress) {
  13453. return cli_->Delete(path, headers, params, progress);
  13454. }
  13455. inline Result Client::Options(const std::string &path) {
  13456. return cli_->Options(path);
  13457. }
  13458. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13459. return cli_->Options(path, headers);
  13460. }
  13461. inline ClientImpl::StreamHandle
  13462. Client::open_stream(const std::string &method, const std::string &path,
  13463. const Params &params, const Headers &headers,
  13464. const std::string &body, const std::string &content_type) {
  13465. return cli_->open_stream(method, path, params, headers, body, content_type);
  13466. }
  13467. inline bool Client::send(Request &req, Response &res, Error &error) {
  13468. return cli_->send(req, res, error);
  13469. }
  13470. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13471. inline void Client::stop() { cli_->stop(); }
  13472. inline std::string Client::host() const { return cli_->host(); }
  13473. inline int Client::port() const { return cli_->port(); }
  13474. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13475. inline socket_t Client::socket() const { return cli_->socket(); }
  13476. inline void
  13477. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13478. cli_->set_hostname_addr_map(std::move(addr_map));
  13479. }
  13480. inline void Client::set_default_headers(Headers headers) {
  13481. cli_->set_default_headers(std::move(headers));
  13482. }
  13483. inline void Client::set_header_writer(
  13484. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13485. cli_->set_header_writer(writer);
  13486. }
  13487. inline void Client::set_address_family(int family) {
  13488. cli_->set_address_family(family);
  13489. }
  13490. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13491. inline void Client::set_socket_options(SocketOptions socket_options) {
  13492. cli_->set_socket_options(std::move(socket_options));
  13493. }
  13494. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13495. cli_->set_connection_timeout(sec, usec);
  13496. }
  13497. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13498. cli_->set_read_timeout(sec, usec);
  13499. }
  13500. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13501. cli_->set_write_timeout(sec, usec);
  13502. }
  13503. inline void Client::set_basic_auth(const std::string &username,
  13504. const std::string &password) {
  13505. cli_->set_basic_auth(username, password);
  13506. }
  13507. inline void Client::set_bearer_token_auth(const std::string &token) {
  13508. cli_->set_bearer_token_auth(token);
  13509. }
  13510. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13511. inline void Client::set_follow_location(bool on) {
  13512. cli_->set_follow_location(on);
  13513. }
  13514. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13515. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13516. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13517. inline void Client::set_payload_max_length(size_t length) {
  13518. cli_->set_payload_max_length(length);
  13519. }
  13520. inline void Client::set_interface(const std::string &intf) {
  13521. cli_->set_interface(intf);
  13522. }
  13523. inline void Client::set_proxy(const std::string &host, int port) {
  13524. cli_->set_proxy(host, port);
  13525. }
  13526. inline void Client::set_proxy_basic_auth(const std::string &username,
  13527. const std::string &password) {
  13528. cli_->set_proxy_basic_auth(username, password);
  13529. }
  13530. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13531. cli_->set_proxy_bearer_token_auth(token);
  13532. }
  13533. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13534. cli_->set_no_proxy(patterns);
  13535. }
  13536. inline void Client::set_logger(Logger logger) {
  13537. cli_->set_logger(std::move(logger));
  13538. }
  13539. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13540. cli_->set_error_logger(std::move(error_logger));
  13541. }
  13542. /*
  13543. * Group 6: SSL Server and Client implementation
  13544. */
  13545. #ifdef CPPHTTPLIB_SSL_ENABLED
  13546. // SSL HTTP server implementation
  13547. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13548. const char *client_ca_cert_file_path,
  13549. const char *client_ca_cert_dir_path,
  13550. const char *private_key_password) {
  13551. using namespace tls;
  13552. ctx_ = create_server_context();
  13553. if (!ctx_) { return; }
  13554. // Load server certificate and private key
  13555. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13556. private_key_password)) {
  13557. last_ssl_error_ = static_cast<int>(get_error());
  13558. free_context(ctx_);
  13559. ctx_ = nullptr;
  13560. return;
  13561. }
  13562. // Load client CA certificates for client authentication
  13563. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13564. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13565. client_ca_cert_dir_path)) {
  13566. last_ssl_error_ = static_cast<int>(get_error());
  13567. free_context(ctx_);
  13568. ctx_ = nullptr;
  13569. return;
  13570. }
  13571. // Enable client certificate verification
  13572. set_verify_client(ctx_, true);
  13573. }
  13574. }
  13575. inline SSLServer::SSLServer(const PemMemory &pem) {
  13576. using namespace tls;
  13577. ctx_ = create_server_context();
  13578. if (ctx_) {
  13579. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13580. pem.private_key_password)) {
  13581. last_ssl_error_ = static_cast<int>(get_error());
  13582. free_context(ctx_);
  13583. ctx_ = nullptr;
  13584. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13585. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13586. last_ssl_error_ = static_cast<int>(get_error());
  13587. free_context(ctx_);
  13588. ctx_ = nullptr;
  13589. } else {
  13590. set_verify_client(ctx_, true);
  13591. }
  13592. }
  13593. }
  13594. }
  13595. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13596. using namespace tls;
  13597. ctx_ = create_server_context();
  13598. if (ctx_) {
  13599. if (!setup_callback(ctx_)) {
  13600. free_context(ctx_);
  13601. ctx_ = nullptr;
  13602. }
  13603. }
  13604. }
  13605. inline SSLServer::~SSLServer() {
  13606. if (ctx_) { tls::free_context(ctx_); }
  13607. }
  13608. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13609. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13610. using namespace tls;
  13611. // Create TLS session with mutex protection
  13612. session_t session = nullptr;
  13613. {
  13614. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13615. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13616. }
  13617. if (!session) {
  13618. last_ssl_error_ = static_cast<int>(get_error());
  13619. detail::shutdown_socket(sock);
  13620. detail::close_socket(sock);
  13621. return false;
  13622. }
  13623. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13624. bool handshake_done = false;
  13625. bool ret = false;
  13626. bool websocket_upgraded = false;
  13627. auto cleanup = detail::scope_exit([&] {
  13628. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13629. free_session(session);
  13630. detail::shutdown_socket(sock);
  13631. detail::close_socket(sock);
  13632. });
  13633. // Perform TLS accept handshake with timeout
  13634. TlsError tls_err;
  13635. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13636. &tls_err)) {
  13637. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13638. // Map TlsError to legacy ssl_error for backward compatibility
  13639. if (tls_err.code == ErrorCode::WantRead) {
  13640. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13641. } else if (tls_err.code == ErrorCode::WantWrite) {
  13642. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13643. } else {
  13644. last_ssl_error_ = SSL_ERROR_SSL;
  13645. }
  13646. #else
  13647. last_ssl_error_ = static_cast<int>(get_error());
  13648. #endif
  13649. return false;
  13650. }
  13651. handshake_done = true;
  13652. std::string remote_addr;
  13653. int remote_port = 0;
  13654. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13655. std::string local_addr;
  13656. int local_port = 0;
  13657. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13658. ret = detail::process_server_socket_ssl(
  13659. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13660. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13661. write_timeout_usec_,
  13662. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13663. return process_request(
  13664. strm, remote_addr, remote_port, local_addr, local_port,
  13665. close_connection, connection_closed,
  13666. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13667. });
  13668. return ret;
  13669. }
  13670. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13671. const char *key_pem,
  13672. const char *client_ca_pem,
  13673. const char *password) {
  13674. if (!ctx_) { return false; }
  13675. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13676. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13677. return false;
  13678. }
  13679. if (client_ca_pem) {
  13680. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13681. }
  13682. return true;
  13683. }
  13684. // SSL HTTP client implementation
  13685. inline SSLClient::~SSLClient() {
  13686. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13687. // base function rather than the derived function once we get to the
  13688. // base class destructor, and won't free the SSL (causing a leak).
  13689. // This must happen before the context is freed below: some backends
  13690. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  13691. // context, so freeing the context first leaves close_notify reading
  13692. // freed memory.
  13693. shutdown_ssl_impl(socket_, true);
  13694. if (ctx_) {
  13695. tls::free_context(ctx_);
  13696. ctx_ = nullptr;
  13697. }
  13698. }
  13699. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13700. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13701. shutdown_ssl_impl(socket, shutdown_gracefully);
  13702. }
  13703. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13704. bool shutdown_gracefully) {
  13705. if (socket.sock == INVALID_SOCKET) {
  13706. assert(socket.ssl == nullptr);
  13707. return;
  13708. }
  13709. if (socket.ssl) {
  13710. tls::shutdown(socket.ssl, shutdown_gracefully);
  13711. {
  13712. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13713. tls::free_session(socket.ssl);
  13714. }
  13715. socket.ssl = nullptr;
  13716. }
  13717. assert(socket.ssl == nullptr);
  13718. }
  13719. inline bool SSLClient::process_socket(
  13720. const Socket &socket,
  13721. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13722. std::function<bool(Stream &strm)> callback) {
  13723. assert(socket.ssl);
  13724. return detail::process_client_socket_ssl(
  13725. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13726. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13727. std::move(callback));
  13728. }
  13729. inline bool SSLClient::is_ssl() const { return true; }
  13730. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13731. if (!is_valid()) {
  13732. error = Error::SSLConnection;
  13733. return false;
  13734. }
  13735. return ClientImpl::create_and_connect_socket(socket, error);
  13736. }
  13737. inline bool SSLClient::setup_proxy_connection(
  13738. Socket &socket,
  13739. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13740. Response &res, bool &success, Error &error) {
  13741. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13742. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13743. return false;
  13744. }
  13745. if (!initialize_ssl(socket, error)) {
  13746. success = false;
  13747. return false;
  13748. }
  13749. return true;
  13750. }
  13751. // Assumes that socket_mutex_ is locked and that there are no requests in
  13752. // flight
  13753. inline bool SSLClient::connect_with_proxy(
  13754. Socket &socket,
  13755. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13756. Response &res, bool &success, Error &error) {
  13757. success = true;
  13758. Response proxy_res;
  13759. if (!detail::process_client_socket(
  13760. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13761. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13762. start_time, [&](Stream &strm) {
  13763. Request req2;
  13764. req2.method = "CONNECT";
  13765. req2.path =
  13766. detail::make_host_and_port_string_always_port(host_, port_);
  13767. if (max_timeout_msec_ > 0) {
  13768. req2.start_time_ = std::chrono::steady_clock::now();
  13769. }
  13770. return process_request(strm, req2, proxy_res, false, error);
  13771. })) {
  13772. // Thread-safe to close everything because we are assuming there are no
  13773. // requests in flight
  13774. shutdown_ssl(socket, true);
  13775. shutdown_socket(socket);
  13776. close_socket(socket);
  13777. success = false;
  13778. return false;
  13779. }
  13780. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13781. if (!proxy_digest_auth_username_.empty() &&
  13782. !proxy_digest_auth_password_.empty()) {
  13783. std::map<std::string, std::string> auth;
  13784. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13785. // Close the current socket and create a new one for the authenticated
  13786. // request
  13787. shutdown_ssl(socket, true);
  13788. shutdown_socket(socket);
  13789. close_socket(socket);
  13790. // Create a new socket for the authenticated CONNECT request
  13791. if (!ensure_socket_connection(socket, error)) {
  13792. success = false;
  13793. output_error_log(error, nullptr);
  13794. return false;
  13795. }
  13796. proxy_res = Response();
  13797. if (!detail::process_client_socket(
  13798. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13799. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13800. start_time, [&](Stream &strm) {
  13801. Request req3;
  13802. req3.method = "CONNECT";
  13803. req3.path = detail::make_host_and_port_string_always_port(
  13804. host_, port_);
  13805. req3.headers.insert(detail::make_digest_authentication_header(
  13806. req3, auth, 1, detail::random_string(10),
  13807. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13808. true));
  13809. if (max_timeout_msec_ > 0) {
  13810. req3.start_time_ = std::chrono::steady_clock::now();
  13811. }
  13812. return process_request(strm, req3, proxy_res, false, error);
  13813. })) {
  13814. // Thread-safe to close everything because we are assuming there are
  13815. // no requests in flight
  13816. shutdown_ssl(socket, true);
  13817. shutdown_socket(socket);
  13818. close_socket(socket);
  13819. success = false;
  13820. return false;
  13821. }
  13822. }
  13823. }
  13824. }
  13825. // If status code is not 200, proxy request is failed.
  13826. // Set error to ProxyConnection and return proxy response
  13827. // as the response of the request
  13828. if (proxy_res.status != StatusCode::OK_200) {
  13829. error = Error::ProxyConnection;
  13830. output_error_log(error, nullptr);
  13831. res = std::move(proxy_res);
  13832. // Thread-safe to close everything because we are assuming there are
  13833. // no requests in flight
  13834. shutdown_ssl(socket, true);
  13835. shutdown_socket(socket);
  13836. close_socket(socket);
  13837. return false;
  13838. }
  13839. return true;
  13840. }
  13841. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13842. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13843. if (is_proxy_enabled_for_host(host_)) { return true; }
  13844. if (!initialize_ssl(socket, error)) {
  13845. shutdown_socket(socket);
  13846. close_socket(socket);
  13847. return false;
  13848. }
  13849. return true;
  13850. }
  13851. // SSL HTTP client implementation
  13852. inline SSLClient::SSLClient(const std::string &host)
  13853. : SSLClient(host, 443, std::string(), std::string()) {}
  13854. inline SSLClient::SSLClient(const std::string &host, int port)
  13855. : SSLClient(host, port, std::string(), std::string()) {}
  13856. inline void SSLClient::init_ctx() {
  13857. ctx_ = tls::create_client_context();
  13858. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13859. }
  13860. inline void SSLClient::reset_ctx_on_error() {
  13861. last_backend_error_ = tls::get_error();
  13862. tls::free_context(ctx_);
  13863. ctx_ = nullptr;
  13864. }
  13865. inline SSLClient::SSLClient(const std::string &host, int port,
  13866. const std::string &client_cert_path,
  13867. const std::string &client_key_path,
  13868. const std::string &private_key_password)
  13869. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13870. init_ctx();
  13871. if (!ctx_) { return; }
  13872. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13873. const char *password =
  13874. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13875. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13876. client_key_path.c_str(), password)) {
  13877. reset_ctx_on_error();
  13878. }
  13879. }
  13880. }
  13881. inline SSLClient::SSLClient(const std::string &host, int port,
  13882. const PemMemory &pem)
  13883. : ClientImpl(host, port) {
  13884. init_ctx();
  13885. if (!ctx_) { return; }
  13886. if (pem.cert_pem && pem.key_pem) {
  13887. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13888. pem.private_key_password)) {
  13889. reset_ctx_on_error();
  13890. }
  13891. }
  13892. }
  13893. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13894. if (ca_cert_store && ctx_) {
  13895. // set_ca_store takes ownership of ca_cert_store
  13896. tls::set_ca_store(ctx_, ca_cert_store);
  13897. ca_cert_store_set_ = true;
  13898. } else if (ca_cert_store) {
  13899. tls::free_ca_store(ca_cert_store);
  13900. }
  13901. }
  13902. inline void
  13903. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13904. if (!ctx_) { return; }
  13905. tls::set_verify_callback(ctx_, verifier);
  13906. }
  13907. inline void SSLClient::set_session_verifier(
  13908. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13909. session_verifier_ = std::move(verifier);
  13910. }
  13911. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13912. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13913. enable_windows_cert_verification_ = enabled;
  13914. }
  13915. #endif
  13916. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13917. std::size_t size) {
  13918. if (ctx_ && ca_cert && size > 0) {
  13919. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13920. tls::load_ca_pem(ctx_, ca_cert, size);
  13921. }
  13922. }
  13923. inline bool SSLClient::load_certs() {
  13924. auto ret = true;
  13925. std::call_once(initialize_cert_, [&]() {
  13926. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13927. ret = detail::load_client_ca_config(
  13928. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13929. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13930. last_backend_error_);
  13931. });
  13932. return ret;
  13933. }
  13934. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13935. using namespace tls;
  13936. // Load CA certificates if server verification is enabled
  13937. if (server_certificate_verification_) {
  13938. if (!load_certs()) {
  13939. error = Error::SSLLoadingCerts;
  13940. output_error_log(error, nullptr);
  13941. return false;
  13942. }
  13943. }
  13944. bool is_ip = detail::is_ip_address(host_);
  13945. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13946. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13947. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13948. // Chain verification happens during the handshake even for IP hosts; the
  13949. // certificate identity is verified post-handshake via verify_hostname().
  13950. set_verify_client(ctx_, server_certificate_verification_);
  13951. #endif
  13952. // Create TLS session
  13953. session_t session = nullptr;
  13954. {
  13955. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13956. session = create_session(ctx_, socket.sock);
  13957. }
  13958. if (!session) {
  13959. error = Error::SSLConnection;
  13960. last_backend_error_ = get_error();
  13961. return false;
  13962. }
  13963. // Use scope_exit to ensure session is freed on error paths
  13964. bool success = false;
  13965. auto session_guard = detail::scope_exit([&] {
  13966. if (!success) { free_session(session); }
  13967. });
  13968. // Set SNI extension (skip for IP addresses per RFC 6066).
  13969. // On MbedTLS, set_sni also enables hostname verification internally.
  13970. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13971. if (!is_ip) {
  13972. if (!set_sni(session, host_.c_str())) {
  13973. error = Error::SSLConnection;
  13974. last_backend_error_ = get_error();
  13975. return false;
  13976. }
  13977. }
  13978. // Perform non-blocking TLS handshake with timeout
  13979. TlsError tls_err;
  13980. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13981. connection_timeout_usec_, &tls_err)) {
  13982. last_ssl_error_ = static_cast<int>(tls_err.code);
  13983. last_backend_error_ = tls_err.backend_code;
  13984. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13985. error = Error::SSLServerVerification;
  13986. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13987. error = Error::SSLServerHostnameVerification;
  13988. } else {
  13989. error = Error::SSLConnection;
  13990. }
  13991. output_error_log(error, nullptr);
  13992. return false;
  13993. }
  13994. // Post-handshake session verifier callback
  13995. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13996. if (session_verifier_) { verification_status = session_verifier_(session); }
  13997. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13998. last_backend_error_ = get_error();
  13999. error = Error::SSLServerVerification;
  14000. output_error_log(error, nullptr);
  14001. return false;
  14002. }
  14003. // Default server certificate verification
  14004. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  14005. server_certificate_verification_) {
  14006. verify_result_ = tls::get_verify_result(session);
  14007. if (verify_result_ != 0) {
  14008. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  14009. error = Error::SSLServerVerification;
  14010. output_error_log(error, nullptr);
  14011. return false;
  14012. }
  14013. auto server_cert = get_peer_cert(session);
  14014. if (!server_cert) {
  14015. last_backend_error_ = get_error();
  14016. error = Error::SSLServerVerification;
  14017. output_error_log(error, nullptr);
  14018. return false;
  14019. }
  14020. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  14021. // Hostname verification (post-handshake for all cases).
  14022. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  14023. // On MbedTLS, set_sni already enabled hostname verification during
  14024. // handshake for non-IP hosts, but this check is still needed for IP
  14025. // addresses where SNI is not set.
  14026. if (server_hostname_verification_) {
  14027. if (!verify_hostname(server_cert, host_.c_str())) {
  14028. last_backend_error_ = hostname_mismatch_code();
  14029. error = Error::SSLServerHostnameVerification;
  14030. output_error_log(error, nullptr);
  14031. return false;
  14032. }
  14033. }
  14034. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14035. // Additional Windows Schannel verification.
  14036. // This provides real-time certificate validation with Windows Update
  14037. // integration, working with both OpenSSL and MbedTLS backends.
  14038. // Skip when a custom CA cert is specified, as the Windows certificate
  14039. // store would not know about user-provided CA certificates. Also skip
  14040. // when system CA trust is explicitly disabled.
  14041. if (enable_windows_cert_verification_ &&
  14042. system_ca_mode_ != SystemCAMode::Disabled &&
  14043. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  14044. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14045. std::vector<unsigned char> der;
  14046. if (get_cert_der(server_cert, der)) {
  14047. uint64_t wincrypt_error = 0;
  14048. if (!detail::verify_cert_with_windows_schannel(
  14049. der, host_, server_hostname_verification_, wincrypt_error)) {
  14050. last_backend_error_ = wincrypt_error;
  14051. error = Error::SSLServerVerification;
  14052. output_error_log(error, nullptr);
  14053. return false;
  14054. }
  14055. }
  14056. }
  14057. #endif
  14058. }
  14059. success = true;
  14060. socket.ssl = session;
  14061. return true;
  14062. }
  14063. inline void Client::set_digest_auth(const std::string &username,
  14064. const std::string &password) {
  14065. cli_->set_digest_auth(username, password);
  14066. }
  14067. inline void Client::set_proxy_digest_auth(const std::string &username,
  14068. const std::string &password) {
  14069. cli_->set_proxy_digest_auth(username, password);
  14070. }
  14071. inline void Client::enable_server_certificate_verification(bool enabled) {
  14072. cli_->enable_server_certificate_verification(enabled);
  14073. }
  14074. inline void Client::enable_server_hostname_verification(bool enabled) {
  14075. cli_->enable_server_hostname_verification(enabled);
  14076. }
  14077. inline void Client::enable_system_ca(bool enabled) {
  14078. cli_->enable_system_ca(enabled);
  14079. }
  14080. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14081. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14082. if (is_ssl_) {
  14083. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14084. enabled);
  14085. }
  14086. }
  14087. #endif
  14088. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14089. const std::string &ca_cert_dir_path) {
  14090. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14091. }
  14092. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14093. if (is_ssl_) {
  14094. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14095. } else if (ca_cert_store) {
  14096. tls::free_ca_store(ca_cert_store);
  14097. }
  14098. }
  14099. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14100. if (is_ssl_) {
  14101. // Use the PEM-based path so the CA data is retained for redirect transfer
  14102. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14103. }
  14104. }
  14105. inline void
  14106. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14107. if (is_ssl_) {
  14108. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14109. std::move(verifier));
  14110. }
  14111. }
  14112. inline void Client::set_session_verifier(
  14113. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14114. if (is_ssl_) {
  14115. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14116. }
  14117. }
  14118. inline tls::ctx_t Client::tls_context() const {
  14119. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14120. return nullptr;
  14121. }
  14122. #endif // CPPHTTPLIB_SSL_ENABLED
  14123. /*
  14124. * Group 7: TLS abstraction layer - Common API
  14125. */
  14126. #ifdef CPPHTTPLIB_SSL_ENABLED
  14127. namespace tls {
  14128. // Helper for PeerCert construction
  14129. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14130. return PeerCert(get_peer_cert(session));
  14131. }
  14132. namespace impl {
  14133. inline VerifyCallback &get_verify_callback() {
  14134. static thread_local VerifyCallback callback;
  14135. return callback;
  14136. }
  14137. inline VerifyCallback &get_mbedtls_verify_callback() {
  14138. static thread_local VerifyCallback callback;
  14139. return callback;
  14140. }
  14141. // Check if a string is an IPv4 address
  14142. inline bool is_ipv4_address(const std::string &str) {
  14143. int dots = 0;
  14144. for (char c : str) {
  14145. if (c == '.') {
  14146. dots++;
  14147. } else if (!detail::is_ascii_digit(c)) {
  14148. return false;
  14149. }
  14150. }
  14151. return dots == 3;
  14152. }
  14153. // Parse IPv4 address string to bytes
  14154. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14155. const char *p = str.c_str();
  14156. for (int i = 0; i < 4; i++) {
  14157. if (i > 0) {
  14158. if (*p != '.') { return false; }
  14159. p++;
  14160. }
  14161. int val = 0;
  14162. int digits = 0;
  14163. while (detail::is_ascii_digit(*p)) {
  14164. val = val * 10 + (*p - '0');
  14165. if (val > 255) { return false; }
  14166. p++;
  14167. digits++;
  14168. }
  14169. if (digits == 0) { return false; }
  14170. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14171. if (digits > 1 && *(p - digits) == '0') { return false; }
  14172. out[i] = static_cast<unsigned char>(val);
  14173. }
  14174. return *p == '\0';
  14175. }
  14176. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14177. // `out` must have room for at least 16 bytes. Returns the address length
  14178. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14179. // literal. Used to match a host against iPAddress SANs the same way the
  14180. // OpenSSL backend does via X509_check_ip.
  14181. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14182. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14183. struct in6_addr addr6 = {};
  14184. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14185. memcpy(out, &addr6, 16);
  14186. return 16;
  14187. }
  14188. return 0;
  14189. }
  14190. #ifdef _WIN32
  14191. // Enumerate Windows system certificates and call callback with DER data
  14192. template <typename Callback>
  14193. inline bool enumerate_windows_system_certs(Callback cb) {
  14194. bool loaded = false;
  14195. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14196. for (auto store_name : store_names) {
  14197. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14198. if (hStore) {
  14199. PCCERT_CONTEXT pContext = nullptr;
  14200. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14201. nullptr) {
  14202. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14203. loaded = true;
  14204. }
  14205. }
  14206. CertCloseStore(hStore, 0);
  14207. }
  14208. }
  14209. return loaded;
  14210. }
  14211. #endif
  14212. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14213. // Enumerate macOS Keychain certificates and call callback with DER data
  14214. template <typename Callback>
  14215. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14216. bool loaded = false;
  14217. const SecTrustSettingsDomain domains[] = {
  14218. kSecTrustSettingsDomainSystem,
  14219. kSecTrustSettingsDomainAdmin,
  14220. kSecTrustSettingsDomainUser,
  14221. };
  14222. for (auto domain : domains) {
  14223. CFArrayRef certs = nullptr;
  14224. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14225. if (status != errSecSuccess || !certs) {
  14226. if (certs) CFRelease(certs);
  14227. continue;
  14228. }
  14229. CFIndex count = CFArrayGetCount(certs);
  14230. for (CFIndex i = 0; i < count; i++) {
  14231. SecCertificateRef cert =
  14232. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14233. CFDataRef data = SecCertificateCopyData(cert);
  14234. if (data) {
  14235. if (cb(CFDataGetBytePtr(data),
  14236. static_cast<size_t>(CFDataGetLength(data)))) {
  14237. loaded = true;
  14238. }
  14239. CFRelease(data);
  14240. }
  14241. }
  14242. CFRelease(certs);
  14243. }
  14244. return loaded;
  14245. }
  14246. #endif
  14247. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14248. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14249. // Common CA certificate file paths on Linux/Unix
  14250. inline const char **system_ca_paths() {
  14251. static const char *paths[] = {
  14252. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14253. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14254. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14255. "/etc/pki/tls/cacert.pem", // OpenELEC
  14256. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14257. nullptr};
  14258. return paths;
  14259. }
  14260. // Common CA certificate directory paths on Linux/Unix
  14261. inline const char **system_ca_dirs() {
  14262. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14263. "/etc/pki/tls/certs", // RHEL/CentOS
  14264. "/usr/share/ca-certificates", // Other
  14265. nullptr};
  14266. return dirs;
  14267. }
  14268. #endif
  14269. } // namespace impl
  14270. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14271. const char *ca_dir) {
  14272. if (!ctx) { return false; }
  14273. bool success = true;
  14274. if (ca_file && *ca_file) {
  14275. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14276. }
  14277. if (ca_dir && *ca_dir) {
  14278. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14279. }
  14280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14281. // Set CA list for client certificate request (CertificateRequest message)
  14282. if (ca_file && *ca_file) {
  14283. auto list = SSL_load_client_CA_file(ca_file);
  14284. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14285. }
  14286. #endif
  14287. return success;
  14288. }
  14289. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14290. const char *password) {
  14291. return set_client_cert_pem(ctx, cert, key, password);
  14292. }
  14293. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14294. const char *key_path, const char *password) {
  14295. return set_client_cert_file(ctx, cert_path, key_path, password);
  14296. }
  14297. // PeerCert implementation
  14298. inline PeerCert::PeerCert() = default;
  14299. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14300. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14301. other.cert_ = nullptr;
  14302. }
  14303. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14304. if (this != &other) {
  14305. if (cert_) { free_cert(cert_); }
  14306. cert_ = other.cert_;
  14307. other.cert_ = nullptr;
  14308. }
  14309. return *this;
  14310. }
  14311. inline PeerCert::~PeerCert() {
  14312. if (cert_) { free_cert(cert_); }
  14313. }
  14314. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14315. inline std::string PeerCert::subject_cn() const {
  14316. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14317. }
  14318. inline std::string PeerCert::issuer_name() const {
  14319. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14320. }
  14321. inline bool PeerCert::check_hostname(const char *hostname) const {
  14322. return cert_ ? verify_hostname(cert_, hostname) : false;
  14323. }
  14324. inline std::vector<SanEntry> PeerCert::sans() const {
  14325. std::vector<SanEntry> result;
  14326. if (cert_) { get_cert_sans(cert_, result); }
  14327. return result;
  14328. }
  14329. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14330. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14331. }
  14332. inline std::string PeerCert::serial() const {
  14333. return cert_ ? get_cert_serial(cert_) : std::string();
  14334. }
  14335. // VerifyContext method implementations
  14336. inline std::string VerifyContext::subject_cn() const {
  14337. return cert ? get_cert_subject_cn(cert) : std::string();
  14338. }
  14339. inline std::string VerifyContext::issuer_name() const {
  14340. return cert ? get_cert_issuer_name(cert) : std::string();
  14341. }
  14342. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14343. return cert ? verify_hostname(cert, hostname) : false;
  14344. }
  14345. inline std::vector<SanEntry> VerifyContext::sans() const {
  14346. std::vector<SanEntry> result;
  14347. if (cert) { get_cert_sans(cert, result); }
  14348. return result;
  14349. }
  14350. inline bool VerifyContext::validity(time_t &not_before,
  14351. time_t &not_after) const {
  14352. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14353. }
  14354. inline std::string VerifyContext::serial() const {
  14355. return cert ? get_cert_serial(cert) : std::string();
  14356. }
  14357. // TlsError static method implementation
  14358. inline std::string TlsError::verify_error_to_string(long error_code) {
  14359. return verify_error_string(error_code);
  14360. }
  14361. } // namespace tls
  14362. // Request::peer_cert() implementation
  14363. inline tls::PeerCert Request::peer_cert() const {
  14364. return tls::get_peer_cert_from_session(ssl);
  14365. }
  14366. // Request::sni() implementation
  14367. inline std::string Request::sni() const {
  14368. if (!ssl) { return std::string(); }
  14369. const char *s = tls::get_sni(ssl);
  14370. return s ? std::string(s) : std::string();
  14371. }
  14372. #endif // CPPHTTPLIB_SSL_ENABLED
  14373. /*
  14374. * Group 8: TLS abstraction layer - OpenSSL backend
  14375. */
  14376. /*
  14377. * OpenSSL Backend Implementation
  14378. */
  14379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14380. namespace tls {
  14381. namespace impl {
  14382. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14383. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14384. switch (ssl_error) {
  14385. case SSL_ERROR_NONE: return ErrorCode::Success;
  14386. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14387. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14388. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14389. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14390. case SSL_ERROR_SSL:
  14391. default: return ErrorCode::Fatal;
  14392. }
  14393. }
  14394. // Helper: Create client CA list from PEM string
  14395. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14396. // Caller takes ownership of returned list
  14397. inline STACK_OF(X509_NAME) *
  14398. create_client_ca_list_from_pem(const char *ca_pem) {
  14399. if (!ca_pem) { return nullptr; }
  14400. auto ca_list = sk_X509_NAME_new_null();
  14401. if (!ca_list) { return nullptr; }
  14402. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14403. if (!bio) {
  14404. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14405. return nullptr;
  14406. }
  14407. X509 *cert = nullptr;
  14408. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14409. nullptr) {
  14410. const X509_NAME *name = X509_get_subject_name(cert);
  14411. if (name) {
  14412. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14413. }
  14414. X509_free(cert);
  14415. }
  14416. BIO_free(bio);
  14417. return ca_list;
  14418. }
  14419. // OpenSSL verify callback wrapper
  14420. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14421. auto &callback = get_verify_callback();
  14422. if (!callback) { return preverify_ok; }
  14423. // Get SSL object from X509_STORE_CTX
  14424. auto ssl = static_cast<SSL *>(
  14425. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14426. if (!ssl) { return preverify_ok; }
  14427. // Get current certificate and depth
  14428. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14429. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14430. int error = X509_STORE_CTX_get_error(ctx);
  14431. // Build context
  14432. VerifyContext verify_ctx;
  14433. verify_ctx.session = static_cast<session_t>(ssl);
  14434. verify_ctx.cert = static_cast<cert_t>(cert);
  14435. verify_ctx.depth = depth;
  14436. verify_ctx.preverify_ok = (preverify_ok != 0);
  14437. verify_ctx.error_code = error;
  14438. verify_ctx.error_string =
  14439. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14440. return callback(verify_ctx) ? 1 : 0;
  14441. }
  14442. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14443. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14444. // that must be released with release_store_objects
  14445. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14446. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14447. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14448. #endif
  14449. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14450. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14451. return X509_STORE_get1_objects(store);
  14452. #else
  14453. return X509_STORE_get0_objects(store);
  14454. #endif
  14455. }
  14456. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14457. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14458. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14459. #else
  14460. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14461. #endif
  14462. }
  14463. } // namespace impl
  14464. inline ctx_t create_client_context() {
  14465. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14466. if (ctx) {
  14467. // Disable auto-retry to properly handle non-blocking I/O
  14468. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14469. // Set minimum TLS version
  14470. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14471. }
  14472. return static_cast<ctx_t>(ctx);
  14473. }
  14474. inline void free_context(ctx_t ctx) {
  14475. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14476. }
  14477. inline bool set_min_version(ctx_t ctx, Version version) {
  14478. if (!ctx) return false;
  14479. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14480. static_cast<int>(version)) == 1;
  14481. }
  14482. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14483. if (!ctx || !pem || len == 0) return false;
  14484. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14485. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14486. if (!store) return false;
  14487. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14488. if (!bio) return false;
  14489. bool ok = true;
  14490. X509 *cert = nullptr;
  14491. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14492. nullptr) {
  14493. if (X509_STORE_add_cert(store, cert) != 1) {
  14494. // Ignore duplicate errors
  14495. auto err = ERR_peek_last_error();
  14496. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14497. ok = false;
  14498. }
  14499. }
  14500. X509_free(cert);
  14501. if (!ok) break;
  14502. }
  14503. BIO_free(bio);
  14504. // Clear any "no more certificates" errors
  14505. ERR_clear_error();
  14506. return ok;
  14507. }
  14508. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14509. if (!ctx || !file_path) return false;
  14510. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14511. nullptr) == 1;
  14512. }
  14513. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14514. if (!ctx || !dir_path) return false;
  14515. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14516. dir_path) == 1;
  14517. }
  14518. inline bool load_system_certs(ctx_t ctx) {
  14519. if (!ctx) return false;
  14520. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14521. #ifdef _WIN32
  14522. // Windows: Load from system certificate store (ROOT and CA)
  14523. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14524. if (!store) return false;
  14525. bool loaded_any = false;
  14526. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14527. for (auto store_name : store_names) {
  14528. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14529. if (!hStore) continue;
  14530. PCCERT_CONTEXT pContext = nullptr;
  14531. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14532. nullptr) {
  14533. const unsigned char *data = pContext->pbCertEncoded;
  14534. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14535. if (x509) {
  14536. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14537. X509_free(x509);
  14538. }
  14539. }
  14540. CertCloseStore(hStore, 0);
  14541. }
  14542. return loaded_any;
  14543. #elif defined(__APPLE__)
  14544. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14545. // macOS: Load from Keychain
  14546. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14547. if (!store) return false;
  14548. bool loaded_any = false;
  14549. const SecTrustSettingsDomain domains[] = {
  14550. kSecTrustSettingsDomainSystem,
  14551. kSecTrustSettingsDomainAdmin,
  14552. kSecTrustSettingsDomainUser,
  14553. };
  14554. for (auto domain : domains) {
  14555. CFArrayRef certs = nullptr;
  14556. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14557. !certs) {
  14558. if (certs) CFRelease(certs);
  14559. continue;
  14560. }
  14561. auto count = CFArrayGetCount(certs);
  14562. for (CFIndex i = 0; i < count; i++) {
  14563. auto cert = reinterpret_cast<SecCertificateRef>(
  14564. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14565. CFDataRef der = SecCertificateCopyData(cert);
  14566. if (der) {
  14567. const unsigned char *data = CFDataGetBytePtr(der);
  14568. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14569. if (x509) {
  14570. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14571. X509_free(x509);
  14572. }
  14573. CFRelease(der);
  14574. }
  14575. }
  14576. CFRelease(certs);
  14577. }
  14578. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14579. #else
  14580. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14581. #endif
  14582. #else
  14583. // Other Unix: use default verify paths
  14584. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14585. #endif
  14586. }
  14587. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14588. const char *password) {
  14589. if (!ctx || !cert || !key) return false;
  14590. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14591. // Load certificate
  14592. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14593. if (!cert_bio) return false;
  14594. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14595. BIO_free(cert_bio);
  14596. if (!x509) return false;
  14597. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14598. X509_free(x509);
  14599. if (!cert_ok) return false;
  14600. // Load private key
  14601. auto key_bio = BIO_new_mem_buf(key, -1);
  14602. if (!key_bio) return false;
  14603. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14604. password ? const_cast<char *>(password)
  14605. : nullptr);
  14606. BIO_free(key_bio);
  14607. if (!pkey) return false;
  14608. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14609. EVP_PKEY_free(pkey);
  14610. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14611. }
  14612. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14613. const char *key_path, const char *password) {
  14614. if (!ctx || !cert_path || !key_path) return false;
  14615. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14616. if (password && password[0] != '\0') {
  14617. SSL_CTX_set_default_passwd_cb_userdata(
  14618. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14619. }
  14620. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14621. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14622. }
  14623. inline ctx_t create_server_context() {
  14624. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14625. if (ctx) {
  14626. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14627. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14628. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14629. }
  14630. return static_cast<ctx_t>(ctx);
  14631. }
  14632. inline void set_verify_client(ctx_t ctx, bool require) {
  14633. if (!ctx) return;
  14634. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14635. require
  14636. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14637. : SSL_VERIFY_NONE,
  14638. nullptr);
  14639. }
  14640. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14641. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14642. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14643. SSL *ssl = SSL_new(ssl_ctx);
  14644. if (!ssl) return nullptr;
  14645. // Disable auto-retry for proper non-blocking I/O handling
  14646. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14647. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14648. if (!bio) {
  14649. SSL_free(ssl);
  14650. return nullptr;
  14651. }
  14652. SSL_set_bio(ssl, bio, bio);
  14653. return static_cast<session_t>(ssl);
  14654. }
  14655. inline void free_session(session_t session) {
  14656. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14657. }
  14658. inline bool set_sni(session_t session, const char *hostname) {
  14659. if (!session || !hostname) return false;
  14660. auto ssl = static_cast<SSL *>(session);
  14661. // Set SNI (Server Name Indication) only - does not enable verification
  14662. #if defined(OPENSSL_IS_BORINGSSL)
  14663. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14664. #else
  14665. // Direct call instead of macro to suppress -Wold-style-cast warning
  14666. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14667. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14668. #endif
  14669. }
  14670. inline bool set_hostname(session_t session, const char *hostname) {
  14671. if (!session || !hostname) return false;
  14672. auto ssl = static_cast<SSL *>(session);
  14673. // Enable hostname verification
  14674. auto param = SSL_get0_param(ssl);
  14675. if (!param) return false;
  14676. if (detail::is_ip_address(hostname)) {
  14677. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14678. // certificate's IP SANs instead of its DNS names
  14679. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14680. } else {
  14681. // Set SNI (Server Name Indication)
  14682. if (!set_sni(session, hostname)) { return false; }
  14683. X509_VERIFY_PARAM_set_hostflags(param,
  14684. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14685. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14686. }
  14687. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14688. return true;
  14689. }
  14690. inline TlsError connect(session_t session) {
  14691. if (!session) { return TlsError(); }
  14692. auto ssl = static_cast<SSL *>(session);
  14693. auto ret = SSL_connect(ssl);
  14694. TlsError err;
  14695. if (ret == 1) {
  14696. err.code = ErrorCode::Success;
  14697. } else {
  14698. auto ssl_err = SSL_get_error(ssl, ret);
  14699. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14700. err.backend_code = ERR_get_error();
  14701. }
  14702. return err;
  14703. }
  14704. inline TlsError accept(session_t session) {
  14705. if (!session) { return TlsError(); }
  14706. auto ssl = static_cast<SSL *>(session);
  14707. auto ret = SSL_accept(ssl);
  14708. TlsError err;
  14709. if (ret == 1) {
  14710. err.code = ErrorCode::Success;
  14711. } else {
  14712. auto ssl_err = SSL_get_error(ssl, ret);
  14713. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14714. err.backend_code = ERR_get_error();
  14715. }
  14716. return err;
  14717. }
  14718. inline bool connect_nonblocking(session_t session, socket_t sock,
  14719. time_t timeout_sec, time_t timeout_usec,
  14720. TlsError *err) {
  14721. if (!session) {
  14722. if (err) { err->code = ErrorCode::Fatal; }
  14723. return false;
  14724. }
  14725. auto ssl = static_cast<SSL *>(session);
  14726. auto bio = SSL_get_rbio(ssl);
  14727. // Set non-blocking mode for handshake
  14728. detail::set_nonblocking(sock, true);
  14729. if (bio) { BIO_set_nbio(bio, 1); }
  14730. auto cleanup = detail::scope_exit([&]() {
  14731. // Restore blocking mode after handshake
  14732. if (bio) { BIO_set_nbio(bio, 0); }
  14733. detail::set_nonblocking(sock, false);
  14734. });
  14735. auto res = 0;
  14736. while ((res = SSL_connect(ssl)) != 1) {
  14737. auto ssl_err = SSL_get_error(ssl, res);
  14738. switch (ssl_err) {
  14739. case SSL_ERROR_WANT_READ:
  14740. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14741. continue;
  14742. }
  14743. break;
  14744. case SSL_ERROR_WANT_WRITE:
  14745. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14746. continue;
  14747. }
  14748. break;
  14749. default: break;
  14750. }
  14751. if (err) {
  14752. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14753. err->backend_code = ERR_get_error();
  14754. }
  14755. return false;
  14756. }
  14757. if (err) { err->code = ErrorCode::Success; }
  14758. return true;
  14759. }
  14760. inline bool accept_nonblocking(session_t session, socket_t sock,
  14761. time_t timeout_sec, time_t timeout_usec,
  14762. TlsError *err) {
  14763. if (!session) {
  14764. if (err) { err->code = ErrorCode::Fatal; }
  14765. return false;
  14766. }
  14767. auto ssl = static_cast<SSL *>(session);
  14768. auto bio = SSL_get_rbio(ssl);
  14769. // Set non-blocking mode for handshake
  14770. detail::set_nonblocking(sock, true);
  14771. if (bio) { BIO_set_nbio(bio, 1); }
  14772. auto cleanup = detail::scope_exit([&]() {
  14773. // Restore blocking mode after handshake
  14774. if (bio) { BIO_set_nbio(bio, 0); }
  14775. detail::set_nonblocking(sock, false);
  14776. });
  14777. auto res = 0;
  14778. while ((res = SSL_accept(ssl)) != 1) {
  14779. auto ssl_err = SSL_get_error(ssl, res);
  14780. switch (ssl_err) {
  14781. case SSL_ERROR_WANT_READ:
  14782. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14783. continue;
  14784. }
  14785. break;
  14786. case SSL_ERROR_WANT_WRITE:
  14787. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14788. continue;
  14789. }
  14790. break;
  14791. default: break;
  14792. }
  14793. if (err) {
  14794. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14795. err->backend_code = ERR_get_error();
  14796. }
  14797. return false;
  14798. }
  14799. if (err) { err->code = ErrorCode::Success; }
  14800. return true;
  14801. }
  14802. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14803. if (!session || !buf) {
  14804. err.code = ErrorCode::Fatal;
  14805. return -1;
  14806. }
  14807. auto ssl = static_cast<SSL *>(session);
  14808. constexpr auto max_len =
  14809. static_cast<size_t>((std::numeric_limits<int>::max)());
  14810. if (len > max_len) { len = max_len; }
  14811. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14812. if (ret > 0) {
  14813. err.code = ErrorCode::Success;
  14814. return ret;
  14815. }
  14816. auto ssl_err = SSL_get_error(ssl, ret);
  14817. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14818. if (err.code == ErrorCode::PeerClosed) {
  14819. return 0;
  14820. } // Gracefully handle the peer closed state.
  14821. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14822. return -1;
  14823. }
  14824. inline ssize_t write(session_t session, const void *buf, size_t len,
  14825. TlsError &err) {
  14826. if (!session || !buf) {
  14827. err.code = ErrorCode::Fatal;
  14828. return -1;
  14829. }
  14830. auto ssl = static_cast<SSL *>(session);
  14831. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14832. if (ret > 0) {
  14833. err.code = ErrorCode::Success;
  14834. return ret;
  14835. }
  14836. auto ssl_err = SSL_get_error(ssl, ret);
  14837. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14838. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14839. return -1;
  14840. }
  14841. inline int pending(const_session_t session) {
  14842. if (!session) return 0;
  14843. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14844. }
  14845. inline void shutdown(session_t session, bool graceful) {
  14846. if (!session) return;
  14847. auto ssl = static_cast<SSL *>(session);
  14848. if (graceful) {
  14849. // First call sends close_notify
  14850. if (SSL_shutdown(ssl) == 0) {
  14851. // Second call waits for peer's close_notify
  14852. SSL_shutdown(ssl);
  14853. }
  14854. }
  14855. }
  14856. inline bool is_peer_closed(session_t session, socket_t sock) {
  14857. if (!session) return true;
  14858. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14859. detail::set_nonblocking(sock, true);
  14860. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14861. auto ssl = static_cast<SSL *>(session);
  14862. char buf;
  14863. auto ret = SSL_peek(ssl, &buf, 1);
  14864. if (ret > 0) return false;
  14865. auto err = SSL_get_error(ssl, ret);
  14866. return err == SSL_ERROR_ZERO_RETURN;
  14867. }
  14868. inline cert_t get_peer_cert(const_session_t session) {
  14869. if (!session) return nullptr;
  14870. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14871. static_cast<SSL *>(const_cast<void *>(session))));
  14872. }
  14873. inline void free_cert(cert_t cert) {
  14874. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14875. }
  14876. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14877. if (!cert || !hostname) return false;
  14878. auto x509 = static_cast<X509 *>(cert);
  14879. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14880. if (detail::is_ip_address(hostname)) {
  14881. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14882. }
  14883. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14884. }
  14885. inline uint64_t hostname_mismatch_code() {
  14886. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14887. }
  14888. inline long get_verify_result(const_session_t session) {
  14889. if (!session) return X509_V_ERR_UNSPECIFIED;
  14890. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14891. }
  14892. inline std::string get_cert_subject_cn(cert_t cert) {
  14893. if (!cert) return "";
  14894. auto x509 = static_cast<X509 *>(cert);
  14895. auto subject_name = X509_get_subject_name(x509);
  14896. if (!subject_name) return "";
  14897. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14898. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14899. if (idx < 0) return "";
  14900. auto entry = X509_NAME_get_entry(subject_name, idx);
  14901. if (!entry) return "";
  14902. auto data = X509_NAME_ENTRY_get_data(entry);
  14903. if (!data) return "";
  14904. return std::string(
  14905. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14906. static_cast<size_t>(ASN1_STRING_length(data)));
  14907. }
  14908. inline std::string get_cert_issuer_name(cert_t cert) {
  14909. if (!cert) return "";
  14910. auto x509 = static_cast<X509 *>(cert);
  14911. auto issuer_name = X509_get_issuer_name(x509);
  14912. if (!issuer_name) return "";
  14913. char buf[256];
  14914. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14915. return std::string(buf);
  14916. }
  14917. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14918. sans.clear();
  14919. if (!cert) return false;
  14920. auto x509 = static_cast<X509 *>(cert);
  14921. auto names = static_cast<GENERAL_NAMES *>(
  14922. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14923. if (!names) return true; // No SANs is valid
  14924. auto count = sk_GENERAL_NAME_num(names);
  14925. for (decltype(count) i = 0; i < count; i++) {
  14926. auto gen = sk_GENERAL_NAME_value(names, i);
  14927. if (!gen) continue;
  14928. SanEntry entry;
  14929. switch (gen->type) {
  14930. case GEN_DNS:
  14931. entry.type = SanType::DNS;
  14932. if (gen->d.dNSName) {
  14933. entry.value = std::string(
  14934. reinterpret_cast<const char *>(
  14935. ASN1_STRING_get0_data(gen->d.dNSName)),
  14936. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14937. }
  14938. break;
  14939. case GEN_IPADD:
  14940. entry.type = SanType::IP;
  14941. if (gen->d.iPAddress) {
  14942. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14943. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14944. if (len == 4) {
  14945. // IPv4
  14946. char buf[INET_ADDRSTRLEN];
  14947. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14948. entry.value = buf;
  14949. } else if (len == 16) {
  14950. // IPv6
  14951. char buf[INET6_ADDRSTRLEN];
  14952. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14953. entry.value = buf;
  14954. }
  14955. }
  14956. break;
  14957. case GEN_EMAIL:
  14958. entry.type = SanType::EMAIL;
  14959. if (gen->d.rfc822Name) {
  14960. entry.value = std::string(
  14961. reinterpret_cast<const char *>(
  14962. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14963. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14964. }
  14965. break;
  14966. case GEN_URI:
  14967. entry.type = SanType::URI;
  14968. if (gen->d.uniformResourceIdentifier) {
  14969. entry.value = std::string(
  14970. reinterpret_cast<const char *>(
  14971. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14972. static_cast<size_t>(
  14973. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14974. }
  14975. break;
  14976. default: entry.type = SanType::OTHER; break;
  14977. }
  14978. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14979. }
  14980. GENERAL_NAMES_free(names);
  14981. return true;
  14982. }
  14983. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14984. time_t &not_after) {
  14985. if (!cert) return false;
  14986. auto x509 = static_cast<X509 *>(cert);
  14987. auto nb = X509_get0_notBefore(x509);
  14988. auto na = X509_get0_notAfter(x509);
  14989. if (!nb || !na) return false;
  14990. ASN1_TIME *epoch = ASN1_TIME_new();
  14991. if (!epoch) return false;
  14992. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14993. if (!ASN1_TIME_set(epoch, 0)) return false;
  14994. int pday, psec;
  14995. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14996. not_before = 86400 * (time_t)pday + psec;
  14997. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14998. not_after = 86400 * (time_t)pday + psec;
  14999. return true;
  15000. }
  15001. inline std::string get_cert_serial(cert_t cert) {
  15002. if (!cert) return "";
  15003. auto x509 = static_cast<X509 *>(cert);
  15004. auto serial = X509_get_serialNumber(x509);
  15005. if (!serial) return "";
  15006. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  15007. if (!bn) return "";
  15008. auto hex = BN_bn2hex(bn);
  15009. BN_free(bn);
  15010. if (!hex) return "";
  15011. std::string result(hex);
  15012. OPENSSL_free(hex);
  15013. return result;
  15014. }
  15015. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15016. if (!cert) return false;
  15017. auto x509 = static_cast<X509 *>(cert);
  15018. auto len = i2d_X509(x509, nullptr);
  15019. if (len < 0) return false;
  15020. der.resize(static_cast<size_t>(len));
  15021. auto p = der.data();
  15022. i2d_X509(x509, &p);
  15023. return true;
  15024. }
  15025. inline const char *get_sni(const_session_t session) {
  15026. if (!session) return nullptr;
  15027. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15028. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15029. }
  15030. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  15031. inline uint64_t get_error() { return ERR_get_error(); }
  15032. inline std::string error_string(uint64_t code) {
  15033. char buf[256];
  15034. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  15035. return std::string(buf);
  15036. }
  15037. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15038. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  15039. if (!mem) { return nullptr; }
  15040. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  15041. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  15042. if (!inf) { return nullptr; }
  15043. auto store = X509_STORE_new();
  15044. if (store) {
  15045. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15046. auto itmp = sk_X509_INFO_value(inf, i);
  15047. if (!itmp) { continue; }
  15048. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15049. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15050. }
  15051. }
  15052. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15053. return static_cast<ca_store_t>(store);
  15054. }
  15055. inline void free_ca_store(ca_store_t store) {
  15056. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15057. }
  15058. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15059. if (!ctx || !store) { return false; }
  15060. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15061. auto x509_store = static_cast<X509_STORE *>(store);
  15062. // Check if same store is already set
  15063. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15064. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15065. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15066. return true;
  15067. }
  15068. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15069. certs.clear();
  15070. if (!ctx) { return 0; }
  15071. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15072. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15073. if (!store) { return 0; }
  15074. auto objs = impl::get_store_objects(store);
  15075. if (!objs) { return 0; }
  15076. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15077. auto count = sk_X509_OBJECT_num(objs);
  15078. for (decltype(count) i = 0; i < count; i++) {
  15079. auto obj = sk_X509_OBJECT_value(objs, i);
  15080. if (!obj) { continue; }
  15081. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15082. auto x509 = X509_OBJECT_get0_X509(obj);
  15083. if (x509) {
  15084. // Increment reference count so caller can free it
  15085. X509_up_ref(x509);
  15086. certs.push_back(static_cast<cert_t>(x509));
  15087. }
  15088. }
  15089. }
  15090. return certs.size();
  15091. }
  15092. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15093. std::vector<std::string> names;
  15094. if (!ctx) { return names; }
  15095. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15096. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15097. if (!store) { return names; }
  15098. auto objs = impl::get_store_objects(store);
  15099. if (!objs) { return names; }
  15100. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15101. auto count = sk_X509_OBJECT_num(objs);
  15102. for (decltype(count) i = 0; i < count; i++) {
  15103. auto obj = sk_X509_OBJECT_value(objs, i);
  15104. if (!obj) { continue; }
  15105. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15106. auto x509 = X509_OBJECT_get0_X509(obj);
  15107. if (x509) {
  15108. auto subject = X509_get_subject_name(x509);
  15109. if (subject) {
  15110. char buf[512];
  15111. X509_NAME_oneline(subject, buf, sizeof(buf));
  15112. names.push_back(buf);
  15113. }
  15114. }
  15115. }
  15116. }
  15117. return names;
  15118. }
  15119. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15120. const char *key_pem, const char *password) {
  15121. if (!ctx || !cert_pem || !key_pem) { return false; }
  15122. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15123. // Load certificate from PEM
  15124. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15125. if (!cert_bio) { return false; }
  15126. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15127. BIO_free(cert_bio);
  15128. if (!cert) { return false; }
  15129. // Load private key from PEM
  15130. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15131. if (!key_bio) {
  15132. X509_free(cert);
  15133. return false;
  15134. }
  15135. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15136. password ? const_cast<char *>(password)
  15137. : nullptr);
  15138. BIO_free(key_bio);
  15139. if (!key) {
  15140. X509_free(cert);
  15141. return false;
  15142. }
  15143. // Update certificate and key
  15144. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15145. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15146. X509_free(cert);
  15147. EVP_PKEY_free(key);
  15148. return ret;
  15149. }
  15150. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15151. if (!ctx || !ca_pem) { return false; }
  15152. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15153. // Create new X509_STORE from PEM
  15154. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15155. if (!store) { return false; }
  15156. // SSL_CTX_set_cert_store takes ownership
  15157. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15158. // Set client CA list for client certificate request
  15159. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15160. if (ca_list) {
  15161. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15162. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15163. }
  15164. return true;
  15165. }
  15166. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15167. if (!ctx) { return false; }
  15168. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15169. impl::get_verify_callback() = std::move(callback);
  15170. if (impl::get_verify_callback()) {
  15171. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15172. } else {
  15173. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15174. }
  15175. return true;
  15176. }
  15177. inline long get_verify_error(const_session_t session) {
  15178. if (!session) { return -1; }
  15179. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15180. return SSL_get_verify_result(ssl);
  15181. }
  15182. inline std::string verify_error_string(long error_code) {
  15183. if (error_code == X509_V_OK) { return ""; }
  15184. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15185. return str ? str : "unknown error";
  15186. }
  15187. } // namespace tls
  15188. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15189. /*
  15190. * Group 9: TLS abstraction layer - Mbed TLS backend
  15191. */
  15192. /*
  15193. * Mbed TLS Backend Implementation
  15194. */
  15195. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15196. namespace tls {
  15197. namespace impl {
  15198. // Mbed TLS session wrapper
  15199. struct MbedTlsSession {
  15200. mbedtls_ssl_context ssl;
  15201. socket_t sock = INVALID_SOCKET;
  15202. std::string hostname; // For client: set via set_sni
  15203. std::string sni_hostname; // For server: received from client via SNI callback
  15204. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15205. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15206. MbedTlsSession(const MbedTlsSession &) = delete;
  15207. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15208. };
  15209. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15210. // queue)
  15211. inline int &mbedtls_last_error() {
  15212. static thread_local int err = 0;
  15213. return err;
  15214. }
  15215. // Helper to map Mbed TLS error to ErrorCode
  15216. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15217. if (ret == 0) { return ErrorCode::Success; }
  15218. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15219. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15220. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15221. return ErrorCode::PeerClosed;
  15222. }
  15223. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15224. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15225. out_errno = errno;
  15226. return ErrorCode::SyscallError;
  15227. }
  15228. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15229. return ErrorCode::CertVerifyFailed;
  15230. }
  15231. return ErrorCode::Fatal;
  15232. }
  15233. // BIO-like send callback for Mbed TLS
  15234. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15235. size_t len) {
  15236. auto sock = *static_cast<socket_t *>(ctx);
  15237. #ifdef _WIN32
  15238. auto ret =
  15239. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15240. if (ret == SOCKET_ERROR) {
  15241. int err = WSAGetLastError();
  15242. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15243. return MBEDTLS_ERR_NET_SEND_FAILED;
  15244. }
  15245. #else
  15246. auto ret = send(sock, buf, len, 0);
  15247. if (ret < 0) {
  15248. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15249. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15250. }
  15251. return MBEDTLS_ERR_NET_SEND_FAILED;
  15252. }
  15253. #endif
  15254. return static_cast<int>(ret);
  15255. }
  15256. // BIO-like recv callback for Mbed TLS
  15257. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15258. auto sock = *static_cast<socket_t *>(ctx);
  15259. #ifdef _WIN32
  15260. auto ret =
  15261. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15262. if (ret == SOCKET_ERROR) {
  15263. int err = WSAGetLastError();
  15264. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15265. return MBEDTLS_ERR_NET_RECV_FAILED;
  15266. }
  15267. #else
  15268. auto ret = recv(sock, buf, len, 0);
  15269. if (ret < 0) {
  15270. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15271. return MBEDTLS_ERR_SSL_WANT_READ;
  15272. }
  15273. return MBEDTLS_ERR_NET_RECV_FAILED;
  15274. }
  15275. #endif
  15276. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15277. return static_cast<int>(ret);
  15278. }
  15279. // MbedTlsContext constructor/destructor implementations
  15280. inline MbedTlsContext::MbedTlsContext() {
  15281. mbedtls_ssl_config_init(&conf);
  15282. mbedtls_entropy_init(&entropy);
  15283. mbedtls_ctr_drbg_init(&ctr_drbg);
  15284. mbedtls_x509_crt_init(&ca_chain);
  15285. mbedtls_x509_crt_init(&own_cert);
  15286. mbedtls_pk_init(&own_key);
  15287. }
  15288. inline MbedTlsContext::~MbedTlsContext() {
  15289. mbedtls_pk_free(&own_key);
  15290. mbedtls_x509_crt_free(&own_cert);
  15291. mbedtls_x509_crt_free(&ca_chain);
  15292. mbedtls_ctr_drbg_free(&ctr_drbg);
  15293. mbedtls_entropy_free(&entropy);
  15294. mbedtls_ssl_config_free(&conf);
  15295. }
  15296. // Thread-local storage for SNI captured during handshake
  15297. // This is needed because the SNI callback doesn't have a way to pass
  15298. // session-specific data before the session is fully set up
  15299. inline std::string &mbedpending_sni() {
  15300. static thread_local std::string sni;
  15301. return sni;
  15302. }
  15303. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15304. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15305. const unsigned char *name, size_t name_len) {
  15306. (void)p_ctx;
  15307. (void)ssl;
  15308. // Store SNI name in thread-local storage
  15309. // It will be retrieved and stored in the session after handshake
  15310. if (name && name_len > 0) {
  15311. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15312. } else {
  15313. mbedpending_sni().clear();
  15314. }
  15315. return 0; // Accept any SNI
  15316. }
  15317. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15318. int cert_depth, uint32_t *flags);
  15319. // MbedTLS verify callback wrapper
  15320. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15321. int cert_depth, uint32_t *flags) {
  15322. auto &callback = get_verify_callback();
  15323. if (!callback) { return 0; } // Continue with default verification
  15324. // data points to the MbedTlsSession
  15325. auto *session = static_cast<MbedTlsSession *>(data);
  15326. // Build context
  15327. VerifyContext verify_ctx;
  15328. verify_ctx.session = static_cast<session_t>(session);
  15329. verify_ctx.cert = static_cast<cert_t>(crt);
  15330. verify_ctx.depth = cert_depth;
  15331. verify_ctx.preverify_ok = (*flags == 0);
  15332. verify_ctx.error_code = static_cast<long>(*flags);
  15333. // Convert Mbed TLS flags to error string
  15334. static thread_local char error_buf[256];
  15335. if (*flags != 0) {
  15336. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15337. verify_ctx.error_string = error_buf;
  15338. } else {
  15339. verify_ctx.error_string = nullptr;
  15340. }
  15341. bool accepted = callback(verify_ctx);
  15342. if (accepted) {
  15343. *flags = 0; // Clear all error flags
  15344. return 0;
  15345. }
  15346. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15347. }
  15348. } // namespace impl
  15349. inline ctx_t create_client_context() {
  15350. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15351. if (!ctx) { return nullptr; }
  15352. ctx->is_server = false;
  15353. // Seed the random number generator
  15354. const char *pers = "httplib_client";
  15355. int ret = mbedtls_ctr_drbg_seed(
  15356. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15357. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15358. if (ret != 0) {
  15359. impl::mbedtls_last_error() = ret;
  15360. delete ctx;
  15361. return nullptr;
  15362. }
  15363. // Set up SSL config for client
  15364. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15365. MBEDTLS_SSL_TRANSPORT_STREAM,
  15366. MBEDTLS_SSL_PRESET_DEFAULT);
  15367. if (ret != 0) {
  15368. impl::mbedtls_last_error() = ret;
  15369. delete ctx;
  15370. return nullptr;
  15371. }
  15372. // Set random number generator
  15373. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15374. // Default: verify peer certificate
  15375. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15376. // Set minimum TLS version to 1.2
  15377. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15378. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15379. #else
  15380. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15381. MBEDTLS_SSL_MINOR_VERSION_3);
  15382. #endif
  15383. return static_cast<ctx_t>(ctx);
  15384. }
  15385. inline ctx_t create_server_context() {
  15386. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15387. if (!ctx) { return nullptr; }
  15388. ctx->is_server = true;
  15389. // Seed the random number generator
  15390. const char *pers = "httplib_server";
  15391. int ret = mbedtls_ctr_drbg_seed(
  15392. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15393. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15394. if (ret != 0) {
  15395. impl::mbedtls_last_error() = ret;
  15396. delete ctx;
  15397. return nullptr;
  15398. }
  15399. // Set up SSL config for server
  15400. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15401. MBEDTLS_SSL_TRANSPORT_STREAM,
  15402. MBEDTLS_SSL_PRESET_DEFAULT);
  15403. if (ret != 0) {
  15404. impl::mbedtls_last_error() = ret;
  15405. delete ctx;
  15406. return nullptr;
  15407. }
  15408. // Set random number generator
  15409. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15410. // Default: don't verify client
  15411. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15412. // Set minimum TLS version to 1.2
  15413. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15414. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15415. #else
  15416. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15417. MBEDTLS_SSL_MINOR_VERSION_3);
  15418. #endif
  15419. // Set SNI callback to capture client's SNI hostname
  15420. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15421. return static_cast<ctx_t>(ctx);
  15422. }
  15423. inline void free_context(ctx_t ctx) {
  15424. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15425. }
  15426. inline bool set_min_version(ctx_t ctx, Version version) {
  15427. if (!ctx) { return false; }
  15428. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15429. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15430. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15431. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15432. if (version >= Version::TLS1_3) {
  15433. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15434. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15435. #endif
  15436. }
  15437. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15438. #else
  15439. // Mbed TLS 2.x uses major/minor version numbers
  15440. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15441. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15442. if (version >= Version::TLS1_3) {
  15443. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15444. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15445. #else
  15446. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15447. #endif
  15448. }
  15449. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15450. #endif
  15451. return true;
  15452. }
  15453. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15454. if (!ctx || !pem) { return false; }
  15455. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15456. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15457. // Add null terminator if not present
  15458. std::string pem_str(pem, len);
  15459. int ret = mbedtls_x509_crt_parse(
  15460. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15461. pem_str.size() + 1);
  15462. if (ret != 0) {
  15463. impl::mbedtls_last_error() = ret;
  15464. return false;
  15465. }
  15466. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15467. return true;
  15468. }
  15469. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15470. if (!ctx || !file_path) { return false; }
  15471. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15472. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15473. if (ret != 0) {
  15474. impl::mbedtls_last_error() = ret;
  15475. return false;
  15476. }
  15477. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15478. return true;
  15479. }
  15480. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15481. if (!ctx || !dir_path) { return false; }
  15482. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15483. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15484. if (ret < 0) { // Returns number of certs on success, negative on error
  15485. impl::mbedtls_last_error() = ret;
  15486. return false;
  15487. }
  15488. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15489. return true;
  15490. }
  15491. inline bool load_system_certs(ctx_t ctx) {
  15492. if (!ctx) { return false; }
  15493. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15494. bool loaded = false;
  15495. #ifdef _WIN32
  15496. loaded = impl::enumerate_windows_system_certs(
  15497. [&](const unsigned char *data, size_t len) {
  15498. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15499. });
  15500. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15501. loaded = impl::enumerate_macos_keychain_certs(
  15502. [&](const unsigned char *data, size_t len) {
  15503. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15504. });
  15505. #else
  15506. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15507. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15508. loaded = true;
  15509. break;
  15510. }
  15511. }
  15512. if (!loaded) {
  15513. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15514. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15515. loaded = true;
  15516. break;
  15517. }
  15518. }
  15519. }
  15520. #endif
  15521. if (loaded) {
  15522. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15523. }
  15524. return loaded;
  15525. }
  15526. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15527. const char *password) {
  15528. if (!ctx || !cert || !key) { return false; }
  15529. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15530. // Parse certificate
  15531. std::string cert_str(cert);
  15532. int ret = mbedtls_x509_crt_parse(
  15533. &mctx->own_cert,
  15534. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15535. cert_str.size() + 1);
  15536. if (ret != 0) {
  15537. impl::mbedtls_last_error() = ret;
  15538. return false;
  15539. }
  15540. // Parse private key
  15541. std::string key_str(key);
  15542. const unsigned char *pwd =
  15543. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15544. size_t pwd_len = password ? strlen(password) : 0;
  15545. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15546. ret = mbedtls_pk_parse_key(
  15547. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15548. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15549. &mctx->ctr_drbg);
  15550. #else
  15551. ret = mbedtls_pk_parse_key(
  15552. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15553. key_str.size() + 1, pwd, pwd_len);
  15554. #endif
  15555. if (ret != 0) {
  15556. impl::mbedtls_last_error() = ret;
  15557. return false;
  15558. }
  15559. // Verify that the certificate and private key match
  15560. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15561. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15562. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15563. #else
  15564. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15565. #endif
  15566. if (ret != 0) {
  15567. impl::mbedtls_last_error() = ret;
  15568. return false;
  15569. }
  15570. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15571. if (ret != 0) {
  15572. impl::mbedtls_last_error() = ret;
  15573. return false;
  15574. }
  15575. return true;
  15576. }
  15577. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15578. const char *key_path, const char *password) {
  15579. if (!ctx || !cert_path || !key_path) { return false; }
  15580. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15581. // Parse certificate file
  15582. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15583. if (ret != 0) {
  15584. impl::mbedtls_last_error() = ret;
  15585. return false;
  15586. }
  15587. // Parse private key file
  15588. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15589. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15590. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15591. #else
  15592. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15593. #endif
  15594. if (ret != 0) {
  15595. impl::mbedtls_last_error() = ret;
  15596. return false;
  15597. }
  15598. // Verify that the certificate and private key match
  15599. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15600. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15601. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15602. #else
  15603. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15604. #endif
  15605. if (ret != 0) {
  15606. impl::mbedtls_last_error() = ret;
  15607. return false;
  15608. }
  15609. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15610. if (ret != 0) {
  15611. impl::mbedtls_last_error() = ret;
  15612. return false;
  15613. }
  15614. return true;
  15615. }
  15616. inline void set_verify_client(ctx_t ctx, bool require) {
  15617. if (!ctx) { return; }
  15618. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15619. mctx->verify_client = require;
  15620. if (require) {
  15621. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15622. } else {
  15623. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15624. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15625. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15626. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15627. : MBEDTLS_SSL_VERIFY_NONE);
  15628. }
  15629. }
  15630. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15631. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15632. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15633. auto session = new (std::nothrow) impl::MbedTlsSession();
  15634. if (!session) { return nullptr; }
  15635. session->sock = sock;
  15636. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15637. if (ret != 0) {
  15638. impl::mbedtls_last_error() = ret;
  15639. delete session;
  15640. return nullptr;
  15641. }
  15642. // Explicitly opt out of in-handshake hostname verification by default;
  15643. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15644. // fails outright when no hostname was set. set_sni() installs the real
  15645. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15646. // caller verifies the certificate identity post-handshake via
  15647. // verify_hostname().
  15648. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15649. // Set BIO callbacks
  15650. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15651. impl::mbedtls_net_recv_cb, nullptr);
  15652. // Set per-session verify callback with session pointer if callback is
  15653. // registered
  15654. if (mctx->has_verify_callback) {
  15655. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15656. session);
  15657. }
  15658. return static_cast<session_t>(session);
  15659. }
  15660. inline void free_session(session_t session) {
  15661. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15662. }
  15663. inline bool set_sni(session_t session, const char *hostname) {
  15664. if (!session || !hostname) { return false; }
  15665. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15666. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15667. if (ret != 0) {
  15668. impl::mbedtls_last_error() = ret;
  15669. return false;
  15670. }
  15671. msession->hostname = hostname;
  15672. return true;
  15673. }
  15674. inline bool set_hostname(session_t session, const char *hostname) {
  15675. // In Mbed TLS, set_hostname also sets up hostname verification
  15676. return set_sni(session, hostname);
  15677. }
  15678. inline TlsError connect(session_t session) {
  15679. TlsError err;
  15680. if (!session) {
  15681. err.code = ErrorCode::Fatal;
  15682. return err;
  15683. }
  15684. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15685. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15686. if (ret == 0) {
  15687. err.code = ErrorCode::Success;
  15688. } else {
  15689. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15690. err.backend_code = static_cast<uint64_t>(-ret);
  15691. impl::mbedtls_last_error() = ret;
  15692. }
  15693. return err;
  15694. }
  15695. inline TlsError accept(session_t session) {
  15696. // Same as connect for Mbed TLS - handshake works for both client and server
  15697. auto result = connect(session);
  15698. // After successful handshake, capture SNI from thread-local storage
  15699. if (result.code == ErrorCode::Success && session) {
  15700. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15701. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15702. impl::mbedpending_sni().clear();
  15703. }
  15704. return result;
  15705. }
  15706. inline bool connect_nonblocking(session_t session, socket_t sock,
  15707. time_t timeout_sec, time_t timeout_usec,
  15708. TlsError *err) {
  15709. if (!session) {
  15710. if (err) { err->code = ErrorCode::Fatal; }
  15711. return false;
  15712. }
  15713. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15714. // Set socket to non-blocking mode
  15715. detail::set_nonblocking(sock, true);
  15716. auto cleanup =
  15717. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15718. int ret;
  15719. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15720. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15721. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15722. continue;
  15723. }
  15724. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15725. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15726. continue;
  15727. }
  15728. }
  15729. // TlsError or timeout
  15730. if (err) {
  15731. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15732. err->backend_code = static_cast<uint64_t>(-ret);
  15733. }
  15734. impl::mbedtls_last_error() = ret;
  15735. return false;
  15736. }
  15737. if (err) { err->code = ErrorCode::Success; }
  15738. return true;
  15739. }
  15740. inline bool accept_nonblocking(session_t session, socket_t sock,
  15741. time_t timeout_sec, time_t timeout_usec,
  15742. TlsError *err) {
  15743. // Same implementation as connect for Mbed TLS
  15744. bool result =
  15745. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15746. // After successful handshake, capture SNI from thread-local storage
  15747. if (result && session) {
  15748. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15749. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15750. impl::mbedpending_sni().clear();
  15751. }
  15752. return result;
  15753. }
  15754. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15755. if (!session || !buf) {
  15756. err.code = ErrorCode::Fatal;
  15757. return -1;
  15758. }
  15759. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15760. int ret =
  15761. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15762. if (ret > 0) {
  15763. err.code = ErrorCode::Success;
  15764. return static_cast<ssize_t>(ret);
  15765. }
  15766. if (ret == 0) {
  15767. err.code = ErrorCode::PeerClosed;
  15768. return 0;
  15769. }
  15770. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15771. err.backend_code = static_cast<uint64_t>(-ret);
  15772. impl::mbedtls_last_error() = ret;
  15773. // mbedTLS signals a clean close_notify via a negative error code rather
  15774. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15775. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15776. return -1;
  15777. }
  15778. inline ssize_t write(session_t session, const void *buf, size_t len,
  15779. TlsError &err) {
  15780. if (!session || !buf) {
  15781. err.code = ErrorCode::Fatal;
  15782. return -1;
  15783. }
  15784. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15785. int ret = mbedtls_ssl_write(&msession->ssl,
  15786. static_cast<const unsigned char *>(buf), len);
  15787. if (ret > 0) {
  15788. err.code = ErrorCode::Success;
  15789. return static_cast<ssize_t>(ret);
  15790. }
  15791. if (ret == 0) {
  15792. err.code = ErrorCode::PeerClosed;
  15793. return 0;
  15794. }
  15795. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15796. err.backend_code = static_cast<uint64_t>(-ret);
  15797. impl::mbedtls_last_error() = ret;
  15798. return -1;
  15799. }
  15800. inline int pending(const_session_t session) {
  15801. if (!session) { return 0; }
  15802. auto msession =
  15803. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15804. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15805. }
  15806. inline void shutdown(session_t session, bool graceful) {
  15807. if (!session) { return; }
  15808. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15809. if (graceful) {
  15810. // Try to send close_notify, but don't block forever
  15811. int ret;
  15812. int attempts = 0;
  15813. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15814. attempts < 3) {
  15815. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15816. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15817. break;
  15818. }
  15819. attempts++;
  15820. }
  15821. }
  15822. }
  15823. inline bool is_peer_closed(session_t session, socket_t sock) {
  15824. if (!session || sock == INVALID_SOCKET) { return true; }
  15825. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15826. // Check if there's already decrypted data available in the TLS buffer
  15827. // If so, the connection is definitely alive
  15828. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15829. // Set socket to non-blocking to avoid blocking on read
  15830. detail::set_nonblocking(sock, true);
  15831. auto cleanup =
  15832. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15833. // Try a 1-byte read to check connection status
  15834. // Note: This will consume the byte if data is available, but for the
  15835. // purpose of checking if peer is closed, this should be acceptable
  15836. // since we're only called when we expect the connection might be closing
  15837. unsigned char buf;
  15838. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15839. // If we got data or WANT_READ (would block), connection is alive
  15840. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15841. // If we get a peer close notify or a connection reset, the peer is closed
  15842. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15843. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15844. }
  15845. inline cert_t get_peer_cert(const_session_t session) {
  15846. if (!session) { return nullptr; }
  15847. auto msession =
  15848. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15849. // Mbed TLS returns a pointer to the internal peer cert chain.
  15850. // WARNING: This pointer is only valid while the session is active.
  15851. // Do not use the certificate after calling free_session().
  15852. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15853. return const_cast<mbedtls_x509_crt *>(cert);
  15854. }
  15855. inline void free_cert(cert_t cert) {
  15856. // Mbed TLS: peer certificate is owned by the SSL context.
  15857. // No-op here, but callers should still call this for cross-backend
  15858. // portability.
  15859. (void)cert;
  15860. }
  15861. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15862. if (!cert || !hostname) { return false; }
  15863. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15864. std::string host_str(hostname);
  15865. // Check if hostname is an IP address (IPv4 or IPv6)
  15866. unsigned char ip_bytes[16];
  15867. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15868. auto is_ip = ip_len > 0;
  15869. // Check Subject Alternative Names (SAN)
  15870. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15871. // - DNS names: raw string bytes
  15872. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15873. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15874. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15875. const unsigned char *p = san->buf.p;
  15876. size_t len = san->buf.len;
  15877. if (is_ip) {
  15878. // For an IP host, only a matching iPAddress SAN of the same family
  15879. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15880. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15881. } else {
  15882. // Check if this SAN is a DNS name (printable ASCII string)
  15883. bool is_dns = len > 0;
  15884. for (size_t i = 0; i < len && is_dns; i++) {
  15885. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15886. }
  15887. if (is_dns) {
  15888. std::string san_name(reinterpret_cast<const char *>(p), len);
  15889. if (detail::match_hostname(san_name, host_str)) { return true; }
  15890. }
  15891. }
  15892. san = san->next;
  15893. }
  15894. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15895. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15896. // the OpenSSL backend's X509_check_ip behaves the same way).
  15897. if (!is_ip) {
  15898. char cn[256];
  15899. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15900. if (ret > 0) {
  15901. std::string cn_str(cn);
  15902. // Look for "CN=" in the DN string
  15903. size_t cn_pos = cn_str.find("CN=");
  15904. if (cn_pos != std::string::npos) {
  15905. size_t start = cn_pos + 3;
  15906. size_t end = cn_str.find(',', start);
  15907. std::string cn_value =
  15908. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15909. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15910. }
  15911. }
  15912. }
  15913. return false;
  15914. }
  15915. inline uint64_t hostname_mismatch_code() {
  15916. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15917. }
  15918. inline long get_verify_result(const_session_t session) {
  15919. if (!session) { return -1; }
  15920. auto msession =
  15921. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15922. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15923. // Return 0 (X509_V_OK equivalent) if verification passed
  15924. return flags == 0 ? 0 : static_cast<long>(flags);
  15925. }
  15926. inline std::string get_cert_subject_cn(cert_t cert) {
  15927. if (!cert) return "";
  15928. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15929. // Find the CN in the subject
  15930. const mbedtls_x509_name *name = &x509->subject;
  15931. while (name != nullptr) {
  15932. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15933. return std::string(reinterpret_cast<const char *>(name->val.p),
  15934. name->val.len);
  15935. }
  15936. name = name->next;
  15937. }
  15938. return "";
  15939. }
  15940. inline std::string get_cert_issuer_name(cert_t cert) {
  15941. if (!cert) return "";
  15942. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15943. // Build a human-readable issuer name string
  15944. char buf[512];
  15945. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15946. if (ret < 0) return "";
  15947. return std::string(buf);
  15948. }
  15949. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15950. sans.clear();
  15951. if (!cert) return false;
  15952. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15953. // Parse the Subject Alternative Name extension
  15954. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15955. while (cur != nullptr) {
  15956. if (cur->buf.len > 0) {
  15957. // Mbed TLS stores SAN as ASN.1 sequences
  15958. // The tag byte indicates the type
  15959. const unsigned char *p = cur->buf.p;
  15960. size_t len = cur->buf.len;
  15961. // First byte is the tag
  15962. unsigned char tag = *p;
  15963. p++;
  15964. len--;
  15965. // Parse length (simple single-byte length assumed)
  15966. if (len > 0 && *p < 0x80) {
  15967. size_t value_len = *p;
  15968. p++;
  15969. len--;
  15970. if (value_len <= len) {
  15971. SanEntry entry;
  15972. // ASN.1 context tags for GeneralName
  15973. switch (tag & 0x1F) {
  15974. case 2: // dNSName
  15975. entry.type = SanType::DNS;
  15976. entry.value =
  15977. std::string(reinterpret_cast<const char *>(p), value_len);
  15978. break;
  15979. case 7: // iPAddress
  15980. entry.type = SanType::IP;
  15981. if (value_len == 4) {
  15982. // IPv4
  15983. char buf[16];
  15984. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15985. entry.value = buf;
  15986. } else if (value_len == 16) {
  15987. // IPv6
  15988. char buf[64];
  15989. snprintf(buf, sizeof(buf),
  15990. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15991. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15992. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15993. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15994. entry.value = buf;
  15995. }
  15996. break;
  15997. case 1: // rfc822Name (email)
  15998. entry.type = SanType::EMAIL;
  15999. entry.value =
  16000. std::string(reinterpret_cast<const char *>(p), value_len);
  16001. break;
  16002. case 6: // uniformResourceIdentifier
  16003. entry.type = SanType::URI;
  16004. entry.value =
  16005. std::string(reinterpret_cast<const char *>(p), value_len);
  16006. break;
  16007. default: entry.type = SanType::OTHER; break;
  16008. }
  16009. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16010. }
  16011. }
  16012. }
  16013. cur = cur->next;
  16014. }
  16015. return true;
  16016. }
  16017. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16018. time_t &not_after) {
  16019. if (!cert) return false;
  16020. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16021. // Convert mbedtls_x509_time to time_t
  16022. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  16023. struct tm tm_time = {};
  16024. tm_time.tm_year = t.year - 1900;
  16025. tm_time.tm_mon = t.mon - 1;
  16026. tm_time.tm_mday = t.day;
  16027. tm_time.tm_hour = t.hour;
  16028. tm_time.tm_min = t.min;
  16029. tm_time.tm_sec = t.sec;
  16030. #ifdef _WIN32
  16031. return _mkgmtime(&tm_time);
  16032. #else
  16033. return timegm(&tm_time);
  16034. #endif
  16035. };
  16036. not_before = to_time_t(x509->valid_from);
  16037. not_after = to_time_t(x509->valid_to);
  16038. return true;
  16039. }
  16040. inline std::string get_cert_serial(cert_t cert) {
  16041. if (!cert) return "";
  16042. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16043. // Convert serial number to hex string
  16044. std::string result;
  16045. result.reserve(x509->serial.len * 2);
  16046. for (size_t i = 0; i < x509->serial.len; i++) {
  16047. char hex[3];
  16048. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16049. result += hex;
  16050. }
  16051. return result;
  16052. }
  16053. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16054. if (!cert) return false;
  16055. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16056. if (!crt->raw.p || crt->raw.len == 0) return false;
  16057. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16058. return true;
  16059. }
  16060. inline const char *get_sni(const_session_t session) {
  16061. if (!session) return nullptr;
  16062. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16063. // For server: return SNI received from client during handshake
  16064. if (!msession->sni_hostname.empty()) {
  16065. return msession->sni_hostname.c_str();
  16066. }
  16067. // For client: return the hostname set via set_sni
  16068. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16069. return nullptr;
  16070. }
  16071. inline uint64_t peek_error() {
  16072. // Mbed TLS doesn't have an error queue, return the last error
  16073. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16074. }
  16075. inline uint64_t get_error() {
  16076. // Mbed TLS doesn't have an error queue, return and clear the last error
  16077. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16078. impl::mbedtls_last_error() = 0;
  16079. return err;
  16080. }
  16081. inline std::string error_string(uint64_t code) {
  16082. char buf[256];
  16083. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16084. return std::string(buf);
  16085. }
  16086. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16087. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16088. if (!ca_chain) { return nullptr; }
  16089. mbedtls_x509_crt_init(ca_chain);
  16090. // mbedtls_x509_crt_parse expects null-terminated PEM
  16091. int ret = mbedtls_x509_crt_parse(ca_chain,
  16092. reinterpret_cast<const unsigned char *>(pem),
  16093. len + 1); // +1 for null terminator
  16094. if (ret != 0) {
  16095. // Try without +1 in case PEM is already null-terminated
  16096. ret = mbedtls_x509_crt_parse(
  16097. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16098. if (ret != 0) {
  16099. mbedtls_x509_crt_free(ca_chain);
  16100. delete ca_chain;
  16101. return nullptr;
  16102. }
  16103. }
  16104. return static_cast<ca_store_t>(ca_chain);
  16105. }
  16106. inline void free_ca_store(ca_store_t store) {
  16107. if (store) {
  16108. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16109. mbedtls_x509_crt_free(ca_chain);
  16110. delete ca_chain;
  16111. }
  16112. }
  16113. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16114. if (!ctx || !store) { return false; }
  16115. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16116. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16117. // Free existing CA chain
  16118. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16119. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16120. // Copy the CA chain (deep copy)
  16121. // Parse from the raw data of the source cert
  16122. mbedtls_x509_crt *src = ca_chain;
  16123. while (src != nullptr) {
  16124. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16125. src->raw.len);
  16126. if (ret != 0) {
  16127. free_ca_store(store);
  16128. return false;
  16129. }
  16130. src = src->next;
  16131. }
  16132. // This function takes ownership of the store; the chain was deep-copied
  16133. // above, so release the source
  16134. free_ca_store(store);
  16135. // Update the SSL config to use the new CA chain
  16136. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16137. return true;
  16138. }
  16139. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16140. certs.clear();
  16141. if (!ctx) { return 0; }
  16142. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16143. // Iterate through the CA chain
  16144. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16145. while (cert != nullptr && cert->raw.len > 0) {
  16146. // Create a copy of the certificate for the caller
  16147. auto *copy = new mbedtls_x509_crt;
  16148. mbedtls_x509_crt_init(copy);
  16149. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16150. if (ret == 0) {
  16151. certs.push_back(static_cast<cert_t>(copy));
  16152. } else {
  16153. mbedtls_x509_crt_free(copy);
  16154. delete copy;
  16155. }
  16156. cert = cert->next;
  16157. }
  16158. return certs.size();
  16159. }
  16160. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16161. std::vector<std::string> names;
  16162. if (!ctx) { return names; }
  16163. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16164. // Iterate through the CA chain
  16165. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16166. while (cert != nullptr && cert->raw.len > 0) {
  16167. char buf[512];
  16168. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16169. if (ret > 0) { names.push_back(buf); }
  16170. cert = cert->next;
  16171. }
  16172. return names;
  16173. }
  16174. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16175. const char *key_pem, const char *password) {
  16176. if (!ctx || !cert_pem || !key_pem) { return false; }
  16177. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16178. // Free existing certificate and key
  16179. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16180. mbedtls_pk_free(&mbed_ctx->own_key);
  16181. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16182. mbedtls_pk_init(&mbed_ctx->own_key);
  16183. // Parse certificate PEM
  16184. int ret = mbedtls_x509_crt_parse(
  16185. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16186. strlen(cert_pem) + 1);
  16187. if (ret != 0) {
  16188. impl::mbedtls_last_error() = ret;
  16189. return false;
  16190. }
  16191. // Parse private key PEM
  16192. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16193. ret = mbedtls_pk_parse_key(
  16194. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16195. strlen(key_pem) + 1,
  16196. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16197. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16198. &mbed_ctx->ctr_drbg);
  16199. #else
  16200. ret = mbedtls_pk_parse_key(
  16201. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16202. strlen(key_pem) + 1,
  16203. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16204. password ? strlen(password) : 0);
  16205. #endif
  16206. if (ret != 0) {
  16207. impl::mbedtls_last_error() = ret;
  16208. return false;
  16209. }
  16210. // Configure SSL to use the new certificate and key
  16211. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16212. &mbed_ctx->own_key);
  16213. if (ret != 0) {
  16214. impl::mbedtls_last_error() = ret;
  16215. return false;
  16216. }
  16217. return true;
  16218. }
  16219. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16220. if (!ctx || !ca_pem) { return false; }
  16221. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16222. // Free existing CA chain
  16223. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16224. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16225. // Parse CA PEM
  16226. int ret = mbedtls_x509_crt_parse(
  16227. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16228. strlen(ca_pem) + 1);
  16229. if (ret != 0) {
  16230. impl::mbedtls_last_error() = ret;
  16231. return false;
  16232. }
  16233. // Update SSL config to use new CA chain
  16234. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16235. return true;
  16236. }
  16237. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16238. if (!ctx) { return false; }
  16239. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16240. impl::get_verify_callback() = std::move(callback);
  16241. mbed_ctx->has_verify_callback =
  16242. static_cast<bool>(impl::get_verify_callback());
  16243. if (mbed_ctx->has_verify_callback) {
  16244. // Set OPTIONAL mode to ensure callback is called even when verification
  16245. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16246. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16247. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16248. nullptr);
  16249. } else {
  16250. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16251. }
  16252. return true;
  16253. }
  16254. inline long get_verify_error(const_session_t session) {
  16255. if (!session) { return -1; }
  16256. auto *msession =
  16257. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16258. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16259. }
  16260. inline std::string verify_error_string(long error_code) {
  16261. if (error_code == 0) { return ""; }
  16262. char buf[256];
  16263. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16264. static_cast<uint32_t>(error_code));
  16265. // Remove trailing newline if present
  16266. std::string result(buf);
  16267. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16268. result.pop_back();
  16269. }
  16270. return result;
  16271. }
  16272. } // namespace tls
  16273. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16274. /*
  16275. * Group 10: TLS abstraction layer - wolfSSL backend
  16276. */
  16277. /*
  16278. * wolfSSL Backend Implementation
  16279. */
  16280. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16281. namespace tls {
  16282. namespace impl {
  16283. // wolfSSL session wrapper
  16284. struct WolfSSLSession {
  16285. WOLFSSL *ssl = nullptr;
  16286. socket_t sock = INVALID_SOCKET;
  16287. std::string hostname; // For client: set via set_sni
  16288. std::string sni_hostname; // For server: received from client via SNI callback
  16289. WolfSSLSession() = default;
  16290. ~WolfSSLSession() {
  16291. if (ssl) { wolfSSL_free(ssl); }
  16292. }
  16293. WolfSSLSession(const WolfSSLSession &) = delete;
  16294. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16295. };
  16296. // Thread-local error code accessor for wolfSSL
  16297. inline uint64_t &wolfssl_last_error() {
  16298. static thread_local uint64_t err = 0;
  16299. return err;
  16300. }
  16301. // Helper to map wolfSSL error to ErrorCode.
  16302. // ssl_error is the value from wolfSSL_get_error().
  16303. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16304. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16305. int &out_errno) {
  16306. switch (ssl_error) {
  16307. case SSL_ERROR_NONE: return ErrorCode::Success;
  16308. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16309. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16310. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16311. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16312. default:
  16313. if (ssl) {
  16314. // wolfSSL stores the low-level error code as a negative value.
  16315. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16316. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16317. if (low_err == DOMAIN_NAME_MISMATCH) {
  16318. return ErrorCode::HostnameMismatch;
  16319. }
  16320. // Check verify result to distinguish cert verification from generic SSL
  16321. // errors.
  16322. long vr = wolfSSL_get_verify_result(ssl);
  16323. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16324. }
  16325. return ErrorCode::Fatal;
  16326. }
  16327. }
  16328. // WolfSSLContext constructor/destructor implementations
  16329. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16330. inline WolfSSLContext::~WolfSSLContext() {
  16331. if (ctx) { wolfSSL_CTX_free(ctx); }
  16332. }
  16333. // Thread-local storage for SNI captured during handshake
  16334. inline std::string &wolfssl_pending_sni() {
  16335. static thread_local std::string sni;
  16336. return sni;
  16337. }
  16338. // SNI callback for wolfSSL server to capture client's SNI hostname
  16339. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16340. (void)ret;
  16341. (void)exArg;
  16342. void *name_data = nullptr;
  16343. unsigned short name_len =
  16344. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16345. if (name_data && name_len > 0) {
  16346. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16347. name_len);
  16348. } else {
  16349. wolfssl_pending_sni().clear();
  16350. }
  16351. return 0; // Continue regardless
  16352. }
  16353. // wolfSSL verify callback wrapper
  16354. inline int wolfssl_verify_callback(int preverify_ok,
  16355. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16356. auto &callback = get_verify_callback();
  16357. if (!callback) { return preverify_ok; }
  16358. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16359. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16360. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16361. // Get the WOLFSSL object from the X509_STORE_CTX
  16362. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16363. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16364. VerifyContext verify_ctx;
  16365. verify_ctx.session = static_cast<session_t>(ssl);
  16366. verify_ctx.cert = static_cast<cert_t>(cert);
  16367. verify_ctx.depth = depth;
  16368. verify_ctx.preverify_ok = (preverify_ok != 0);
  16369. verify_ctx.error_code = static_cast<long>(err);
  16370. if (err != 0) {
  16371. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16372. } else {
  16373. verify_ctx.error_string = nullptr;
  16374. }
  16375. bool accepted = callback(verify_ctx);
  16376. return accepted ? 1 : 0;
  16377. }
  16378. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16379. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16380. wolfSSL_CTX_set_default_passwd_cb(
  16381. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16382. auto *pwd = static_cast<const char *>(userdata);
  16383. if (!pwd) return 0;
  16384. auto len = static_cast<int>(strlen(pwd));
  16385. if (len > size) len = size;
  16386. memcpy(buf, pwd, static_cast<size_t>(len));
  16387. return len;
  16388. });
  16389. }
  16390. } // namespace impl
  16391. inline ctx_t create_client_context() {
  16392. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16393. if (!ctx) { return nullptr; }
  16394. ctx->is_server = false;
  16395. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16396. if (!method) {
  16397. delete ctx;
  16398. return nullptr;
  16399. }
  16400. ctx->ctx = wolfSSL_CTX_new(method);
  16401. if (!ctx->ctx) {
  16402. delete ctx;
  16403. return nullptr;
  16404. }
  16405. // Default: verify peer certificate
  16406. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16407. return static_cast<ctx_t>(ctx);
  16408. }
  16409. inline ctx_t create_server_context() {
  16410. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16411. if (!ctx) { return nullptr; }
  16412. ctx->is_server = true;
  16413. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16414. if (!method) {
  16415. delete ctx;
  16416. return nullptr;
  16417. }
  16418. ctx->ctx = wolfSSL_CTX_new(method);
  16419. if (!ctx->ctx) {
  16420. delete ctx;
  16421. return nullptr;
  16422. }
  16423. // Default: don't verify client
  16424. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16425. // Enable SNI on server
  16426. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16427. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16428. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16429. return static_cast<ctx_t>(ctx);
  16430. }
  16431. inline void free_context(ctx_t ctx) {
  16432. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16433. }
  16434. inline bool set_min_version(ctx_t ctx, Version version) {
  16435. if (!ctx) { return false; }
  16436. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16437. int min_ver = WOLFSSL_TLSV1_2;
  16438. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16439. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16440. }
  16441. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16442. if (!ctx || !pem) { return false; }
  16443. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16444. int ret = wolfSSL_CTX_load_verify_buffer(
  16445. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16446. static_cast<long>(len), SSL_FILETYPE_PEM);
  16447. if (ret != SSL_SUCCESS) {
  16448. impl::wolfssl_last_error() =
  16449. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16450. return false;
  16451. }
  16452. wctx->ca_pem_data_.append(pem, len);
  16453. return true;
  16454. }
  16455. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16456. if (!ctx || !file_path) { return false; }
  16457. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16458. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16459. if (ret != SSL_SUCCESS) {
  16460. impl::wolfssl_last_error() =
  16461. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16462. return false;
  16463. }
  16464. return true;
  16465. }
  16466. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16467. if (!ctx || !dir_path) { return false; }
  16468. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16469. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16470. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16471. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16472. // immediately. Return true even on failure since the CA file may have
  16473. // already been loaded, matching OpenSSL's lenient behavior.
  16474. (void)ret;
  16475. return true;
  16476. }
  16477. inline bool load_system_certs(ctx_t ctx) {
  16478. if (!ctx) { return false; }
  16479. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16480. bool loaded = false;
  16481. #ifdef _WIN32
  16482. loaded = impl::enumerate_windows_system_certs(
  16483. [&](const unsigned char *data, size_t len) {
  16484. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16485. static_cast<long>(len),
  16486. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16487. });
  16488. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16489. loaded = impl::enumerate_macos_keychain_certs(
  16490. [&](const unsigned char *data, size_t len) {
  16491. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16492. static_cast<long>(len),
  16493. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16494. });
  16495. #else
  16496. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16497. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16498. SSL_SUCCESS) {
  16499. loaded = true;
  16500. break;
  16501. }
  16502. }
  16503. if (!loaded) {
  16504. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16505. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16506. SSL_SUCCESS) {
  16507. loaded = true;
  16508. break;
  16509. }
  16510. }
  16511. }
  16512. #endif
  16513. return loaded;
  16514. }
  16515. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16516. const char *password) {
  16517. if (!ctx || !cert || !key) { return false; }
  16518. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16519. // Load certificate
  16520. int ret = wolfSSL_CTX_use_certificate_buffer(
  16521. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16522. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16523. if (ret != SSL_SUCCESS) {
  16524. impl::wolfssl_last_error() =
  16525. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16526. return false;
  16527. }
  16528. // Set password callback if password is provided
  16529. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16530. // Load private key
  16531. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16532. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16533. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16534. if (ret != SSL_SUCCESS) {
  16535. impl::wolfssl_last_error() =
  16536. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16537. return false;
  16538. }
  16539. // Verify that the certificate and private key match
  16540. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16541. }
  16542. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16543. const char *key_path, const char *password) {
  16544. if (!ctx || !cert_path || !key_path) { return false; }
  16545. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16546. // Load certificate file
  16547. int ret =
  16548. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16549. if (ret != SSL_SUCCESS) {
  16550. impl::wolfssl_last_error() =
  16551. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16552. return false;
  16553. }
  16554. // Set password callback if password is provided
  16555. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16556. // Load private key file
  16557. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16558. if (ret != SSL_SUCCESS) {
  16559. impl::wolfssl_last_error() =
  16560. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16561. return false;
  16562. }
  16563. // Verify that the certificate and private key match
  16564. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16565. }
  16566. inline void set_verify_client(ctx_t ctx, bool require) {
  16567. if (!ctx) { return; }
  16568. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16569. wctx->verify_client = require;
  16570. if (require) {
  16571. wolfSSL_CTX_set_verify(
  16572. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16573. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16574. } else {
  16575. if (wctx->has_verify_callback) {
  16576. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16577. impl::wolfssl_verify_callback);
  16578. } else {
  16579. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16580. }
  16581. }
  16582. }
  16583. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16584. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16585. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16586. auto session = new (std::nothrow) impl::WolfSSLSession();
  16587. if (!session) { return nullptr; }
  16588. session->sock = sock;
  16589. session->ssl = wolfSSL_new(wctx->ctx);
  16590. if (!session->ssl) {
  16591. impl::wolfssl_last_error() =
  16592. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16593. delete session;
  16594. return nullptr;
  16595. }
  16596. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16597. return static_cast<session_t>(session);
  16598. }
  16599. inline void free_session(session_t session) {
  16600. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16601. }
  16602. inline bool set_sni(session_t session, const char *hostname) {
  16603. if (!session || !hostname) { return false; }
  16604. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16605. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16606. static_cast<word16>(strlen(hostname)));
  16607. if (ret != WOLFSSL_SUCCESS) {
  16608. impl::wolfssl_last_error() =
  16609. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16610. return false;
  16611. }
  16612. // Also set hostname for verification
  16613. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16614. wsession->hostname = hostname;
  16615. return true;
  16616. }
  16617. inline bool set_hostname(session_t session, const char *hostname) {
  16618. // In wolfSSL, set_hostname also sets up hostname verification
  16619. return set_sni(session, hostname);
  16620. }
  16621. inline TlsError connect(session_t session) {
  16622. TlsError err;
  16623. if (!session) {
  16624. err.code = ErrorCode::Fatal;
  16625. return err;
  16626. }
  16627. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16628. int ret = wolfSSL_connect(wsession->ssl);
  16629. if (ret == SSL_SUCCESS) {
  16630. err.code = ErrorCode::Success;
  16631. } else {
  16632. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16633. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16634. err.backend_code = static_cast<uint64_t>(ssl_error);
  16635. impl::wolfssl_last_error() = err.backend_code;
  16636. }
  16637. return err;
  16638. }
  16639. inline TlsError accept(session_t session) {
  16640. TlsError err;
  16641. if (!session) {
  16642. err.code = ErrorCode::Fatal;
  16643. return err;
  16644. }
  16645. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16646. int ret = wolfSSL_accept(wsession->ssl);
  16647. if (ret == SSL_SUCCESS) {
  16648. err.code = ErrorCode::Success;
  16649. // Capture SNI from thread-local storage after successful handshake
  16650. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16651. impl::wolfssl_pending_sni().clear();
  16652. } else {
  16653. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16654. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16655. err.backend_code = static_cast<uint64_t>(ssl_error);
  16656. impl::wolfssl_last_error() = err.backend_code;
  16657. }
  16658. return err;
  16659. }
  16660. inline bool connect_nonblocking(session_t session, socket_t sock,
  16661. time_t timeout_sec, time_t timeout_usec,
  16662. TlsError *err) {
  16663. if (!session) {
  16664. if (err) { err->code = ErrorCode::Fatal; }
  16665. return false;
  16666. }
  16667. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16668. // Set socket to non-blocking mode
  16669. detail::set_nonblocking(sock, true);
  16670. auto cleanup =
  16671. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16672. int ret;
  16673. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16674. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16675. if (ssl_error == SSL_ERROR_WANT_READ) {
  16676. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16677. continue;
  16678. }
  16679. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16680. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16681. continue;
  16682. }
  16683. }
  16684. // Error or timeout
  16685. if (err) {
  16686. err->code =
  16687. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16688. err->backend_code = static_cast<uint64_t>(ssl_error);
  16689. }
  16690. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16691. return false;
  16692. }
  16693. if (err) { err->code = ErrorCode::Success; }
  16694. return true;
  16695. }
  16696. inline bool accept_nonblocking(session_t session, socket_t sock,
  16697. time_t timeout_sec, time_t timeout_usec,
  16698. TlsError *err) {
  16699. if (!session) {
  16700. if (err) { err->code = ErrorCode::Fatal; }
  16701. return false;
  16702. }
  16703. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16704. // Set socket to non-blocking mode
  16705. detail::set_nonblocking(sock, true);
  16706. auto cleanup =
  16707. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16708. int ret;
  16709. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16710. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16711. if (ssl_error == SSL_ERROR_WANT_READ) {
  16712. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16713. continue;
  16714. }
  16715. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16716. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16717. continue;
  16718. }
  16719. }
  16720. // Error or timeout
  16721. if (err) {
  16722. err->code =
  16723. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16724. err->backend_code = static_cast<uint64_t>(ssl_error);
  16725. }
  16726. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16727. return false;
  16728. }
  16729. if (err) { err->code = ErrorCode::Success; }
  16730. // Capture SNI from thread-local storage after successful handshake
  16731. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16732. impl::wolfssl_pending_sni().clear();
  16733. return true;
  16734. }
  16735. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16736. if (!session || !buf) {
  16737. err.code = ErrorCode::Fatal;
  16738. return -1;
  16739. }
  16740. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16741. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16742. if (ret > 0) {
  16743. err.code = ErrorCode::Success;
  16744. return static_cast<ssize_t>(ret);
  16745. }
  16746. if (ret == 0) {
  16747. err.code = ErrorCode::PeerClosed;
  16748. return 0;
  16749. }
  16750. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16751. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16752. err.backend_code = static_cast<uint64_t>(ssl_error);
  16753. impl::wolfssl_last_error() = err.backend_code;
  16754. return -1;
  16755. }
  16756. inline ssize_t write(session_t session, const void *buf, size_t len,
  16757. TlsError &err) {
  16758. if (!session || !buf) {
  16759. err.code = ErrorCode::Fatal;
  16760. return -1;
  16761. }
  16762. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16763. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16764. if (ret > 0) {
  16765. err.code = ErrorCode::Success;
  16766. return static_cast<ssize_t>(ret);
  16767. }
  16768. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16769. // Treat this as an error (return -1) so callers don't spin in a
  16770. // write loop adding zero to the offset.
  16771. if (ret == 0) {
  16772. err.code = ErrorCode::PeerClosed;
  16773. return -1;
  16774. }
  16775. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16776. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16777. err.backend_code = static_cast<uint64_t>(ssl_error);
  16778. impl::wolfssl_last_error() = err.backend_code;
  16779. return -1;
  16780. }
  16781. inline int pending(const_session_t session) {
  16782. if (!session) { return 0; }
  16783. auto wsession =
  16784. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16785. return wolfSSL_pending(wsession->ssl);
  16786. }
  16787. inline void shutdown(session_t session, bool graceful) {
  16788. if (!session) { return; }
  16789. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16790. if (graceful) {
  16791. int ret;
  16792. int attempts = 0;
  16793. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16794. attempts < 3) {
  16795. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16796. if (ssl_error != SSL_ERROR_WANT_READ &&
  16797. ssl_error != SSL_ERROR_WANT_WRITE) {
  16798. break;
  16799. }
  16800. attempts++;
  16801. }
  16802. } else {
  16803. wolfSSL_shutdown(wsession->ssl);
  16804. }
  16805. }
  16806. inline bool is_peer_closed(session_t session, socket_t sock) {
  16807. if (!session || sock == INVALID_SOCKET) { return true; }
  16808. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16809. // Check if there's already decrypted data available
  16810. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16811. // Set socket to non-blocking to avoid blocking on read
  16812. detail::set_nonblocking(sock, true);
  16813. auto cleanup =
  16814. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16815. // Peek 1 byte to check connection status without consuming data
  16816. unsigned char buf;
  16817. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16818. // If we got data or WANT_READ (would block), connection is alive
  16819. if (ret > 0) { return false; }
  16820. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16821. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16822. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16823. ret == 0;
  16824. }
  16825. inline cert_t get_peer_cert(const_session_t session) {
  16826. if (!session) { return nullptr; }
  16827. auto wsession =
  16828. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16829. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16830. return static_cast<cert_t>(cert);
  16831. }
  16832. inline void free_cert(cert_t cert) {
  16833. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16834. }
  16835. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16836. if (!cert || !hostname) { return false; }
  16837. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16838. std::string host_str(hostname);
  16839. // Check if hostname is an IP address (IPv4 or IPv6)
  16840. unsigned char ip_bytes[16];
  16841. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16842. auto is_ip = ip_len > 0;
  16843. // Check Subject Alternative Names
  16844. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16845. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16846. if (san_names) {
  16847. int san_count = wolfSSL_sk_num(san_names);
  16848. for (int i = 0; i < san_count; i++) {
  16849. auto *names =
  16850. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16851. if (!names) continue;
  16852. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16853. // DNS name
  16854. unsigned char *dns_name = nullptr;
  16855. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16856. if (dns_name && dns_len > 0) {
  16857. std::string san_name(reinterpret_cast<char *>(dns_name),
  16858. static_cast<size_t>(dns_len));
  16859. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16860. if (detail::match_hostname(san_name, host_str)) {
  16861. wolfSSL_sk_free(san_names);
  16862. return true;
  16863. }
  16864. }
  16865. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16866. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16867. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16868. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16869. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16870. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16871. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16872. wolfSSL_sk_free(san_names);
  16873. return true;
  16874. }
  16875. }
  16876. }
  16877. wolfSSL_sk_free(san_names);
  16878. }
  16879. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16880. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16881. // the OpenSSL backend's X509_check_ip behaves the same way).
  16882. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16883. if (subject) {
  16884. char cn[256] = {};
  16885. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16886. sizeof(cn));
  16887. if (cn_len > 0) {
  16888. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16889. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16890. }
  16891. }
  16892. return false;
  16893. }
  16894. inline uint64_t hostname_mismatch_code() {
  16895. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16896. }
  16897. inline long get_verify_result(const_session_t session) {
  16898. if (!session) { return -1; }
  16899. auto wsession =
  16900. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16901. long result = wolfSSL_get_verify_result(wsession->ssl);
  16902. return result;
  16903. }
  16904. inline std::string get_cert_subject_cn(cert_t cert) {
  16905. if (!cert) return "";
  16906. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16907. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16908. if (!subject) return "";
  16909. char cn[256] = {};
  16910. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16911. sizeof(cn));
  16912. if (cn_len <= 0) return "";
  16913. return std::string(cn, static_cast<size_t>(cn_len));
  16914. }
  16915. inline std::string get_cert_issuer_name(cert_t cert) {
  16916. if (!cert) return "";
  16917. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16918. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16919. if (!issuer) return "";
  16920. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16921. if (!name_str) return "";
  16922. std::string result(name_str);
  16923. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16924. return result;
  16925. }
  16926. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16927. sans.clear();
  16928. if (!cert) return false;
  16929. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16930. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16931. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16932. if (!san_names) return true; // No SANs is not an error
  16933. int count = wolfSSL_sk_num(san_names);
  16934. for (int i = 0; i < count; i++) {
  16935. auto *name =
  16936. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16937. if (!name) continue;
  16938. SanEntry entry;
  16939. switch (name->type) {
  16940. case WOLFSSL_GEN_DNS: {
  16941. entry.type = SanType::DNS;
  16942. unsigned char *dns_name = nullptr;
  16943. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16944. if (dns_name && dns_len > 0) {
  16945. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16946. static_cast<size_t>(dns_len));
  16947. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16948. }
  16949. break;
  16950. }
  16951. case WOLFSSL_GEN_IPADD: {
  16952. entry.type = SanType::IP;
  16953. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16954. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16955. if (ip_data && ip_len == 4) {
  16956. char buf[16];
  16957. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16958. ip_data[2], ip_data[3]);
  16959. entry.value = buf;
  16960. } else if (ip_data && ip_len == 16) {
  16961. char buf[64];
  16962. snprintf(buf, sizeof(buf),
  16963. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16964. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16965. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16966. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16967. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16968. ip_data[14], ip_data[15]);
  16969. entry.value = buf;
  16970. }
  16971. break;
  16972. }
  16973. case WOLFSSL_GEN_EMAIL:
  16974. entry.type = SanType::EMAIL;
  16975. {
  16976. unsigned char *email = nullptr;
  16977. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16978. if (email && email_len > 0) {
  16979. entry.value = std::string(reinterpret_cast<char *>(email),
  16980. static_cast<size_t>(email_len));
  16981. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16982. }
  16983. }
  16984. break;
  16985. case WOLFSSL_GEN_URI:
  16986. entry.type = SanType::URI;
  16987. {
  16988. unsigned char *uri = nullptr;
  16989. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16990. &uri, name->d.uniformResourceIdentifier);
  16991. if (uri && uri_len > 0) {
  16992. entry.value = std::string(reinterpret_cast<char *>(uri),
  16993. static_cast<size_t>(uri_len));
  16994. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16995. }
  16996. }
  16997. break;
  16998. default: entry.type = SanType::OTHER; break;
  16999. }
  17000. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17001. }
  17002. wolfSSL_sk_free(san_names);
  17003. return true;
  17004. }
  17005. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17006. time_t &not_after) {
  17007. if (!cert) return false;
  17008. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17009. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  17010. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  17011. if (!nb || !na) return false;
  17012. // wolfSSL_ASN1_TIME_to_tm is available
  17013. struct tm tm_nb = {}, tm_na = {};
  17014. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  17015. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  17016. #ifdef _WIN32
  17017. not_before = _mkgmtime(&tm_nb);
  17018. not_after = _mkgmtime(&tm_na);
  17019. #else
  17020. not_before = timegm(&tm_nb);
  17021. not_after = timegm(&tm_na);
  17022. #endif
  17023. return true;
  17024. }
  17025. inline std::string get_cert_serial(cert_t cert) {
  17026. if (!cert) return "";
  17027. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17028. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  17029. if (!serial_asn1) return "";
  17030. // Get the serial number data
  17031. int len = serial_asn1->length;
  17032. unsigned char *data = serial_asn1->data;
  17033. if (!data || len <= 0) return "";
  17034. std::string result;
  17035. result.reserve(static_cast<size_t>(len) * 2);
  17036. for (int i = 0; i < len; i++) {
  17037. char hex[3];
  17038. snprintf(hex, sizeof(hex), "%02X", data[i]);
  17039. result += hex;
  17040. }
  17041. return result;
  17042. }
  17043. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17044. if (!cert) return false;
  17045. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17046. int der_len = 0;
  17047. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17048. if (!der_data || der_len <= 0) return false;
  17049. der.assign(der_data, der_data + der_len);
  17050. return true;
  17051. }
  17052. inline const char *get_sni(const_session_t session) {
  17053. if (!session) return nullptr;
  17054. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17055. // For server: return SNI received from client during handshake
  17056. if (!wsession->sni_hostname.empty()) {
  17057. return wsession->sni_hostname.c_str();
  17058. }
  17059. // For client: return the hostname set via set_sni
  17060. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17061. return nullptr;
  17062. }
  17063. inline uint64_t peek_error() {
  17064. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17065. }
  17066. inline uint64_t get_error() {
  17067. uint64_t err = impl::wolfssl_last_error();
  17068. impl::wolfssl_last_error() = 0;
  17069. return err;
  17070. }
  17071. inline std::string error_string(uint64_t code) {
  17072. char buf[256];
  17073. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17074. return std::string(buf);
  17075. }
  17076. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17077. if (!pem || len == 0) { return nullptr; }
  17078. // Validate by attempting to load into a temporary ctx
  17079. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17080. if (!tmp_ctx) { return nullptr; }
  17081. int ret = wolfSSL_CTX_load_verify_buffer(
  17082. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17083. static_cast<long>(len), SSL_FILETYPE_PEM);
  17084. wolfSSL_CTX_free(tmp_ctx);
  17085. if (ret != SSL_SUCCESS) { return nullptr; }
  17086. return static_cast<ca_store_t>(
  17087. new impl::WolfSSLCAStore{std::string(pem, len)});
  17088. }
  17089. inline void free_ca_store(ca_store_t store) {
  17090. delete static_cast<impl::WolfSSLCAStore *>(store);
  17091. }
  17092. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17093. if (!ctx || !store) { return false; }
  17094. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17095. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17096. int ret = wolfSSL_CTX_load_verify_buffer(
  17097. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17098. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17099. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17100. // This function takes ownership of the store; the PEM data was copied into
  17101. // the context, so release the source
  17102. free_ca_store(store);
  17103. return ret == SSL_SUCCESS;
  17104. }
  17105. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17106. certs.clear();
  17107. if (!ctx) { return 0; }
  17108. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17109. if (wctx->ca_pem_data_.empty()) { return 0; }
  17110. const std::string &pem = wctx->ca_pem_data_;
  17111. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17112. const std::string end_marker = "-----END CERTIFICATE-----";
  17113. size_t pos = 0;
  17114. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17115. size_t end_pos = pem.find(end_marker, pos);
  17116. if (end_pos == std::string::npos) { break; }
  17117. end_pos += end_marker.size();
  17118. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17119. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17120. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17121. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17122. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17123. pos = end_pos;
  17124. }
  17125. return certs.size();
  17126. }
  17127. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17128. std::vector<std::string> names;
  17129. if (!ctx) { return names; }
  17130. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17131. if (wctx->ca_pem_data_.empty()) { return names; }
  17132. const std::string &pem = wctx->ca_pem_data_;
  17133. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17134. const std::string end_marker = "-----END CERTIFICATE-----";
  17135. size_t pos = 0;
  17136. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17137. size_t end_pos = pem.find(end_marker, pos);
  17138. if (end_pos == std::string::npos) { break; }
  17139. end_pos += end_marker.size();
  17140. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17141. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17142. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17143. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17144. if (x509) {
  17145. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17146. if (subject) {
  17147. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17148. if (name_str) {
  17149. names.push_back(name_str);
  17150. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17151. }
  17152. }
  17153. wolfSSL_X509_free(x509);
  17154. }
  17155. pos = end_pos;
  17156. }
  17157. return names;
  17158. }
  17159. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17160. const char *key_pem, const char *password) {
  17161. if (!ctx || !cert_pem || !key_pem) { return false; }
  17162. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17163. // Load new certificate
  17164. int ret = wolfSSL_CTX_use_certificate_buffer(
  17165. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17166. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17167. if (ret != SSL_SUCCESS) {
  17168. impl::wolfssl_last_error() =
  17169. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17170. return false;
  17171. }
  17172. // Set password if provided
  17173. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17174. // Load new private key
  17175. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17176. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17177. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17178. if (ret != SSL_SUCCESS) {
  17179. impl::wolfssl_last_error() =
  17180. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17181. return false;
  17182. }
  17183. return true;
  17184. }
  17185. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17186. if (!ctx || !ca_pem) { return false; }
  17187. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17188. int ret = wolfSSL_CTX_load_verify_buffer(
  17189. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17190. static_cast<long>(strlen(ca_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 set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17199. if (!ctx) { return false; }
  17200. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17201. impl::get_verify_callback() = std::move(callback);
  17202. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17203. if (wctx->has_verify_callback) {
  17204. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17205. impl::wolfssl_verify_callback);
  17206. } else {
  17207. wolfSSL_CTX_set_verify(
  17208. wctx->ctx,
  17209. wctx->verify_client
  17210. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17211. : SSL_VERIFY_NONE,
  17212. nullptr);
  17213. }
  17214. return true;
  17215. }
  17216. inline long get_verify_error(const_session_t session) {
  17217. if (!session) { return -1; }
  17218. auto *wsession =
  17219. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17220. return wolfSSL_get_verify_result(wsession->ssl);
  17221. }
  17222. inline std::string verify_error_string(long error_code) {
  17223. if (error_code == 0) { return ""; }
  17224. const char *str =
  17225. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17226. return str ? std::string(str) : std::string();
  17227. }
  17228. } // namespace tls
  17229. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17230. // WebSocket implementation
  17231. namespace ws {
  17232. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17233. bool fin) {
  17234. std::lock_guard<std::mutex> lock(write_mutex_);
  17235. if (closed_) { return false; }
  17236. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17237. }
  17238. inline ReadResult WebSocket::read(std::string &msg) {
  17239. while (!closed_) {
  17240. Opcode opcode;
  17241. std::string payload;
  17242. bool fin;
  17243. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17244. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17245. closed_ = true;
  17246. return Fail;
  17247. }
  17248. switch (opcode) {
  17249. case Opcode::Ping: {
  17250. std::lock_guard<std::mutex> lock(write_mutex_);
  17251. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17252. payload.size(), true, !is_server_);
  17253. continue;
  17254. }
  17255. case Opcode::Pong: {
  17256. std::lock_guard<std::mutex> lock(ping_mutex_);
  17257. unacked_pings_ = 0;
  17258. continue;
  17259. }
  17260. case Opcode::Close: {
  17261. if (!closed_.exchange(true)) {
  17262. // Echo close frame back
  17263. std::lock_guard<std::mutex> lock(write_mutex_);
  17264. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17265. payload.size(), true, !is_server_);
  17266. }
  17267. return Fail;
  17268. }
  17269. case Opcode::Text:
  17270. case Opcode::Binary: {
  17271. auto result = opcode == Opcode::Text ? Text : Binary;
  17272. msg = std::move(payload);
  17273. // Handle fragmentation
  17274. if (!fin) {
  17275. while (true) {
  17276. Opcode cont_opcode;
  17277. std::string cont_payload;
  17278. bool cont_fin;
  17279. if (!impl::read_websocket_frame(
  17280. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17281. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17282. closed_ = true;
  17283. return Fail;
  17284. }
  17285. if (cont_opcode == Opcode::Ping) {
  17286. std::lock_guard<std::mutex> lock(write_mutex_);
  17287. detail::write_websocket_frame(
  17288. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17289. true, !is_server_);
  17290. continue;
  17291. }
  17292. if (cont_opcode == Opcode::Pong) {
  17293. std::lock_guard<std::mutex> lock(ping_mutex_);
  17294. unacked_pings_ = 0;
  17295. continue;
  17296. }
  17297. if (cont_opcode == Opcode::Close) {
  17298. if (!closed_.exchange(true)) {
  17299. std::lock_guard<std::mutex> lock(write_mutex_);
  17300. detail::write_websocket_frame(
  17301. strm_, Opcode::Close, cont_payload.data(),
  17302. cont_payload.size(), true, !is_server_);
  17303. }
  17304. return Fail;
  17305. }
  17306. // RFC 6455: continuation frames must use opcode 0x0
  17307. if (cont_opcode != Opcode::Continuation) {
  17308. closed_ = true;
  17309. return Fail;
  17310. }
  17311. msg += cont_payload;
  17312. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17313. closed_ = true;
  17314. return Fail;
  17315. }
  17316. if (cont_fin) { break; }
  17317. }
  17318. }
  17319. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17320. if (result == Text && !impl::is_valid_utf8(msg)) {
  17321. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17322. return Fail;
  17323. }
  17324. return result;
  17325. }
  17326. default: closed_ = true; return Fail;
  17327. }
  17328. }
  17329. return Fail;
  17330. }
  17331. inline bool WebSocket::send(const std::string &data) {
  17332. return send_frame(Opcode::Text, data.data(), data.size());
  17333. }
  17334. inline bool WebSocket::send(const char *data, size_t len) {
  17335. return send_frame(Opcode::Binary, data, len);
  17336. }
  17337. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17338. if (closed_.exchange(true)) { return; }
  17339. ping_cv_.notify_all();
  17340. std::string payload;
  17341. auto code = static_cast<uint16_t>(status);
  17342. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17343. payload.push_back(static_cast<char>(code & 0xFF));
  17344. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17345. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17346. payload += reason.substr(0, 123);
  17347. {
  17348. std::lock_guard<std::mutex> lock(write_mutex_);
  17349. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17350. payload.size(), true, !is_server_);
  17351. }
  17352. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17353. // Close response before closing the TCP connection. Use a short timeout to
  17354. // avoid hanging if the peer doesn't respond.
  17355. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17356. Opcode op;
  17357. std::string resp;
  17358. bool fin;
  17359. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17360. if (op == Opcode::Close) { break; }
  17361. }
  17362. }
  17363. inline WebSocket::~WebSocket() {
  17364. {
  17365. std::lock_guard<std::mutex> lock(ping_mutex_);
  17366. closed_ = true;
  17367. }
  17368. ping_cv_.notify_all();
  17369. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17370. }
  17371. inline void WebSocket::start_heartbeat() {
  17372. if (ping_interval_sec_ == 0) { return; }
  17373. ping_thread_ = std::thread([this]() {
  17374. std::unique_lock<std::mutex> lock(ping_mutex_);
  17375. while (!closed_) {
  17376. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17377. if (closed_) { break; }
  17378. // If the peer has failed to respond to the previous pings, give up.
  17379. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17380. // opt-in liveness check controlled by max_missed_pongs_.
  17381. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17382. lock.unlock();
  17383. close(CloseStatus::GoingAway, "pong timeout");
  17384. return;
  17385. }
  17386. lock.unlock();
  17387. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17388. lock.lock();
  17389. closed_ = true;
  17390. break;
  17391. }
  17392. lock.lock();
  17393. unacked_pings_++;
  17394. }
  17395. });
  17396. }
  17397. inline const Request &WebSocket::request() const { return req_; }
  17398. inline bool WebSocket::is_open() const { return !closed_; }
  17399. // WebSocketClient implementation
  17400. inline WebSocketClient::WebSocketClient(
  17401. const std::string &scheme_host_port_path, const Headers &headers)
  17402. : headers_(headers) {
  17403. detail::UrlComponents uc;
  17404. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17405. !uc.host.empty() && !uc.path.empty()) {
  17406. auto &scheme = uc.scheme;
  17407. #ifdef CPPHTTPLIB_SSL_ENABLED
  17408. if (scheme != "ws" && scheme != "wss") {
  17409. #else
  17410. if (scheme != "ws") {
  17411. #endif
  17412. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17413. std::string msg = "'" + scheme + "' scheme is not supported.";
  17414. throw std::invalid_argument(msg);
  17415. #endif
  17416. return;
  17417. }
  17418. auto is_ssl = scheme == "wss";
  17419. host_ = std::move(uc.host);
  17420. port_ = is_ssl ? 443 : 80;
  17421. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17422. path_ = std::move(uc.path);
  17423. if (!uc.query.empty()) { path_ += uc.query; }
  17424. #ifdef CPPHTTPLIB_SSL_ENABLED
  17425. is_ssl_ = is_ssl;
  17426. if (is_ssl_) {
  17427. // The context lives as long as the client so that CA configuration
  17428. // survives reconnects; sessions are created per connection.
  17429. tls_ctx_ = tls::create_client_context();
  17430. if (!tls_ctx_) { return; }
  17431. }
  17432. #else
  17433. if (is_ssl) { return; }
  17434. #endif
  17435. is_valid_ = true;
  17436. }
  17437. }
  17438. inline WebSocketClient::~WebSocketClient() {
  17439. shutdown_and_close();
  17440. #ifdef CPPHTTPLIB_SSL_ENABLED
  17441. if (tls_ctx_) {
  17442. tls::free_context(tls_ctx_);
  17443. tls_ctx_ = nullptr;
  17444. }
  17445. #endif
  17446. }
  17447. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17448. inline void WebSocketClient::shutdown_and_close() {
  17449. // Send the close frame while the TLS session is still alive: ws_ holds an
  17450. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  17451. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  17452. if (ws_ && ws_->is_open()) { ws_->close(); }
  17453. ws_.reset();
  17454. #ifdef CPPHTTPLIB_SSL_ENABLED
  17455. if (is_ssl_) {
  17456. if (tls_session_) {
  17457. tls::shutdown(tls_session_, true);
  17458. tls::free_session(tls_session_);
  17459. tls_session_ = nullptr;
  17460. }
  17461. }
  17462. #endif
  17463. if (sock_ != INVALID_SOCKET) {
  17464. detail::shutdown_socket(sock_);
  17465. detail::close_socket(sock_);
  17466. sock_ = INVALID_SOCKET;
  17467. }
  17468. }
  17469. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17470. #ifdef CPPHTTPLIB_SSL_ENABLED
  17471. if (is_ssl_) {
  17472. if (server_certificate_verification_ && !certs_loaded_) {
  17473. uint64_t backend_error = 0;
  17474. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17475. custom_ca_loaded_, system_ca_mode_,
  17476. backend_error);
  17477. certs_loaded_ = true;
  17478. }
  17479. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17480. server_certificate_verification_,
  17481. read_timeout_sec_,
  17482. read_timeout_usec_)) {
  17483. return false;
  17484. }
  17485. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17486. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17487. write_timeout_sec_, write_timeout_usec_));
  17488. return true;
  17489. }
  17490. #endif
  17491. strm = std::unique_ptr<Stream>(
  17492. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17493. write_timeout_sec_, write_timeout_usec_));
  17494. return true;
  17495. }
  17496. inline bool WebSocketClient::connect() {
  17497. if (!is_valid_) { return false; }
  17498. shutdown_and_close();
  17499. // Check is custom IP specified for host_
  17500. std::string ip;
  17501. auto it = addr_map_.find(host_);
  17502. if (it != addr_map_.end()) { ip = it->second; }
  17503. Error error;
  17504. sock_ = detail::create_client_socket(
  17505. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17506. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17507. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17508. write_timeout_usec_, interface_, error);
  17509. if (sock_ == INVALID_SOCKET) { return false; }
  17510. std::unique_ptr<Stream> strm;
  17511. if (!create_stream(strm)) {
  17512. shutdown_and_close();
  17513. return false;
  17514. }
  17515. #ifdef CPPHTTPLIB_SSL_ENABLED
  17516. auto is_ssl = is_ssl_;
  17517. #else
  17518. auto is_ssl = false;
  17519. #endif
  17520. std::string selected_subprotocol;
  17521. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17522. headers_, selected_subprotocol)) {
  17523. shutdown_and_close();
  17524. return false;
  17525. }
  17526. subprotocol_ = std::move(selected_subprotocol);
  17527. Request req;
  17528. req.method = "GET";
  17529. req.path = path_;
  17530. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17531. websocket_ping_interval_sec_,
  17532. websocket_max_missed_pongs_));
  17533. return true;
  17534. }
  17535. inline ReadResult WebSocketClient::read(std::string &msg) {
  17536. if (!ws_) { return Fail; }
  17537. return ws_->read(msg);
  17538. }
  17539. inline bool WebSocketClient::send(const std::string &data) {
  17540. if (!ws_) { return false; }
  17541. return ws_->send(data);
  17542. }
  17543. inline bool WebSocketClient::send(const char *data, size_t len) {
  17544. if (!ws_) { return false; }
  17545. return ws_->send(data, len);
  17546. }
  17547. inline void WebSocketClient::close(CloseStatus status,
  17548. const std::string &reason) {
  17549. if (ws_) { ws_->close(status, reason); }
  17550. }
  17551. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17552. inline const std::string &WebSocketClient::subprotocol() const {
  17553. return subprotocol_;
  17554. }
  17555. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17556. read_timeout_sec_ = sec;
  17557. read_timeout_usec_ = usec;
  17558. }
  17559. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17560. write_timeout_sec_ = sec;
  17561. write_timeout_usec_ = usec;
  17562. }
  17563. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17564. websocket_ping_interval_sec_ = sec;
  17565. }
  17566. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17567. websocket_max_missed_pongs_ = count;
  17568. }
  17569. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17570. inline void WebSocketClient::set_address_family(int family) {
  17571. address_family_ = family;
  17572. }
  17573. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17574. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17575. socket_options_ = std::move(socket_options);
  17576. }
  17577. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17578. connection_timeout_sec_ = sec;
  17579. connection_timeout_usec_ = usec;
  17580. }
  17581. inline void WebSocketClient::set_interface(const std::string &intf) {
  17582. interface_ = intf;
  17583. }
  17584. inline void WebSocketClient::set_hostname_addr_map(
  17585. std::map<std::string, std::string> addr_map) {
  17586. addr_map_ = std::move(addr_map);
  17587. }
  17588. #ifdef CPPHTTPLIB_SSL_ENABLED
  17589. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17590. ca_cert_file_path_ = path;
  17591. }
  17592. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17593. if (store && tls_ctx_) {
  17594. // set_ca_store takes ownership of store
  17595. tls::set_ca_store(tls_ctx_, store);
  17596. custom_ca_loaded_ = true;
  17597. } else if (store) {
  17598. tls::free_ca_store(store);
  17599. }
  17600. }
  17601. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17602. std::size_t size) {
  17603. if (tls_ctx_ && ca_cert && size > 0) {
  17604. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17605. custom_ca_loaded_ = true;
  17606. }
  17607. }
  17608. inline void
  17609. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17610. server_certificate_verification_ = enabled;
  17611. }
  17612. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17613. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17614. }
  17615. #endif // CPPHTTPLIB_SSL_ENABLED
  17616. } // namespace ws
  17617. // ----------------------------------------------------------------------------
  17618. } // namespace httplib
  17619. #endif // CPPHTTPLIB_HTTPLIB_H