httplib.h 683 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689
  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.48.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003000"
  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 <cctype>
  246. #include <chrono>
  247. #include <climits>
  248. #include <condition_variable>
  249. #include <cstdlib>
  250. #include <cstring>
  251. #include <errno.h>
  252. #include <exception>
  253. #include <fcntl.h>
  254. #include <fstream>
  255. #include <functional>
  256. #include <iomanip>
  257. #include <iostream>
  258. #include <list>
  259. #include <map>
  260. #include <memory>
  261. #include <mutex>
  262. #include <random>
  263. #include <regex>
  264. #include <set>
  265. #include <sstream>
  266. #include <string>
  267. #include <sys/stat.h>
  268. #include <system_error>
  269. #include <thread>
  270. #include <unordered_map>
  271. #include <unordered_set>
  272. #include <utility>
  273. // On macOS with a TLS backend, enable Keychain root certificates by default
  274. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  275. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  276. // only; on those platforms the user must provide a CA bundle explicitly.
  277. #if defined(__APPLE__) && defined(__clang__) && \
  278. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  279. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  280. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  281. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  282. #if TARGET_OS_OSX
  283. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  285. #endif
  286. #endif
  287. #endif
  288. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  289. defined(__APPLE__) && !TARGET_OS_OSX
  290. #error \
  291. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  292. #endif
  293. // On Windows, enable Schannel certificate verification by default
  294. // unless the user explicitly opts out.
  295. #if defined(_WIN32) && \
  296. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  297. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  298. #endif
  299. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  300. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  301. #if TARGET_OS_MAC && defined(__clang__)
  302. #include <CFNetwork/CFHost.h>
  303. #include <CoreFoundation/CoreFoundation.h>
  304. #endif
  305. #endif
  306. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  307. #ifdef _WIN32
  308. #include <wincrypt.h>
  309. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  310. // used
  311. #undef X509_NAME
  312. #undef X509_CERT_PAIR
  313. #undef X509_EXTENSIONS
  314. #undef PKCS7_SIGNER_INFO
  315. #ifdef _MSC_VER
  316. #pragma comment(lib, "crypt32.lib")
  317. #endif
  318. #endif // _WIN32
  319. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  320. #if TARGET_OS_OSX
  321. #include <Security/Security.h>
  322. #endif
  323. #endif
  324. #include <openssl/err.h>
  325. #include <openssl/evp.h>
  326. #include <openssl/ssl.h>
  327. #include <openssl/x509v3.h>
  328. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  329. #include <openssl/applink.c>
  330. #endif
  331. #include <iostream>
  332. #include <sstream>
  333. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  334. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  335. #error Please use OpenSSL or a current version of BoringSSL
  336. #endif
  337. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  338. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  339. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  340. #endif
  341. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  342. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  343. #include <mbedtls/ctr_drbg.h>
  344. #include <mbedtls/entropy.h>
  345. #include <mbedtls/error.h>
  346. #include <mbedtls/md5.h>
  347. #include <mbedtls/net_sockets.h>
  348. #include <mbedtls/oid.h>
  349. #include <mbedtls/pk.h>
  350. #include <mbedtls/sha1.h>
  351. #include <mbedtls/sha256.h>
  352. #include <mbedtls/sha512.h>
  353. #include <mbedtls/ssl.h>
  354. #include <mbedtls/x509_crt.h>
  355. #ifdef _WIN32
  356. #include <wincrypt.h>
  357. #ifdef _MSC_VER
  358. #pragma comment(lib, "crypt32.lib")
  359. #endif
  360. #endif // _WIN32
  361. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  362. #if TARGET_OS_OSX
  363. #include <Security/Security.h>
  364. #endif
  365. #endif
  366. // Mbed TLS 3.x API compatibility
  367. #if MBEDTLS_VERSION_MAJOR >= 3
  368. #define CPPHTTPLIB_MBEDTLS_V3
  369. #endif
  370. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  371. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  372. #include <wolfssl/options.h>
  373. #include <wolfssl/openssl/x509v3.h>
  374. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  375. #ifndef WOLFSSL_GEN_EMAIL
  376. #define WOLFSSL_GEN_EMAIL 1
  377. #endif
  378. #ifndef WOLFSSL_GEN_DNS
  379. #define WOLFSSL_GEN_DNS 2
  380. #endif
  381. #ifndef WOLFSSL_GEN_URI
  382. #define WOLFSSL_GEN_URI 6
  383. #endif
  384. #ifndef WOLFSSL_GEN_IPADD
  385. #define WOLFSSL_GEN_IPADD 7
  386. #endif
  387. #include <wolfssl/ssl.h>
  388. #include <wolfssl/wolfcrypt/hash.h>
  389. #include <wolfssl/wolfcrypt/md5.h>
  390. #include <wolfssl/wolfcrypt/sha256.h>
  391. #include <wolfssl/wolfcrypt/sha512.h>
  392. #ifdef _WIN32
  393. #include <wincrypt.h>
  394. #ifdef _MSC_VER
  395. #pragma comment(lib, "crypt32.lib")
  396. #endif
  397. #endif // _WIN32
  398. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  399. #if TARGET_OS_OSX
  400. #include <Security/Security.h>
  401. #endif
  402. #endif
  403. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  404. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  405. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  406. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  407. #define CPPHTTPLIB_SSL_ENABLED
  408. #endif
  409. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  410. #include <zlib.h>
  411. #endif
  412. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  413. #include <brotli/decode.h>
  414. #include <brotli/encode.h>
  415. #endif
  416. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  417. #include <zstd.h>
  418. #endif
  419. /*
  420. * Declaration
  421. */
  422. namespace httplib {
  423. namespace ws {
  424. class WebSocket;
  425. } // namespace ws
  426. namespace detail {
  427. /*
  428. * Backport std::make_unique from C++14.
  429. *
  430. * NOTE: This code came up with the following stackoverflow post:
  431. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  432. *
  433. */
  434. template <class T, class... Args>
  435. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  436. make_unique(Args &&...args) {
  437. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  438. }
  439. template <class T>
  440. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  441. make_unique(std::size_t n) {
  442. typedef typename std::remove_extent<T>::type RT;
  443. return std::unique_ptr<T>(new RT[n]);
  444. }
  445. namespace case_ignore {
  446. inline unsigned char to_lower(int c) {
  447. const static unsigned char table[256] = {
  448. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  449. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  450. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  451. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  452. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  453. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  454. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  455. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  456. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  457. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  458. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  459. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  460. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  461. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  462. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  463. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  464. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  465. 255,
  466. };
  467. return table[(unsigned char)(char)c];
  468. }
  469. inline std::string to_lower(const std::string &s) {
  470. std::string result = s;
  471. std::transform(
  472. result.begin(), result.end(), result.begin(),
  473. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  474. return result;
  475. }
  476. inline bool equal(const std::string &a, const std::string &b) {
  477. return a.size() == b.size() &&
  478. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  479. return to_lower(ca) == to_lower(cb);
  480. });
  481. }
  482. struct equal_to {
  483. bool operator()(const std::string &a, const std::string &b) const {
  484. return equal(a, b);
  485. }
  486. };
  487. struct hash {
  488. size_t operator()(const std::string &key) const {
  489. return hash_core(key.data(), key.size(), 0);
  490. }
  491. size_t hash_core(const char *s, size_t l, size_t h) const {
  492. return (l == 0) ? h
  493. : hash_core(s + 1, l - 1,
  494. // Unsets the 6 high bits of h, therefore no
  495. // overflow happens
  496. (((std::numeric_limits<size_t>::max)() >> 6) &
  497. h * 33) ^
  498. static_cast<unsigned char>(to_lower(*s)));
  499. }
  500. };
  501. template <typename T>
  502. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  503. detail::case_ignore::equal_to>;
  504. } // namespace case_ignore
  505. // This is based on
  506. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  507. struct scope_exit {
  508. explicit scope_exit(std::function<void(void)> &&f)
  509. : exit_function(std::move(f)), execute_on_destruction{true} {}
  510. scope_exit(scope_exit &&rhs) noexcept
  511. : exit_function(std::move(rhs.exit_function)),
  512. execute_on_destruction{rhs.execute_on_destruction} {
  513. rhs.release();
  514. }
  515. ~scope_exit() {
  516. if (execute_on_destruction) { this->exit_function(); }
  517. }
  518. void release() { this->execute_on_destruction = false; }
  519. private:
  520. scope_exit(const scope_exit &) = delete;
  521. void operator=(const scope_exit &) = delete;
  522. scope_exit &operator=(scope_exit &&) = delete;
  523. std::function<void(void)> exit_function;
  524. bool execute_on_destruction;
  525. };
  526. // Simple from_chars implementation for integer and double types (C++17
  527. // substitute)
  528. template <typename T> struct from_chars_result {
  529. const char *ptr;
  530. std::errc ec;
  531. };
  532. template <typename T>
  533. inline from_chars_result<T> from_chars(const char *first, const char *last,
  534. T &value, int base = 10) {
  535. value = 0;
  536. const char *p = first;
  537. bool negative = false;
  538. if (p != last && *p == '-') {
  539. negative = true;
  540. ++p;
  541. }
  542. if (p == last) { return {first, std::errc::invalid_argument}; }
  543. T result = 0;
  544. for (; p != last; ++p) {
  545. char c = *p;
  546. int digit = -1;
  547. if ('0' <= c && c <= '9') {
  548. digit = c - '0';
  549. } else if ('a' <= c && c <= 'z') {
  550. digit = c - 'a' + 10;
  551. } else if ('A' <= c && c <= 'Z') {
  552. digit = c - 'A' + 10;
  553. } else {
  554. break;
  555. }
  556. if (digit < 0 || digit >= base) { break; }
  557. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  558. return {p, std::errc::result_out_of_range};
  559. }
  560. result = result * base + digit;
  561. }
  562. if (p == first || (negative && p == first + 1)) {
  563. return {first, std::errc::invalid_argument};
  564. }
  565. value = negative ? -result : result;
  566. return {p, std::errc{}};
  567. }
  568. // from_chars for double (hand-written, locale-independent)
  569. //
  570. // The only double consumed by this library is the HTTP quality value, whose
  571. // grammar is (RFC 9110 12.4.2):
  572. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  573. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  574. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  575. // '.' always the decimal separator (std::strtod would instead read it from the
  576. // global C locale, mis-parsing q-values once an embedder calls
  577. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  578. // the result to [0, 1], so inputs outside that range need not be distinguished
  579. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  580. // cases that exponent and wide-range handling would introduce.
  581. inline from_chars_result<double> from_chars(const char *first, const char *last,
  582. double &value) {
  583. value = 0.0;
  584. const char *p = first;
  585. // Each 1eN is exactly representable, so a single final division by the
  586. // matching entry yields a correctly-rounded result.
  587. static const double powers_of_ten[] = {
  588. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  589. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  590. const int max_frac_digits =
  591. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  592. // Accumulate digits into a 64-bit integer and remember how many were
  593. // fractional. Two independent caps keep this bounded and safe:
  594. // * accumulation saturates before mantissa could overflow uint64_t, and
  595. // * frac_digits is capped at max_frac_digits so it is always a valid index
  596. // into powers_of_ten (without this an input like "0.000...0" would never
  597. // grow mantissa, so the saturation cap alone would not bound it).
  598. // Both caps only drop digits far beyond the precision a q-value needs; any
  599. // value they would change is well outside [0, 1] and rejected by the caller.
  600. uint64_t mantissa = 0;
  601. int frac_digits = 0;
  602. bool seen_digit = false;
  603. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  604. auto accumulate = [&](char c) {
  605. if (mantissa <= limit) {
  606. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  607. return true;
  608. }
  609. return false;
  610. };
  611. for (; p != last && '0' <= *p && *p <= '9'; ++p) {
  612. seen_digit = true;
  613. accumulate(*p);
  614. }
  615. if (p != last && *p == '.') {
  616. ++p;
  617. for (; p != last && '0' <= *p && *p <= '9'; ++p) {
  618. seen_digit = true;
  619. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  620. }
  621. }
  622. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  623. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  624. return {p, std::errc{}};
  625. }
  626. inline bool parse_port(const char *s, size_t len, int &port) {
  627. int val = 0;
  628. auto r = from_chars(s, s + len, val);
  629. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  630. port = val;
  631. return true;
  632. }
  633. inline bool parse_port(const std::string &s, int &port) {
  634. return parse_port(s.data(), s.size(), port);
  635. }
  636. struct UrlComponents {
  637. std::string scheme;
  638. std::string host;
  639. std::string port;
  640. std::string path;
  641. std::string query;
  642. };
  643. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  644. uc = {};
  645. size_t pos = 0;
  646. auto sep = url.find("://");
  647. if (sep != std::string::npos) {
  648. uc.scheme = url.substr(0, sep);
  649. // Scheme must be [a-z]+ only
  650. if (uc.scheme.empty()) { return false; }
  651. for (auto c : uc.scheme) {
  652. if (c < 'a' || c > 'z') { return false; }
  653. }
  654. pos = sep + 3;
  655. } else if (url.compare(0, 2, "//") == 0) {
  656. pos = 2;
  657. }
  658. auto has_authority_prefix = pos > 0;
  659. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  660. url[0] != '?' && url[0] != '#');
  661. if (has_authority) {
  662. if (pos < url.size() && url[pos] == '[') {
  663. auto close = url.find(']', pos);
  664. if (close == std::string::npos) { return false; }
  665. uc.host = url.substr(pos + 1, close - pos - 1);
  666. // IPv6 host must be [a-fA-F0-9:]+ only
  667. if (uc.host.empty()) { return false; }
  668. for (auto c : uc.host) {
  669. if (!((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ||
  670. (c >= '0' && c <= '9') || c == ':')) {
  671. return false;
  672. }
  673. }
  674. pos = close + 1;
  675. } else {
  676. auto end = url.find_first_of(":/?#", pos);
  677. if (end == std::string::npos) { end = url.size(); }
  678. uc.host = url.substr(pos, end - pos);
  679. pos = end;
  680. }
  681. if (pos < url.size() && url[pos] == ':') {
  682. ++pos;
  683. auto end = url.find_first_of("/?#", pos);
  684. if (end == std::string::npos) { end = url.size(); }
  685. uc.port = url.substr(pos, end - pos);
  686. pos = end;
  687. }
  688. // Without :// or //, the entire input must be consumed as host[:port].
  689. // If there is leftover (path, query, etc.), this is not a valid
  690. // host[:port] string — clear and reparse as a plain path.
  691. if (!has_authority_prefix && pos < url.size()) {
  692. uc.host.clear();
  693. uc.port.clear();
  694. pos = 0;
  695. }
  696. }
  697. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  698. auto end = url.find_first_of("?#", pos);
  699. if (end == std::string::npos) { end = url.size(); }
  700. uc.path = url.substr(pos, end - pos);
  701. pos = end;
  702. }
  703. if (pos < url.size() && url[pos] == '?') {
  704. auto end = url.find('#', pos);
  705. if (end == std::string::npos) { end = url.size(); }
  706. uc.query = url.substr(pos, end - pos);
  707. }
  708. return true;
  709. }
  710. } // namespace detail
  711. enum class SSLVerifierResponse {
  712. // no decision has been made, use the built-in certificate verifier
  713. NoDecisionMade,
  714. // connection certificate is verified and accepted
  715. CertificateAccepted,
  716. // connection certificate was processed but is rejected
  717. CertificateRejected
  718. };
  719. // System CA loading policy for SSL clients. Auto (the default) loads system
  720. // CA certs only when no custom CA is configured; enable_system_ca() switches
  721. // to an explicit policy.
  722. enum class SystemCAMode { Auto, Enabled, Disabled };
  723. enum StatusCode {
  724. // Information responses
  725. Continue_100 = 100,
  726. SwitchingProtocol_101 = 101,
  727. Processing_102 = 102,
  728. EarlyHints_103 = 103,
  729. // Successful responses
  730. OK_200 = 200,
  731. Created_201 = 201,
  732. Accepted_202 = 202,
  733. NonAuthoritativeInformation_203 = 203,
  734. NoContent_204 = 204,
  735. ResetContent_205 = 205,
  736. PartialContent_206 = 206,
  737. MultiStatus_207 = 207,
  738. AlreadyReported_208 = 208,
  739. IMUsed_226 = 226,
  740. // Redirection messages
  741. MultipleChoices_300 = 300,
  742. MovedPermanently_301 = 301,
  743. Found_302 = 302,
  744. SeeOther_303 = 303,
  745. NotModified_304 = 304,
  746. UseProxy_305 = 305,
  747. unused_306 = 306,
  748. TemporaryRedirect_307 = 307,
  749. PermanentRedirect_308 = 308,
  750. // Client error responses
  751. BadRequest_400 = 400,
  752. Unauthorized_401 = 401,
  753. PaymentRequired_402 = 402,
  754. Forbidden_403 = 403,
  755. NotFound_404 = 404,
  756. MethodNotAllowed_405 = 405,
  757. NotAcceptable_406 = 406,
  758. ProxyAuthenticationRequired_407 = 407,
  759. RequestTimeout_408 = 408,
  760. Conflict_409 = 409,
  761. Gone_410 = 410,
  762. LengthRequired_411 = 411,
  763. PreconditionFailed_412 = 412,
  764. PayloadTooLarge_413 = 413,
  765. UriTooLong_414 = 414,
  766. UnsupportedMediaType_415 = 415,
  767. RangeNotSatisfiable_416 = 416,
  768. ExpectationFailed_417 = 417,
  769. ImATeapot_418 = 418,
  770. MisdirectedRequest_421 = 421,
  771. UnprocessableContent_422 = 422,
  772. Locked_423 = 423,
  773. FailedDependency_424 = 424,
  774. TooEarly_425 = 425,
  775. UpgradeRequired_426 = 426,
  776. PreconditionRequired_428 = 428,
  777. TooManyRequests_429 = 429,
  778. RequestHeaderFieldsTooLarge_431 = 431,
  779. UnavailableForLegalReasons_451 = 451,
  780. // Server error responses
  781. InternalServerError_500 = 500,
  782. NotImplemented_501 = 501,
  783. BadGateway_502 = 502,
  784. ServiceUnavailable_503 = 503,
  785. GatewayTimeout_504 = 504,
  786. HttpVersionNotSupported_505 = 505,
  787. VariantAlsoNegotiates_506 = 506,
  788. InsufficientStorage_507 = 507,
  789. LoopDetected_508 = 508,
  790. NotExtended_510 = 510,
  791. NetworkAuthenticationRequired_511 = 511,
  792. };
  793. using Headers =
  794. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  795. detail::case_ignore::equal_to>;
  796. using Params = std::multimap<std::string, std::string>;
  797. using Match = std::smatch;
  798. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  799. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  800. /*
  801. * detail: type-erased storage used by UserData.
  802. * ABI-stable regardless of C++ standard — always uses this custom
  803. * implementation instead of std::any.
  804. */
  805. namespace detail {
  806. using any_type_id = const void *;
  807. template <typename T> any_type_id any_typeid() noexcept {
  808. static const char id = 0;
  809. return &id;
  810. }
  811. struct any_storage {
  812. virtual ~any_storage() = default;
  813. virtual std::unique_ptr<any_storage> clone() const = 0;
  814. virtual any_type_id type_id() const noexcept = 0;
  815. };
  816. template <typename T> struct any_value final : any_storage {
  817. T value;
  818. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  819. std::unique_ptr<any_storage> clone() const override {
  820. return std::unique_ptr<any_storage>(new any_value<T>(value));
  821. }
  822. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  823. };
  824. } // namespace detail
  825. class UserData {
  826. public:
  827. UserData() = default;
  828. UserData(UserData &&) noexcept = default;
  829. UserData &operator=(UserData &&) noexcept = default;
  830. UserData(const UserData &o) {
  831. for (const auto &e : o.entries_) {
  832. if (e.second) { entries_[e.first] = e.second->clone(); }
  833. }
  834. }
  835. UserData &operator=(const UserData &o) {
  836. if (this != &o) {
  837. entries_.clear();
  838. for (const auto &e : o.entries_) {
  839. if (e.second) { entries_[e.first] = e.second->clone(); }
  840. }
  841. }
  842. return *this;
  843. }
  844. template <typename T> void set(const std::string &key, T &&value) {
  845. using D = typename std::decay<T>::type;
  846. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  847. }
  848. template <typename T> T *get(const std::string &key) noexcept {
  849. auto it = entries_.find(key);
  850. if (it == entries_.end() || !it->second) { return nullptr; }
  851. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  852. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  853. }
  854. template <typename T> const T *get(const std::string &key) const noexcept {
  855. auto it = entries_.find(key);
  856. if (it == entries_.end() || !it->second) { return nullptr; }
  857. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  858. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  859. }
  860. bool has(const std::string &key) const noexcept {
  861. return entries_.find(key) != entries_.end();
  862. }
  863. void erase(const std::string &key) { entries_.erase(key); }
  864. void clear() noexcept { entries_.clear(); }
  865. private:
  866. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  867. entries_;
  868. };
  869. struct Response;
  870. using ResponseHandler = std::function<bool(const Response &response)>;
  871. struct FormData {
  872. std::string name;
  873. std::string content;
  874. std::string filename;
  875. std::string content_type;
  876. Headers headers;
  877. };
  878. struct FormField {
  879. std::string name;
  880. std::string content;
  881. Headers headers;
  882. };
  883. using FormFields = std::multimap<std::string, FormField>;
  884. using FormFiles = std::multimap<std::string, FormData>;
  885. struct MultipartFormData {
  886. FormFields fields; // Text fields from multipart
  887. FormFiles files; // Files from multipart
  888. // Text field access
  889. std::string get_field(const std::string &key, size_t id = 0) const;
  890. std::vector<std::string> get_fields(const std::string &key) const;
  891. bool has_field(const std::string &key) const;
  892. size_t get_field_count(const std::string &key) const;
  893. // File access
  894. FormData get_file(const std::string &key, size_t id = 0) const;
  895. std::vector<FormData> get_files(const std::string &key) const;
  896. bool has_file(const std::string &key) const;
  897. size_t get_file_count(const std::string &key) const;
  898. };
  899. struct UploadFormData {
  900. std::string name;
  901. std::string content;
  902. std::string filename;
  903. std::string content_type;
  904. };
  905. using UploadFormDataItems = std::vector<UploadFormData>;
  906. class DataSink {
  907. public:
  908. DataSink() : os(&sb_), sb_(*this) {}
  909. DataSink(const DataSink &) = delete;
  910. DataSink &operator=(const DataSink &) = delete;
  911. DataSink(DataSink &&) = delete;
  912. DataSink &operator=(DataSink &&) = delete;
  913. std::function<bool(const char *data, size_t data_len)> write;
  914. std::function<bool()> is_writable;
  915. std::function<void()> done;
  916. std::function<void(const Headers &trailer)> done_with_trailer;
  917. std::ostream os;
  918. private:
  919. class data_sink_streambuf final : public std::streambuf {
  920. public:
  921. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  922. protected:
  923. std::streamsize xsputn(const char *s, std::streamsize n) override {
  924. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  925. return 0;
  926. }
  927. private:
  928. DataSink &sink_;
  929. };
  930. data_sink_streambuf sb_;
  931. };
  932. using ContentProvider =
  933. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  934. using ContentProviderWithoutLength =
  935. std::function<bool(size_t offset, DataSink &sink)>;
  936. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  937. struct FormDataProvider {
  938. std::string name;
  939. ContentProviderWithoutLength provider;
  940. std::string filename;
  941. std::string content_type;
  942. };
  943. using FormDataProviderItems = std::vector<FormDataProvider>;
  944. inline FormDataProvider
  945. make_file_provider(const std::string &name, const std::string &filepath,
  946. const std::string &filename = std::string(),
  947. const std::string &content_type = std::string()) {
  948. FormDataProvider fdp;
  949. fdp.name = name;
  950. fdp.filename = filename.empty() ? filepath : filename;
  951. fdp.content_type = content_type;
  952. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  953. std::ifstream f(filepath, std::ios::binary);
  954. if (!f) { return false; }
  955. if (offset > 0) {
  956. f.seekg(static_cast<std::streamoff>(offset));
  957. if (!f.good()) {
  958. sink.done();
  959. return true;
  960. }
  961. }
  962. char buf[8192];
  963. f.read(buf, sizeof(buf));
  964. auto n = static_cast<size_t>(f.gcount());
  965. if (n > 0) { return sink.write(buf, n); }
  966. sink.done(); // EOF
  967. return true;
  968. };
  969. return fdp;
  970. }
  971. inline std::pair<size_t, ContentProvider>
  972. make_file_body(const std::string &filepath) {
  973. size_t size = 0;
  974. {
  975. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  976. if (!f) { return {0, ContentProvider{}}; }
  977. size = static_cast<size_t>(f.tellg());
  978. }
  979. ContentProvider provider = [filepath](size_t offset, size_t length,
  980. DataSink &sink) -> bool {
  981. std::ifstream f(filepath, std::ios::binary);
  982. if (!f) { return false; }
  983. f.seekg(static_cast<std::streamoff>(offset));
  984. if (!f.good()) { return false; }
  985. char buf[8192];
  986. while (length > 0) {
  987. auto to_read = (std::min)(sizeof(buf), length);
  988. f.read(buf, static_cast<std::streamsize>(to_read));
  989. auto n = static_cast<size_t>(f.gcount());
  990. if (n == 0) { break; }
  991. if (!sink.write(buf, n)) { return false; }
  992. length -= n;
  993. }
  994. return true;
  995. };
  996. return {size, std::move(provider)};
  997. }
  998. using ContentReceiverWithProgress = std::function<bool(
  999. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1000. using ContentReceiver =
  1001. std::function<bool(const char *data, size_t data_length)>;
  1002. using FormDataHeader = std::function<bool(const FormData &file)>;
  1003. class ContentReader {
  1004. public:
  1005. using Reader = std::function<bool(ContentReceiver receiver)>;
  1006. using FormDataReader =
  1007. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1008. ContentReader(Reader reader, FormDataReader multipart_reader)
  1009. : reader_(std::move(reader)),
  1010. formdata_reader_(std::move(multipart_reader)) {}
  1011. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1012. return formdata_reader_(std::move(header), std::move(receiver));
  1013. }
  1014. bool operator()(ContentReceiver receiver) const {
  1015. return reader_(std::move(receiver));
  1016. }
  1017. Reader reader_;
  1018. FormDataReader formdata_reader_;
  1019. };
  1020. using Range = std::pair<ssize_t, ssize_t>;
  1021. using Ranges = std::vector<Range>;
  1022. #ifdef CPPHTTPLIB_SSL_ENABLED
  1023. // TLS abstraction layer - public type definitions and API
  1024. namespace tls {
  1025. // Opaque handles (defined as void* for abstraction)
  1026. using ctx_t = void *;
  1027. using session_t = void *;
  1028. using const_session_t = const void *; // For read-only session access
  1029. using cert_t = void *;
  1030. using ca_store_t = void *;
  1031. // TLS versions
  1032. enum class Version {
  1033. TLS1_2 = 0x0303,
  1034. TLS1_3 = 0x0304,
  1035. };
  1036. // Subject Alternative Names (SAN) entry types
  1037. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1038. // SAN entry structure
  1039. struct SanEntry {
  1040. SanType type;
  1041. std::string value;
  1042. };
  1043. // Verification context for certificate verification callback
  1044. struct VerifyContext {
  1045. session_t session; // TLS session handle
  1046. cert_t cert; // Current certificate being verified
  1047. int depth; // Certificate chain depth (0 = leaf)
  1048. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1049. long error_code; // Backend-specific error code (0 = no error)
  1050. const char *error_string; // Human-readable error description
  1051. // Certificate introspection methods
  1052. std::string subject_cn() const;
  1053. std::string issuer_name() const;
  1054. bool check_hostname(const char *hostname) const;
  1055. std::vector<SanEntry> sans() const;
  1056. bool validity(time_t &not_before, time_t &not_after) const;
  1057. std::string serial() const;
  1058. };
  1059. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1060. // TlsError codes for TLS operations (backend-independent)
  1061. enum class ErrorCode : int {
  1062. Success = 0,
  1063. WantRead, // Non-blocking: need to wait for read
  1064. WantWrite, // Non-blocking: need to wait for write
  1065. PeerClosed, // Peer closed the connection
  1066. Fatal, // Unrecoverable error
  1067. SyscallError, // System call error (check sys_errno)
  1068. CertVerifyFailed, // Certificate verification failed
  1069. HostnameMismatch, // Hostname verification failed
  1070. };
  1071. // TLS error information
  1072. struct TlsError {
  1073. ErrorCode code = ErrorCode::Fatal;
  1074. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1075. int sys_errno = 0; // errno when SyscallError
  1076. // Convert verification error code to human-readable string
  1077. static std::string verify_error_to_string(long error_code);
  1078. };
  1079. // RAII wrapper for peer certificate
  1080. class PeerCert {
  1081. public:
  1082. PeerCert();
  1083. PeerCert(PeerCert &&other) noexcept;
  1084. PeerCert &operator=(PeerCert &&other) noexcept;
  1085. ~PeerCert();
  1086. PeerCert(const PeerCert &) = delete;
  1087. PeerCert &operator=(const PeerCert &) = delete;
  1088. explicit operator bool() const;
  1089. std::string subject_cn() const;
  1090. std::string issuer_name() const;
  1091. bool check_hostname(const char *hostname) const;
  1092. std::vector<SanEntry> sans() const;
  1093. bool validity(time_t &not_before, time_t &not_after) const;
  1094. std::string serial() const;
  1095. private:
  1096. explicit PeerCert(cert_t cert);
  1097. cert_t cert_ = nullptr;
  1098. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1099. };
  1100. // Callback for TLS context setup (used by SSLServer constructor)
  1101. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1102. } // namespace tls
  1103. #endif
  1104. struct Request {
  1105. std::string method;
  1106. std::string path;
  1107. std::string matched_route;
  1108. Params params;
  1109. Headers headers;
  1110. Headers trailers;
  1111. std::string body;
  1112. std::string remote_addr;
  1113. int remote_port = -1;
  1114. std::string local_addr;
  1115. int local_port = -1;
  1116. // for server
  1117. std::string version;
  1118. std::string target;
  1119. MultipartFormData form;
  1120. Ranges ranges;
  1121. Match matches;
  1122. std::unordered_map<std::string, std::string> path_params;
  1123. std::function<bool()> is_connection_closed = []() { return true; };
  1124. // for client
  1125. std::vector<std::string> accept_content_types;
  1126. ResponseHandler response_handler;
  1127. ContentReceiverWithProgress content_receiver;
  1128. DownloadProgress download_progress;
  1129. UploadProgress upload_progress;
  1130. bool has_header(const std::string &key) const;
  1131. std::string get_header_value(const std::string &key, const char *def = "",
  1132. size_t id = 0) const;
  1133. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1134. size_t id = 0) const;
  1135. size_t get_header_value_count(const std::string &key) const;
  1136. void set_header(const std::string &key, const std::string &val);
  1137. bool has_trailer(const std::string &key) const;
  1138. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1139. size_t get_trailer_value_count(const std::string &key) const;
  1140. bool has_param(const std::string &key) const;
  1141. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1142. std::vector<std::string> get_param_values(const std::string &key) const;
  1143. size_t get_param_value_count(const std::string &key) const;
  1144. bool is_multipart_form_data() const;
  1145. // private members...
  1146. bool body_consumed_ = false;
  1147. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1148. size_t content_length_ = 0;
  1149. ContentProvider content_provider_;
  1150. bool is_chunked_content_provider_ = false;
  1151. size_t authorization_count_ = 0;
  1152. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1153. (std::chrono::steady_clock::time_point::min)();
  1154. #ifdef CPPHTTPLIB_SSL_ENABLED
  1155. tls::const_session_t ssl = nullptr;
  1156. tls::PeerCert peer_cert() const;
  1157. std::string sni() const;
  1158. #endif
  1159. };
  1160. struct Response {
  1161. std::string version;
  1162. int status = -1;
  1163. std::string reason;
  1164. Headers headers;
  1165. Headers trailers;
  1166. std::string body;
  1167. std::string location; // Redirect location
  1168. // User-defined context — set by pre-routing/pre-request handlers and read
  1169. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1170. UserData user_data;
  1171. bool has_header(const std::string &key) const;
  1172. std::string get_header_value(const std::string &key, const char *def = "",
  1173. size_t id = 0) const;
  1174. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1175. size_t id = 0) const;
  1176. size_t get_header_value_count(const std::string &key) const;
  1177. void set_header(const std::string &key, const std::string &val);
  1178. bool has_trailer(const std::string &key) const;
  1179. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1180. size_t get_trailer_value_count(const std::string &key) const;
  1181. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1182. void set_content(const char *s, size_t n, const std::string &content_type);
  1183. void set_content(const std::string &s, const std::string &content_type);
  1184. void set_content(std::string &&s, const std::string &content_type);
  1185. void set_content_provider(
  1186. size_t length, const std::string &content_type, ContentProvider provider,
  1187. ContentProviderResourceReleaser resource_releaser = nullptr);
  1188. void set_content_provider(
  1189. const std::string &content_type, ContentProviderWithoutLength provider,
  1190. ContentProviderResourceReleaser resource_releaser = nullptr);
  1191. void set_chunked_content_provider(
  1192. const std::string &content_type, ContentProviderWithoutLength provider,
  1193. ContentProviderResourceReleaser resource_releaser = nullptr);
  1194. void set_file_content(const std::string &path,
  1195. const std::string &content_type);
  1196. void set_file_content(const std::string &path);
  1197. Response() = default;
  1198. Response(const Response &) = default;
  1199. Response &operator=(const Response &) = default;
  1200. Response(Response &&) = default;
  1201. Response &operator=(Response &&) = default;
  1202. ~Response() {
  1203. if (content_provider_resource_releaser_) {
  1204. content_provider_resource_releaser_(content_provider_success_);
  1205. }
  1206. }
  1207. // private members...
  1208. size_t content_length_ = 0;
  1209. ContentProvider content_provider_;
  1210. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1211. bool is_chunked_content_provider_ = false;
  1212. bool content_provider_success_ = false;
  1213. std::string file_content_path_;
  1214. std::string file_content_content_type_;
  1215. };
  1216. enum class Error {
  1217. Success = 0,
  1218. Unknown,
  1219. Connection,
  1220. BindIPAddress,
  1221. Read,
  1222. Write,
  1223. ExceedRedirectCount,
  1224. Canceled,
  1225. SSLConnection,
  1226. SSLLoadingCerts,
  1227. SSLServerVerification,
  1228. SSLServerHostnameVerification,
  1229. UnsupportedMultipartBoundaryChars,
  1230. Compression,
  1231. ConnectionTimeout,
  1232. ProxyConnection,
  1233. ConnectionClosed,
  1234. Timeout,
  1235. ResourceExhaustion,
  1236. TooManyFormDataFiles,
  1237. ExceedMaxPayloadSize,
  1238. ExceedUriMaxLength,
  1239. ExceedMaxSocketDescriptorCount,
  1240. InvalidRequestLine,
  1241. InvalidHTTPMethod,
  1242. InvalidHTTPVersion,
  1243. InvalidHeaders,
  1244. MultipartParsing,
  1245. OpenFile,
  1246. Listen,
  1247. GetSockName,
  1248. UnsupportedAddressFamily,
  1249. HTTPParsing,
  1250. InvalidRangeHeader,
  1251. // For internal use only
  1252. SSLPeerCouldBeClosed_,
  1253. };
  1254. std::string to_string(Error error);
  1255. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1256. class Stream {
  1257. public:
  1258. virtual ~Stream() = default;
  1259. virtual bool is_readable() const = 0;
  1260. virtual bool wait_readable() const = 0;
  1261. virtual bool wait_writable() const = 0;
  1262. virtual bool is_peer_alive() const { return wait_writable(); }
  1263. virtual ssize_t read(char *ptr, size_t size) = 0;
  1264. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1265. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1266. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1267. virtual socket_t socket() const = 0;
  1268. virtual time_t duration() const = 0;
  1269. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1270. (void)sec;
  1271. (void)usec;
  1272. }
  1273. ssize_t write(const char *ptr);
  1274. ssize_t write(const std::string &s);
  1275. Error get_error() const { return error_; }
  1276. protected:
  1277. Error error_ = Error::Success;
  1278. };
  1279. class TaskQueue {
  1280. public:
  1281. TaskQueue() = default;
  1282. virtual ~TaskQueue() = default;
  1283. virtual bool enqueue(std::function<void()> fn) = 0;
  1284. virtual void shutdown() = 0;
  1285. virtual void on_idle() {}
  1286. };
  1287. class ThreadPool final : public TaskQueue {
  1288. public:
  1289. explicit ThreadPool(size_t n, size_t max_n = 0, size_t mqr = 0);
  1290. ThreadPool(const ThreadPool &) = delete;
  1291. ~ThreadPool() override = default;
  1292. bool enqueue(std::function<void()> fn) override;
  1293. void shutdown() override;
  1294. private:
  1295. void worker(bool is_dynamic);
  1296. void move_to_finished(std::thread::id id);
  1297. void cleanup_finished_threads();
  1298. size_t base_thread_count_;
  1299. size_t max_thread_count_;
  1300. size_t max_queued_requests_;
  1301. size_t idle_thread_count_;
  1302. bool shutdown_;
  1303. std::list<std::function<void()>> jobs_;
  1304. std::vector<std::thread> threads_; // base threads
  1305. std::list<std::thread> dynamic_threads_; // dynamic threads
  1306. std::vector<std::thread>
  1307. finished_threads_; // exited dynamic threads awaiting join
  1308. std::condition_variable cond_;
  1309. std::mutex mutex_;
  1310. };
  1311. using Logger = std::function<void(const Request &, const Response &)>;
  1312. // Forward declaration for Error type
  1313. enum class Error;
  1314. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1315. using SocketOptions = std::function<void(socket_t sock)>;
  1316. void default_socket_options(socket_t sock);
  1317. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1318. const char *status_message(int status);
  1319. std::string to_string(Error error);
  1320. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1321. std::string get_bearer_token_auth(const Request &req);
  1322. namespace detail {
  1323. class MatcherBase {
  1324. public:
  1325. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1326. virtual ~MatcherBase() = default;
  1327. const std::string &pattern() const { return pattern_; }
  1328. // Match request path and populate its matches and
  1329. virtual bool match(Request &request) const = 0;
  1330. private:
  1331. std::string pattern_;
  1332. };
  1333. /**
  1334. * Captures parameters in request path and stores them in Request::path_params
  1335. *
  1336. * Capture name is a substring of a pattern from : to /.
  1337. * The rest of the pattern is matched against the request path directly
  1338. * Parameters are captured starting from the next character after
  1339. * the end of the last matched static pattern fragment until the next /.
  1340. *
  1341. * Example pattern:
  1342. * "/path/fragments/:capture/more/fragments/:second_capture"
  1343. * Static fragments:
  1344. * "/path/fragments/", "more/fragments/"
  1345. *
  1346. * Given the following request path:
  1347. * "/path/fragments/:1/more/fragments/:2"
  1348. * the resulting capture will be
  1349. * {{"capture", "1"}, {"second_capture", "2"}}
  1350. */
  1351. class PathParamsMatcher final : public MatcherBase {
  1352. public:
  1353. PathParamsMatcher(const std::string &pattern);
  1354. bool match(Request &request) const override;
  1355. private:
  1356. // Treat segment separators as the end of path parameter capture
  1357. // Does not need to handle query parameters as they are parsed before path
  1358. // matching
  1359. static constexpr char separator = '/';
  1360. // Contains static path fragments to match against, excluding the '/' after
  1361. // path params
  1362. // Fragments are separated by path params
  1363. std::vector<std::string> static_fragments_;
  1364. // Stores the names of the path parameters to be used as keys in the
  1365. // Request::path_params map
  1366. std::vector<std::string> param_names_;
  1367. };
  1368. /**
  1369. * Performs std::regex_match on request path
  1370. * and stores the result in Request::matches
  1371. *
  1372. * Note that regex match is performed directly on the whole request.
  1373. * This means that wildcard patterns may match multiple path segments with /:
  1374. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1375. */
  1376. class RegexMatcher final : public MatcherBase {
  1377. public:
  1378. RegexMatcher(const std::string &pattern)
  1379. : MatcherBase(pattern), regex_(pattern) {}
  1380. bool match(Request &request) const override;
  1381. private:
  1382. std::regex regex_;
  1383. };
  1384. int close_socket(socket_t sock) noexcept;
  1385. ssize_t write_headers(Stream &strm, const Headers &headers);
  1386. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1387. time_t usec);
  1388. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1389. const std::string &boundary);
  1390. ContentProvider
  1391. make_multipart_content_provider(const UploadFormDataItems &items,
  1392. const std::string &boundary);
  1393. } // namespace detail
  1394. bool is_valid_multipart_boundary(const std::string &boundary);
  1395. // Serializer for multipart/form-data request bodies. The boundary is owned
  1396. // by the writer so that per-part framing and the final terminator always
  1397. // agree. Field names and filenames are escaped following the WHATWG HTML
  1398. // standard ('"' -> %22, CR -> %0D, LF -> %0A).
  1399. class MultipartFormDataWriter {
  1400. public:
  1401. MultipartFormDataWriter();
  1402. // precondition: is_valid_multipart_boundary(boundary)
  1403. explicit MultipartFormDataWriter(std::string boundary);
  1404. const std::string &boundary() const;
  1405. std::string content_type() const;
  1406. // In-memory items -> whole body (known length)
  1407. std::string serialize(const UploadFormDataItems &items) const;
  1408. size_t content_length(const UploadFormDataItems &items) const;
  1409. // Per-part framing for streaming via a content provider
  1410. std::string item_begin(const UploadFormData &item) const;
  1411. static std::string item_end();
  1412. std::string finish() const;
  1413. private:
  1414. std::string boundary_;
  1415. };
  1416. class Server {
  1417. public:
  1418. using Handler = std::function<void(const Request &, Response &)>;
  1419. using ExceptionHandler =
  1420. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1421. enum class HandlerResponse {
  1422. Handled,
  1423. Unhandled,
  1424. };
  1425. using HandlerWithResponse =
  1426. std::function<HandlerResponse(const Request &, Response &)>;
  1427. using HandlerWithContentReader = std::function<void(
  1428. const Request &, Response &, const ContentReader &content_reader)>;
  1429. using Expect100ContinueHandler =
  1430. std::function<int(const Request &, Response &)>;
  1431. using StartHandler = std::function<void()>;
  1432. using WebSocketHandler =
  1433. std::function<void(const Request &, ws::WebSocket &)>;
  1434. using SubProtocolSelector =
  1435. std::function<std::string(const std::vector<std::string> &protocols)>;
  1436. Server();
  1437. virtual ~Server();
  1438. virtual bool is_valid() const;
  1439. Server &Get(const std::string &pattern, Handler handler);
  1440. Server &Post(const std::string &pattern, Handler handler);
  1441. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1442. Server &Put(const std::string &pattern, Handler handler);
  1443. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1444. Server &Patch(const std::string &pattern, Handler handler);
  1445. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1446. Server &Delete(const std::string &pattern, Handler handler);
  1447. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1448. Server &Options(const std::string &pattern, Handler handler);
  1449. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1450. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1451. SubProtocolSelector sub_protocol_selector);
  1452. bool set_base_dir(const std::string &dir,
  1453. const std::string &mount_point = std::string());
  1454. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1455. Headers headers = Headers());
  1456. bool remove_mount_point(const std::string &mount_point);
  1457. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1458. const std::string &mime);
  1459. Server &set_default_file_mimetype(const std::string &mime);
  1460. Server &set_file_request_handler(Handler handler);
  1461. template <class ErrorHandlerFunc>
  1462. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1463. return set_error_handler_core(
  1464. std::forward<ErrorHandlerFunc>(handler),
  1465. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1466. }
  1467. Server &set_exception_handler(ExceptionHandler handler);
  1468. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1469. Server &set_post_routing_handler(Handler handler);
  1470. Server &set_pre_request_handler(HandlerWithResponse handler);
  1471. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1472. Server &set_start_handler(StartHandler handler);
  1473. Server &set_logger(Logger logger);
  1474. Server &set_pre_compression_logger(Logger logger);
  1475. Server &set_error_logger(ErrorLogger error_logger);
  1476. Server &set_address_family(int family);
  1477. Server &set_tcp_nodelay(bool on);
  1478. Server &set_ipv6_v6only(bool on);
  1479. Server &set_socket_options(SocketOptions socket_options);
  1480. Server &set_default_headers(Headers headers);
  1481. Server &
  1482. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1483. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1484. Server &set_keep_alive_max_count(size_t count);
  1485. Server &set_keep_alive_timeout(time_t sec);
  1486. template <class Rep, class Period>
  1487. Server &
  1488. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1489. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1490. template <class Rep, class Period>
  1491. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1492. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1493. template <class Rep, class Period>
  1494. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1495. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1496. template <class Rep, class Period>
  1497. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1498. Server &set_payload_max_length(size_t length);
  1499. Server &set_websocket_ping_interval(time_t sec);
  1500. template <class Rep, class Period>
  1501. Server &set_websocket_ping_interval(
  1502. const std::chrono::duration<Rep, Period> &duration);
  1503. Server &set_websocket_max_missed_pongs(int count);
  1504. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1505. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1506. bool listen_after_bind();
  1507. bool listen(const std::string &host, int port, int socket_flags = 0);
  1508. bool is_running() const;
  1509. void wait_until_ready() const;
  1510. void stop() noexcept;
  1511. void decommission();
  1512. std::function<TaskQueue *(void)> new_task_queue;
  1513. protected:
  1514. bool process_request(Stream &strm, const std::string &remote_addr,
  1515. int remote_port, const std::string &local_addr,
  1516. int local_port, bool close_connection,
  1517. bool &connection_closed,
  1518. const std::function<void(Request &)> &setup_request,
  1519. bool *websocket_upgraded = nullptr);
  1520. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1521. std::vector<std::string> trusted_proxies_;
  1522. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1523. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1524. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1525. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1526. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1527. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1528. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1529. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1530. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1531. time_t websocket_ping_interval_sec_ =
  1532. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1533. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1534. private:
  1535. using Handlers =
  1536. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1537. using HandlersForContentReader =
  1538. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1539. HandlerWithContentReader>>;
  1540. static std::unique_ptr<detail::MatcherBase>
  1541. make_matcher(const std::string &pattern);
  1542. template <typename H>
  1543. Server &add_handler(
  1544. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1545. const std::string &pattern, H handler) {
  1546. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1547. return *this;
  1548. }
  1549. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1550. Server &set_error_handler_core(Handler handler, std::false_type);
  1551. socket_t create_server_socket(const std::string &host, int port,
  1552. int socket_flags,
  1553. SocketOptions socket_options) const;
  1554. int bind_internal(const std::string &host, int port, int socket_flags);
  1555. bool listen_internal();
  1556. bool routing(Request &req, Response &res, Stream &strm);
  1557. bool handle_file_request(Request &req, Response &res);
  1558. bool check_if_not_modified(const Request &req, Response &res,
  1559. const std::string &etag, time_t mtime) const;
  1560. bool check_if_range(Request &req, const std::string &etag,
  1561. time_t mtime) const;
  1562. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1563. Stream &strm);
  1564. bool dispatch_request_for_content_reader(
  1565. Request &req, Response &res, ContentReader content_reader,
  1566. const HandlersForContentReader &handlers) const;
  1567. bool parse_request_line(const char *s, Request &req) const;
  1568. void apply_ranges(const Request &req, Response &res,
  1569. std::string &content_type, std::string &boundary) const;
  1570. bool write_response(Stream &strm, bool close_connection, Request &req,
  1571. Response &res);
  1572. bool write_response_with_content(Stream &strm, bool close_connection,
  1573. const Request &req, Response &res);
  1574. bool write_response_core(Stream &strm, bool close_connection,
  1575. const Request &req, Response &res,
  1576. bool need_apply_ranges);
  1577. bool write_content_with_provider(Stream &strm, const Request &req,
  1578. Response &res, const std::string &boundary,
  1579. const std::string &content_type);
  1580. bool read_content(Stream &strm, Request &req, Response &res);
  1581. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1582. Response &res,
  1583. ContentReceiver receiver,
  1584. FormDataHeader multipart_header,
  1585. ContentReceiver multipart_receiver);
  1586. bool read_content_core(Stream &strm, Request &req, Response &res,
  1587. ContentReceiver receiver,
  1588. FormDataHeader multipart_header,
  1589. ContentReceiver multipart_receiver) const;
  1590. virtual bool process_and_close_socket(socket_t sock);
  1591. void output_log(const Request &req, const Response &res) const;
  1592. void output_pre_compression_log(const Request &req,
  1593. const Response &res) const;
  1594. void output_error_log(const Error &err, const Request *req) const;
  1595. std::atomic<bool> is_running_{false};
  1596. std::atomic<bool> is_decommissioned{false};
  1597. struct MountPointEntry {
  1598. std::string mount_point;
  1599. std::string base_dir;
  1600. std::string resolved_base_dir;
  1601. Headers headers;
  1602. };
  1603. std::vector<MountPointEntry> base_dirs_;
  1604. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1605. std::string default_file_mimetype_ = "application/octet-stream";
  1606. Handler file_request_handler_;
  1607. Handlers get_handlers_;
  1608. Handlers post_handlers_;
  1609. HandlersForContentReader post_handlers_for_content_reader_;
  1610. Handlers put_handlers_;
  1611. HandlersForContentReader put_handlers_for_content_reader_;
  1612. Handlers patch_handlers_;
  1613. HandlersForContentReader patch_handlers_for_content_reader_;
  1614. Handlers delete_handlers_;
  1615. HandlersForContentReader delete_handlers_for_content_reader_;
  1616. Handlers options_handlers_;
  1617. struct WebSocketHandlerEntry {
  1618. std::unique_ptr<detail::MatcherBase> matcher;
  1619. WebSocketHandler handler;
  1620. SubProtocolSelector sub_protocol_selector;
  1621. };
  1622. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1623. WebSocketHandlers websocket_handlers_;
  1624. HandlerWithResponse error_handler_;
  1625. ExceptionHandler exception_handler_;
  1626. HandlerWithResponse pre_routing_handler_;
  1627. Handler post_routing_handler_;
  1628. HandlerWithResponse pre_request_handler_;
  1629. Expect100ContinueHandler expect_100_continue_handler_;
  1630. StartHandler start_handler_;
  1631. mutable std::mutex logger_mutex_;
  1632. Logger logger_;
  1633. Logger pre_compression_logger_;
  1634. ErrorLogger error_logger_;
  1635. int address_family_ = AF_UNSPEC;
  1636. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1637. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1638. SocketOptions socket_options_ = default_socket_options;
  1639. Headers default_headers_;
  1640. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1641. detail::write_headers;
  1642. };
  1643. class Result {
  1644. public:
  1645. Result() = default;
  1646. Result(std::unique_ptr<Response> &&res, Error err,
  1647. Headers &&request_headers = Headers{})
  1648. : res_(std::move(res)), err_(err),
  1649. request_headers_(std::move(request_headers)) {}
  1650. // Response
  1651. operator bool() const { return res_ != nullptr; }
  1652. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1653. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1654. const Response &value() const { return *res_; }
  1655. Response &value() { return *res_; }
  1656. const Response &operator*() const { return *res_; }
  1657. Response &operator*() { return *res_; }
  1658. const Response *operator->() const { return res_.get(); }
  1659. Response *operator->() { return res_.get(); }
  1660. // Error
  1661. Error error() const { return err_; }
  1662. // Request Headers
  1663. bool has_request_header(const std::string &key) const;
  1664. std::string get_request_header_value(const std::string &key,
  1665. const char *def = "",
  1666. size_t id = 0) const;
  1667. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1668. size_t id = 0) const;
  1669. size_t get_request_header_value_count(const std::string &key) const;
  1670. private:
  1671. std::unique_ptr<Response> res_;
  1672. Error err_ = Error::Unknown;
  1673. Headers request_headers_;
  1674. #ifdef CPPHTTPLIB_SSL_ENABLED
  1675. public:
  1676. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1677. int ssl_error)
  1678. : res_(std::move(res)), err_(err),
  1679. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1680. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1681. int ssl_error, uint64_t ssl_backend_error)
  1682. : res_(std::move(res)), err_(err),
  1683. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1684. ssl_backend_error_(ssl_backend_error) {}
  1685. int ssl_error() const { return ssl_error_; }
  1686. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1687. private:
  1688. int ssl_error_ = 0;
  1689. uint64_t ssl_backend_error_ = 0;
  1690. #endif
  1691. };
  1692. struct ClientConnection {
  1693. socket_t sock = INVALID_SOCKET;
  1694. bool is_open() const { return sock != INVALID_SOCKET; }
  1695. ClientConnection() = default;
  1696. ~ClientConnection();
  1697. ClientConnection(const ClientConnection &) = delete;
  1698. ClientConnection &operator=(const ClientConnection &) = delete;
  1699. ClientConnection(ClientConnection &&other) noexcept
  1700. : sock(other.sock)
  1701. #ifdef CPPHTTPLIB_SSL_ENABLED
  1702. ,
  1703. session(other.session)
  1704. #endif
  1705. {
  1706. other.sock = INVALID_SOCKET;
  1707. #ifdef CPPHTTPLIB_SSL_ENABLED
  1708. other.session = nullptr;
  1709. #endif
  1710. }
  1711. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1712. if (this != &other) {
  1713. sock = other.sock;
  1714. other.sock = INVALID_SOCKET;
  1715. #ifdef CPPHTTPLIB_SSL_ENABLED
  1716. session = other.session;
  1717. other.session = nullptr;
  1718. #endif
  1719. }
  1720. return *this;
  1721. }
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. tls::session_t session = nullptr;
  1724. #endif
  1725. };
  1726. namespace detail {
  1727. struct ChunkedDecoder;
  1728. struct BodyReader {
  1729. Stream *stream = nullptr;
  1730. bool has_content_length = false;
  1731. size_t content_length = 0;
  1732. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1733. size_t bytes_read = 0;
  1734. bool chunked = false;
  1735. bool eof = false;
  1736. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1737. Error last_error = Error::Success;
  1738. ssize_t read(char *buf, size_t len);
  1739. bool has_error() const { return last_error != Error::Success; }
  1740. };
  1741. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1742. size_t len) {
  1743. (void)stream;
  1744. return br.read(buf, len);
  1745. }
  1746. class decompressor;
  1747. enum class NoProxyKind {
  1748. Wildcard, // "*"
  1749. HostnameSuffix, // "example.com" or ".example.com"
  1750. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1751. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1752. };
  1753. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1754. // Lets one CIDR matcher cover both families.
  1755. using IPBytes = std::array<uint8_t, 16>;
  1756. struct NoProxyEntry {
  1757. NoProxyKind kind = NoProxyKind::Wildcard;
  1758. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1759. IPBytes net{};
  1760. int prefix_bits = 0;
  1761. };
  1762. struct NormalizedTarget {
  1763. std::string hostname; // lowercase; brackets and trailing dot removed
  1764. bool is_ipv4 = false;
  1765. bool is_ipv6 = false;
  1766. IPBytes ip{};
  1767. };
  1768. } // namespace detail
  1769. class ClientImpl {
  1770. public:
  1771. explicit ClientImpl(const std::string &host);
  1772. explicit ClientImpl(const std::string &host, int port);
  1773. explicit ClientImpl(const std::string &host, int port,
  1774. const std::string &client_cert_path,
  1775. const std::string &client_key_path);
  1776. virtual ~ClientImpl();
  1777. virtual bool is_valid() const;
  1778. struct StreamHandle {
  1779. std::unique_ptr<Response> response;
  1780. Error error = Error::Success;
  1781. StreamHandle() = default;
  1782. StreamHandle(const StreamHandle &) = delete;
  1783. StreamHandle &operator=(const StreamHandle &) = delete;
  1784. StreamHandle(StreamHandle &&) = default;
  1785. StreamHandle &operator=(StreamHandle &&) = default;
  1786. ~StreamHandle() = default;
  1787. bool is_valid() const {
  1788. return response != nullptr && error == Error::Success;
  1789. }
  1790. ssize_t read(char *buf, size_t len);
  1791. void parse_trailers_if_needed();
  1792. Error get_read_error() const { return body_reader_.last_error; }
  1793. bool has_read_error() const { return body_reader_.has_error(); }
  1794. bool trailers_parsed_ = false;
  1795. private:
  1796. friend class ClientImpl;
  1797. ssize_t read_with_decompression(char *buf, size_t len);
  1798. std::unique_ptr<ClientConnection> connection_;
  1799. std::unique_ptr<Stream> socket_stream_;
  1800. Stream *stream_ = nullptr;
  1801. detail::BodyReader body_reader_;
  1802. std::unique_ptr<detail::decompressor> decompressor_;
  1803. std::string decompress_buffer_;
  1804. size_t decompress_offset_ = 0;
  1805. size_t decompressed_bytes_read_ = 0;
  1806. };
  1807. // clang-format off
  1808. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1809. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1810. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1811. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1812. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1813. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1814. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1815. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1816. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1817. Result Head(const std::string &path);
  1818. Result Head(const std::string &path, const Headers &headers);
  1819. Result Post(const std::string &path);
  1820. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1821. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1822. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1823. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1824. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1825. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1826. Result Post(const std::string &path, const Params &params);
  1827. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1828. Result Post(const std::string &path, const Headers &headers);
  1829. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1830. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1831. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1832. 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);
  1833. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1834. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1835. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1836. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1840. Result Put(const std::string &path);
  1841. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1842. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1843. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1844. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1845. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1847. Result Put(const std::string &path, const Params &params);
  1848. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1849. Result Put(const std::string &path, const Headers &headers);
  1850. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1851. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1852. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1853. 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);
  1854. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1855. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1856. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1857. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1861. Result Patch(const std::string &path);
  1862. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1863. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1864. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1865. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1866. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1868. Result Patch(const std::string &path, const Params &params);
  1869. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1870. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1871. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1872. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1873. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1874. 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);
  1875. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1876. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1877. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1878. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1882. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1883. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1884. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1885. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1886. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1887. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1888. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1889. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1890. Result Options(const std::string &path);
  1891. Result Options(const std::string &path, const Headers &headers);
  1892. // clang-format on
  1893. // Streaming API: Open a stream for reading response body incrementally
  1894. // Socket ownership is transferred to StreamHandle for true streaming
  1895. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1896. StreamHandle open_stream(const std::string &method, const std::string &path,
  1897. const Params &params = {},
  1898. const Headers &headers = {},
  1899. const std::string &body = {},
  1900. const std::string &content_type = {});
  1901. bool send(Request &req, Response &res, Error &error);
  1902. Result send(const Request &req);
  1903. void stop();
  1904. std::string host() const;
  1905. int port() const;
  1906. size_t is_socket_open() const;
  1907. socket_t socket() const;
  1908. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1909. void set_default_headers(Headers headers);
  1910. void
  1911. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1912. void set_address_family(int family);
  1913. void set_tcp_nodelay(bool on);
  1914. void set_ipv6_v6only(bool on);
  1915. void set_socket_options(SocketOptions socket_options);
  1916. void set_connection_timeout(time_t sec, time_t usec = 0);
  1917. template <class Rep, class Period>
  1918. void
  1919. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1920. void set_read_timeout(time_t sec, time_t usec = 0);
  1921. template <class Rep, class Period>
  1922. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1923. void set_write_timeout(time_t sec, time_t usec = 0);
  1924. template <class Rep, class Period>
  1925. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1926. void set_max_timeout(time_t msec);
  1927. template <class Rep, class Period>
  1928. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1929. void set_basic_auth(const std::string &username, const std::string &password);
  1930. void set_bearer_token_auth(const std::string &token);
  1931. void set_keep_alive(bool on);
  1932. void set_follow_location(bool on);
  1933. void set_path_encode(bool on);
  1934. void set_compress(bool on);
  1935. void set_decompress(bool on);
  1936. void set_payload_max_length(size_t length);
  1937. void set_interface(const std::string &intf);
  1938. void set_proxy(const std::string &host, int port);
  1939. void set_proxy_basic_auth(const std::string &username,
  1940. const std::string &password);
  1941. void set_proxy_bearer_token_auth(const std::string &token);
  1942. void set_no_proxy(const std::vector<std::string> &patterns);
  1943. void set_logger(Logger logger);
  1944. void set_error_logger(ErrorLogger error_logger);
  1945. protected:
  1946. struct Socket {
  1947. socket_t sock = INVALID_SOCKET;
  1948. // For Mbed TLS compatibility: start_time for request timeout tracking
  1949. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1950. bool is_open() const { return sock != INVALID_SOCKET; }
  1951. #ifdef CPPHTTPLIB_SSL_ENABLED
  1952. tls::session_t ssl = nullptr;
  1953. #endif
  1954. };
  1955. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1956. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1957. virtual bool setup_proxy_connection(
  1958. Socket &socket,
  1959. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1960. Response &res, bool &success, Error &error);
  1961. bool is_proxy_enabled_for_host(const std::string &host) const;
  1962. // All of:
  1963. // shutdown_ssl
  1964. // shutdown_socket
  1965. // close_socket
  1966. // disconnect
  1967. // should ONLY be called when socket_mutex_ is locked, and only when
  1968. // no other thread is using the socket.
  1969. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1970. void shutdown_socket(Socket &socket) const;
  1971. void close_socket(Socket &socket);
  1972. void disconnect(bool gracefully);
  1973. bool process_request(Stream &strm, Request &req, Response &res,
  1974. bool close_connection, Error &error);
  1975. bool write_content_with_provider(Stream &strm, const Request &req,
  1976. Error &error) const;
  1977. void copy_settings(const ClientImpl &rhs);
  1978. void output_log(const Request &req, const Response &res) const;
  1979. void output_error_log(const Error &err, const Request *req) const;
  1980. // Socket endpoint information
  1981. const std::string host_;
  1982. const int port_;
  1983. // Current open socket
  1984. Socket socket_;
  1985. mutable std::mutex socket_mutex_;
  1986. std::recursive_mutex request_mutex_;
  1987. // These are all protected under socket_mutex
  1988. size_t socket_requests_in_flight_ = 0;
  1989. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1990. bool socket_should_be_closed_when_request_is_done_ = false;
  1991. // Hostname-IP map
  1992. std::map<std::string, std::string> addr_map_;
  1993. // Default headers
  1994. Headers default_headers_;
  1995. // Header writer
  1996. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1997. detail::write_headers;
  1998. // Settings
  1999. std::string client_cert_path_;
  2000. std::string client_key_path_;
  2001. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2002. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2003. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2004. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2005. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2006. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2007. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2008. std::string basic_auth_username_;
  2009. std::string basic_auth_password_;
  2010. std::string bearer_token_auth_token_;
  2011. bool keep_alive_ = false;
  2012. bool follow_location_ = false;
  2013. bool path_encode_ = true;
  2014. int address_family_ = AF_UNSPEC;
  2015. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2016. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2017. SocketOptions socket_options_ = nullptr;
  2018. bool compress_ = false;
  2019. bool decompress_ = true;
  2020. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2021. bool has_payload_max_length_ = false;
  2022. std::string interface_;
  2023. std::string proxy_host_;
  2024. int proxy_port_ = -1;
  2025. std::string proxy_basic_auth_username_;
  2026. std::string proxy_basic_auth_password_;
  2027. std::string proxy_bearer_token_auth_token_;
  2028. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2029. mutable detail::NormalizedTarget host_normalized_;
  2030. mutable bool host_normalized_valid_ = false;
  2031. mutable std::mutex logger_mutex_;
  2032. Logger logger_;
  2033. ErrorLogger error_logger_;
  2034. private:
  2035. bool send_(Request &req, Response &res, Error &error);
  2036. Result send_(Request &&req);
  2037. socket_t create_client_socket(Error &error) const;
  2038. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2039. bool skip_100_continue = true) const;
  2040. bool write_request(Stream &strm, Request &req, bool close_connection,
  2041. Error &error, bool skip_body = false);
  2042. bool write_request_body(Stream &strm, Request &req, Error &error);
  2043. void prepare_default_headers(Request &r, bool for_stream,
  2044. const std::string &ct);
  2045. bool redirect(Request &req, Response &res, Error &error);
  2046. bool create_redirect_client(const std::string &scheme,
  2047. const std::string &host, int port, Request &req,
  2048. Response &res, const std::string &path,
  2049. const std::string &location, Error &error);
  2050. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2051. bool handle_request(Stream &strm, Request &req, Response &res,
  2052. bool close_connection, Error &error);
  2053. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2054. Request &req, const char *body, size_t content_length,
  2055. ContentProvider content_provider,
  2056. ContentProviderWithoutLength content_provider_without_length,
  2057. const std::string &content_type, ContentReceiver content_receiver,
  2058. Error &error);
  2059. Result send_with_content_provider_and_receiver(
  2060. const std::string &method, const std::string &path,
  2061. const Headers &headers, const char *body, size_t content_length,
  2062. ContentProvider content_provider,
  2063. ContentProviderWithoutLength content_provider_without_length,
  2064. const std::string &content_type, ContentReceiver content_receiver,
  2065. UploadProgress progress);
  2066. ContentProviderWithoutLength get_multipart_content_provider(
  2067. const std::string &boundary, const UploadFormDataItems &items,
  2068. const FormDataProviderItems &provider_items) const;
  2069. virtual bool
  2070. process_socket(const Socket &socket,
  2071. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2072. std::function<bool(Stream &strm)> callback);
  2073. virtual bool is_ssl() const;
  2074. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2075. #ifdef CPPHTTPLIB_SSL_ENABLED
  2076. public:
  2077. void set_digest_auth(const std::string &username,
  2078. const std::string &password);
  2079. void set_proxy_digest_auth(const std::string &username,
  2080. const std::string &password);
  2081. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2082. const std::string &ca_cert_dir_path = std::string());
  2083. void enable_server_certificate_verification(bool enabled);
  2084. void enable_server_hostname_verification(bool enabled);
  2085. void enable_system_ca(bool enabled);
  2086. protected:
  2087. std::string digest_auth_username_;
  2088. std::string digest_auth_password_;
  2089. std::string proxy_digest_auth_username_;
  2090. std::string proxy_digest_auth_password_;
  2091. std::string ca_cert_file_path_;
  2092. std::string ca_cert_dir_path_;
  2093. bool server_certificate_verification_ = true;
  2094. bool server_hostname_verification_ = true;
  2095. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2096. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2097. int last_ssl_error_ = 0;
  2098. uint64_t last_backend_error_ = 0;
  2099. #endif
  2100. };
  2101. class Client {
  2102. public:
  2103. // Universal interface
  2104. explicit Client(const std::string &scheme_host_port);
  2105. explicit Client(const std::string &scheme_host_port,
  2106. const std::string &client_cert_path,
  2107. const std::string &client_key_path);
  2108. // HTTP only interface
  2109. explicit Client(const std::string &host, int port);
  2110. explicit Client(const std::string &host, int port,
  2111. const std::string &client_cert_path,
  2112. const std::string &client_key_path);
  2113. Client(Client &&) = default;
  2114. Client &operator=(Client &&) = default;
  2115. ~Client();
  2116. bool is_valid() const;
  2117. // clang-format off
  2118. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2119. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2120. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2121. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2122. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2123. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2124. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2125. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2126. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2127. Result Head(const std::string &path);
  2128. Result Head(const std::string &path, const Headers &headers);
  2129. Result Post(const std::string &path);
  2130. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2131. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2132. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2133. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2134. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2135. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2136. Result Post(const std::string &path, const Params &params);
  2137. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2138. Result Post(const std::string &path, const Headers &headers);
  2139. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2140. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2141. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2142. 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);
  2143. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2144. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2145. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2146. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2147. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2150. Result Put(const std::string &path);
  2151. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2152. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2153. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2154. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2155. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2156. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2157. Result Put(const std::string &path, const Params &params);
  2158. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2159. Result Put(const std::string &path, const Headers &headers);
  2160. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2162. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2163. 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);
  2164. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2165. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2166. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2167. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2168. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2171. Result Patch(const std::string &path);
  2172. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2173. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2174. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2175. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2176. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2177. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2178. Result Patch(const std::string &path, const Params &params);
  2179. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2180. Result Patch(const std::string &path, const Headers &headers);
  2181. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2183. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2184. 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);
  2185. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2186. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2187. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2188. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2189. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2192. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2193. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2194. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2195. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2196. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2197. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2198. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2199. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2200. Result Options(const std::string &path);
  2201. Result Options(const std::string &path, const Headers &headers);
  2202. // clang-format on
  2203. // Streaming API: Open a stream for reading response body incrementally
  2204. // Socket ownership is transferred to StreamHandle for true streaming
  2205. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2206. ClientImpl::StreamHandle open_stream(const std::string &method,
  2207. const std::string &path,
  2208. const Params &params = {},
  2209. const Headers &headers = {},
  2210. const std::string &body = {},
  2211. const std::string &content_type = {});
  2212. bool send(Request &req, Response &res, Error &error);
  2213. Result send(const Request &req);
  2214. void stop();
  2215. std::string host() const;
  2216. int port() const;
  2217. size_t is_socket_open() const;
  2218. socket_t socket() const;
  2219. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2220. void set_default_headers(Headers headers);
  2221. void
  2222. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2223. void set_address_family(int family);
  2224. void set_tcp_nodelay(bool on);
  2225. void set_socket_options(SocketOptions socket_options);
  2226. void set_connection_timeout(time_t sec, time_t usec = 0);
  2227. template <class Rep, class Period>
  2228. void
  2229. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2230. void set_read_timeout(time_t sec, time_t usec = 0);
  2231. template <class Rep, class Period>
  2232. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2233. void set_write_timeout(time_t sec, time_t usec = 0);
  2234. template <class Rep, class Period>
  2235. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2236. void set_max_timeout(time_t msec);
  2237. template <class Rep, class Period>
  2238. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2239. void set_basic_auth(const std::string &username, const std::string &password);
  2240. void set_bearer_token_auth(const std::string &token);
  2241. void set_keep_alive(bool on);
  2242. void set_follow_location(bool on);
  2243. void set_path_encode(bool on);
  2244. void set_compress(bool on);
  2245. void set_decompress(bool on);
  2246. void set_payload_max_length(size_t length);
  2247. void set_interface(const std::string &intf);
  2248. void set_proxy(const std::string &host, int port);
  2249. void set_proxy_basic_auth(const std::string &username,
  2250. const std::string &password);
  2251. void set_proxy_bearer_token_auth(const std::string &token);
  2252. void set_no_proxy(const std::vector<std::string> &patterns);
  2253. void set_logger(Logger logger);
  2254. void set_error_logger(ErrorLogger error_logger);
  2255. private:
  2256. std::unique_ptr<ClientImpl> cli_;
  2257. #ifdef CPPHTTPLIB_SSL_ENABLED
  2258. public:
  2259. void set_digest_auth(const std::string &username,
  2260. const std::string &password);
  2261. void set_proxy_digest_auth(const std::string &username,
  2262. const std::string &password);
  2263. void enable_server_certificate_verification(bool enabled);
  2264. void enable_server_hostname_verification(bool enabled);
  2265. void enable_system_ca(bool enabled);
  2266. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2267. const std::string &ca_cert_dir_path = std::string());
  2268. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2269. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2270. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2271. void set_session_verifier(
  2272. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2273. tls::ctx_t tls_context() const;
  2274. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2275. void enable_windows_certificate_verification(bool enabled);
  2276. #endif
  2277. private:
  2278. bool is_ssl_ = false;
  2279. #endif
  2280. };
  2281. #ifdef CPPHTTPLIB_SSL_ENABLED
  2282. class SSLServer : public Server {
  2283. public:
  2284. SSLServer(const char *cert_path, const char *private_key_path,
  2285. const char *client_ca_cert_file_path = nullptr,
  2286. const char *client_ca_cert_dir_path = nullptr,
  2287. const char *private_key_password = nullptr);
  2288. struct PemMemory {
  2289. const char *cert_pem;
  2290. size_t cert_pem_len;
  2291. const char *key_pem;
  2292. size_t key_pem_len;
  2293. const char *client_ca_pem;
  2294. size_t client_ca_pem_len;
  2295. const char *private_key_password;
  2296. };
  2297. explicit SSLServer(const PemMemory &pem);
  2298. // The callback receives the ctx_t handle which can be cast to the
  2299. // appropriate backend type (SSL_CTX* for OpenSSL,
  2300. // tls::impl::MbedTlsContext* for Mbed TLS)
  2301. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2302. ~SSLServer() override;
  2303. bool is_valid() const override;
  2304. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2305. const char *client_ca_pem = nullptr,
  2306. const char *password = nullptr);
  2307. tls::ctx_t tls_context() const { return ctx_; }
  2308. int ssl_last_error() const { return last_ssl_error_; }
  2309. private:
  2310. bool process_and_close_socket(socket_t sock) override;
  2311. tls::ctx_t ctx_ = nullptr;
  2312. std::mutex ctx_mutex_;
  2313. int last_ssl_error_ = 0;
  2314. };
  2315. class SSLClient final : public ClientImpl {
  2316. public:
  2317. explicit SSLClient(const std::string &host);
  2318. explicit SSLClient(const std::string &host, int port);
  2319. explicit SSLClient(const std::string &host, int port,
  2320. const std::string &client_cert_path,
  2321. const std::string &client_key_path,
  2322. const std::string &private_key_password = std::string());
  2323. struct PemMemory {
  2324. const char *cert_pem;
  2325. size_t cert_pem_len;
  2326. const char *key_pem;
  2327. size_t key_pem_len;
  2328. const char *private_key_password;
  2329. };
  2330. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2331. ~SSLClient() override;
  2332. bool is_valid() const override;
  2333. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2334. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2335. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2336. // Post-handshake session verifier (backend-independent)
  2337. void set_session_verifier(
  2338. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2339. tls::ctx_t tls_context() const { return ctx_; }
  2340. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2341. void enable_windows_certificate_verification(bool enabled);
  2342. #endif
  2343. private:
  2344. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2345. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2346. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2347. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2348. bool
  2349. process_socket(const Socket &socket,
  2350. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2351. std::function<bool(Stream &strm)> callback) override;
  2352. bool is_ssl() const override;
  2353. bool setup_proxy_connection(
  2354. Socket &socket,
  2355. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2356. Response &res, bool &success, Error &error) override;
  2357. bool connect_with_proxy(
  2358. Socket &sock,
  2359. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2360. Response &res, bool &success, Error &error);
  2361. bool initialize_ssl(Socket &socket, Error &error);
  2362. void init_ctx();
  2363. void reset_ctx_on_error();
  2364. bool load_certs();
  2365. tls::ctx_t ctx_ = nullptr;
  2366. std::mutex ctx_mutex_;
  2367. std::once_flag initialize_cert_;
  2368. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2369. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2370. // Used to keep custom CA configuration exclusive with system CA loading.
  2371. bool ca_cert_store_set_ = false;
  2372. long verify_result_ = 0;
  2373. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2374. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2375. bool enable_windows_cert_verification_ = true;
  2376. #endif
  2377. friend class ClientImpl;
  2378. };
  2379. #endif // CPPHTTPLIB_SSL_ENABLED
  2380. namespace detail {
  2381. template <typename T, typename U>
  2382. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2383. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2384. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2385. duration - std::chrono::seconds(sec))
  2386. .count();
  2387. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2388. }
  2389. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2390. return N - 1;
  2391. }
  2392. inline bool is_numeric(const std::string &str) {
  2393. return !str.empty() &&
  2394. std::all_of(str.cbegin(), str.cend(),
  2395. [](unsigned char c) { return std::isdigit(c); });
  2396. }
  2397. inline size_t get_header_value_u64(const Headers &headers,
  2398. const std::string &key, size_t def,
  2399. size_t id, bool &is_invalid_value) {
  2400. is_invalid_value = false;
  2401. auto rng = headers.equal_range(key);
  2402. auto it = rng.first;
  2403. std::advance(it, static_cast<ssize_t>(id));
  2404. if (it != rng.second) {
  2405. if (is_numeric(it->second)) {
  2406. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2407. } else {
  2408. is_invalid_value = true;
  2409. }
  2410. }
  2411. return def;
  2412. }
  2413. inline size_t get_header_value_u64(const Headers &headers,
  2414. const std::string &key, size_t def,
  2415. size_t id) {
  2416. auto dummy = false;
  2417. return get_header_value_u64(headers, key, def, id, dummy);
  2418. }
  2419. } // namespace detail
  2420. template <class Rep, class Period>
  2421. inline Server &
  2422. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2423. detail::duration_to_sec_and_usec(
  2424. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2425. return *this;
  2426. }
  2427. template <class Rep, class Period>
  2428. inline Server &
  2429. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2430. detail::duration_to_sec_and_usec(
  2431. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2432. return *this;
  2433. }
  2434. template <class Rep, class Period>
  2435. inline Server &
  2436. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2437. detail::duration_to_sec_and_usec(
  2438. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2439. return *this;
  2440. }
  2441. template <class Rep, class Period>
  2442. inline void ClientImpl::set_connection_timeout(
  2443. const std::chrono::duration<Rep, Period> &duration) {
  2444. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2445. set_connection_timeout(sec, usec);
  2446. });
  2447. }
  2448. template <class Rep, class Period>
  2449. inline void ClientImpl::set_read_timeout(
  2450. const std::chrono::duration<Rep, Period> &duration) {
  2451. detail::duration_to_sec_and_usec(
  2452. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2453. }
  2454. template <class Rep, class Period>
  2455. inline void ClientImpl::set_write_timeout(
  2456. const std::chrono::duration<Rep, Period> &duration) {
  2457. detail::duration_to_sec_and_usec(
  2458. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2459. }
  2460. template <class Rep, class Period>
  2461. inline void ClientImpl::set_max_timeout(
  2462. const std::chrono::duration<Rep, Period> &duration) {
  2463. auto msec =
  2464. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2465. set_max_timeout(msec);
  2466. }
  2467. template <class Rep, class Period>
  2468. inline void Client::set_connection_timeout(
  2469. const std::chrono::duration<Rep, Period> &duration) {
  2470. cli_->set_connection_timeout(duration);
  2471. }
  2472. template <class Rep, class Period>
  2473. inline void
  2474. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2475. cli_->set_read_timeout(duration);
  2476. }
  2477. template <class Rep, class Period>
  2478. inline void
  2479. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2480. cli_->set_write_timeout(duration);
  2481. }
  2482. inline void Client::set_max_timeout(time_t msec) {
  2483. cli_->set_max_timeout(msec);
  2484. }
  2485. template <class Rep, class Period>
  2486. inline void
  2487. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2488. cli_->set_max_timeout(duration);
  2489. }
  2490. /*
  2491. * Forward declarations and types that will be part of the .h file if split into
  2492. * .h + .cc.
  2493. */
  2494. std::string hosted_at(const std::string &hostname);
  2495. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2496. // JavaScript-style URL encoding/decoding functions
  2497. std::string encode_uri_component(const std::string &value);
  2498. std::string encode_uri(const std::string &value);
  2499. std::string decode_uri_component(const std::string &value);
  2500. std::string decode_uri(const std::string &value);
  2501. // RFC 3986 compliant URL component encoding/decoding functions
  2502. std::string encode_path_component(const std::string &component);
  2503. std::string decode_path_component(const std::string &component);
  2504. std::string encode_query_component(const std::string &component,
  2505. bool space_as_plus = true);
  2506. std::string decode_query_component(const std::string &component,
  2507. bool plus_as_space = true);
  2508. std::string sanitize_filename(const std::string &filename);
  2509. std::string append_query_params(const std::string &path, const Params &params);
  2510. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2511. std::pair<std::string, std::string>
  2512. make_basic_authentication_header(const std::string &username,
  2513. const std::string &password,
  2514. bool is_proxy = false);
  2515. namespace detail {
  2516. #if defined(_WIN32)
  2517. inline std::wstring u8string_to_wstring(const char *s) {
  2518. if (!s) { return std::wstring(); }
  2519. auto len = static_cast<int>(strlen(s));
  2520. if (!len) { return std::wstring(); }
  2521. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2522. if (!wlen) { return std::wstring(); }
  2523. std::wstring ws;
  2524. ws.resize(wlen);
  2525. wlen = ::MultiByteToWideChar(
  2526. CP_UTF8, 0, s, len,
  2527. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2528. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2529. return ws;
  2530. }
  2531. #endif
  2532. struct FileStat {
  2533. FileStat(const std::string &path);
  2534. bool is_file() const;
  2535. bool is_dir() const;
  2536. time_t mtime() const;
  2537. size_t size() const;
  2538. private:
  2539. #if defined(_WIN32)
  2540. struct _stat st_;
  2541. #else
  2542. struct stat st_;
  2543. #endif
  2544. int ret_ = -1;
  2545. };
  2546. std::string make_host_and_port_string(const std::string &host, int port,
  2547. bool is_ssl);
  2548. std::string trim_copy(const std::string &s);
  2549. void divide(
  2550. const char *data, std::size_t size, char d,
  2551. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2552. fn);
  2553. void divide(
  2554. const std::string &str, char d,
  2555. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2556. fn);
  2557. void split(const char *b, const char *e, char d,
  2558. std::function<void(const char *, const char *)> fn);
  2559. void split(const char *b, const char *e, char d, size_t m,
  2560. std::function<void(const char *, const char *)> fn);
  2561. bool process_client_socket(
  2562. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2563. time_t write_timeout_sec, time_t write_timeout_usec,
  2564. time_t max_timeout_msec,
  2565. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2566. std::function<bool(Stream &)> callback);
  2567. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2568. int port, int address_family, bool tcp_nodelay,
  2569. bool ipv6_v6only, SocketOptions socket_options,
  2570. time_t connection_timeout_sec,
  2571. time_t connection_timeout_usec,
  2572. time_t read_timeout_sec, time_t read_timeout_usec,
  2573. time_t write_timeout_sec,
  2574. time_t write_timeout_usec,
  2575. const std::string &intf, Error &error);
  2576. const char *get_header_value(const Headers &headers, const std::string &key,
  2577. const char *def, size_t id);
  2578. std::string params_to_query_str(const Params &params);
  2579. void parse_query_text(const char *data, std::size_t size, Params &params);
  2580. void parse_query_text(const std::string &s, Params &params);
  2581. bool parse_multipart_boundary(const std::string &content_type,
  2582. std::string &boundary);
  2583. bool parse_range_header(const std::string &s, Ranges &ranges);
  2584. bool parse_accept_header(const std::string &s,
  2585. std::vector<std::string> &content_types);
  2586. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2587. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2588. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2589. EncodingType encoding_type(const Request &req, const Response &res);
  2590. class BufferStream final : public Stream {
  2591. public:
  2592. BufferStream() = default;
  2593. ~BufferStream() override = default;
  2594. bool is_readable() const override;
  2595. bool wait_readable() const override;
  2596. bool wait_writable() const override;
  2597. ssize_t read(char *ptr, size_t size) override;
  2598. ssize_t write(const char *ptr, size_t size) override;
  2599. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2600. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2601. socket_t socket() const override;
  2602. time_t duration() const override;
  2603. const std::string &get_buffer() const;
  2604. private:
  2605. std::string buffer;
  2606. size_t position = 0;
  2607. };
  2608. class compressor {
  2609. public:
  2610. virtual ~compressor() = default;
  2611. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2612. virtual bool compress(const char *data, size_t data_length, bool last,
  2613. Callback callback) = 0;
  2614. };
  2615. class decompressor {
  2616. public:
  2617. virtual ~decompressor() = default;
  2618. virtual bool is_valid() const = 0;
  2619. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2620. virtual bool decompress(const char *data, size_t data_length,
  2621. Callback callback) = 0;
  2622. };
  2623. class nocompressor final : public compressor {
  2624. public:
  2625. ~nocompressor() override = default;
  2626. bool compress(const char *data, size_t data_length, bool /*last*/,
  2627. Callback callback) override;
  2628. };
  2629. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2630. class gzip_compressor final : public compressor {
  2631. public:
  2632. gzip_compressor();
  2633. ~gzip_compressor() override;
  2634. bool compress(const char *data, size_t data_length, bool last,
  2635. Callback callback) override;
  2636. private:
  2637. bool is_valid_ = false;
  2638. z_stream strm_;
  2639. };
  2640. class gzip_decompressor final : public decompressor {
  2641. public:
  2642. gzip_decompressor();
  2643. ~gzip_decompressor() override;
  2644. bool is_valid() const override;
  2645. bool decompress(const char *data, size_t data_length,
  2646. Callback callback) override;
  2647. private:
  2648. bool is_valid_ = false;
  2649. z_stream strm_;
  2650. };
  2651. #endif
  2652. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2653. class brotli_compressor final : public compressor {
  2654. public:
  2655. brotli_compressor();
  2656. ~brotli_compressor();
  2657. bool compress(const char *data, size_t data_length, bool last,
  2658. Callback callback) override;
  2659. private:
  2660. BrotliEncoderState *state_ = nullptr;
  2661. };
  2662. class brotli_decompressor final : public decompressor {
  2663. public:
  2664. brotli_decompressor();
  2665. ~brotli_decompressor();
  2666. bool is_valid() const override;
  2667. bool decompress(const char *data, size_t data_length,
  2668. Callback callback) override;
  2669. private:
  2670. BrotliDecoderResult decoder_r;
  2671. BrotliDecoderState *decoder_s = nullptr;
  2672. };
  2673. #endif
  2674. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2675. class zstd_compressor : public compressor {
  2676. public:
  2677. zstd_compressor();
  2678. ~zstd_compressor();
  2679. bool compress(const char *data, size_t data_length, bool last,
  2680. Callback callback) override;
  2681. private:
  2682. ZSTD_CCtx *ctx_ = nullptr;
  2683. };
  2684. class zstd_decompressor : public decompressor {
  2685. public:
  2686. zstd_decompressor();
  2687. ~zstd_decompressor();
  2688. bool is_valid() const override;
  2689. bool decompress(const char *data, size_t data_length,
  2690. Callback callback) override;
  2691. private:
  2692. ZSTD_DCtx *ctx_ = nullptr;
  2693. };
  2694. #endif
  2695. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2696. // to store data. The call can set memory on stack for performance.
  2697. class stream_line_reader {
  2698. public:
  2699. stream_line_reader(Stream &strm, char *fixed_buffer,
  2700. size_t fixed_buffer_size);
  2701. const char *ptr() const;
  2702. size_t size() const;
  2703. bool end_with_crlf() const;
  2704. bool getline();
  2705. private:
  2706. void append(char c);
  2707. Stream &strm_;
  2708. char *fixed_buffer_;
  2709. const size_t fixed_buffer_size_;
  2710. size_t fixed_buffer_used_size_ = 0;
  2711. std::string growable_buffer_;
  2712. };
  2713. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2714. const Headers &src_headers);
  2715. struct ChunkedDecoder {
  2716. Stream &strm;
  2717. size_t chunk_remaining = 0;
  2718. bool finished = false;
  2719. char line_buf[64];
  2720. size_t last_chunk_total = 0;
  2721. size_t last_chunk_offset = 0;
  2722. explicit ChunkedDecoder(Stream &s);
  2723. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2724. size_t &out_chunk_total);
  2725. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2726. };
  2727. class mmap {
  2728. public:
  2729. mmap(const char *path);
  2730. ~mmap();
  2731. bool open(const char *path);
  2732. void close();
  2733. bool is_open() const;
  2734. size_t size() const;
  2735. const char *data() const;
  2736. private:
  2737. #if defined(_WIN32)
  2738. HANDLE hFile_ = NULL;
  2739. HANDLE hMapping_ = NULL;
  2740. #else
  2741. int fd_ = -1;
  2742. #endif
  2743. size_t size_ = 0;
  2744. void *addr_ = nullptr;
  2745. bool is_open_empty_file = false;
  2746. };
  2747. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2748. namespace fields {
  2749. bool is_token_char(char c);
  2750. bool is_token(const std::string &s);
  2751. bool is_field_name(const std::string &s);
  2752. bool is_vchar(char c);
  2753. bool is_obs_text(char c);
  2754. bool is_field_vchar(char c);
  2755. bool is_field_content(const std::string &s);
  2756. bool is_field_value(const std::string &s);
  2757. } // namespace fields
  2758. } // namespace detail
  2759. /*
  2760. * TLS Abstraction Layer Declarations
  2761. */
  2762. #ifdef CPPHTTPLIB_SSL_ENABLED
  2763. // TLS abstraction layer - backend-specific type declarations
  2764. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2765. namespace tls {
  2766. namespace impl {
  2767. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2768. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2769. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2770. struct MbedTlsContext {
  2771. mbedtls_ssl_config conf;
  2772. mbedtls_entropy_context entropy;
  2773. mbedtls_ctr_drbg_context ctr_drbg;
  2774. mbedtls_x509_crt ca_chain;
  2775. mbedtls_x509_crt own_cert;
  2776. mbedtls_pk_context own_key;
  2777. bool is_server = false;
  2778. bool verify_client = false;
  2779. bool has_verify_callback = false;
  2780. MbedTlsContext();
  2781. ~MbedTlsContext();
  2782. MbedTlsContext(const MbedTlsContext &) = delete;
  2783. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2784. };
  2785. } // namespace impl
  2786. } // namespace tls
  2787. #endif
  2788. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2789. namespace tls {
  2790. namespace impl {
  2791. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2792. // This struct is accessible via tls::impl for use in SSL context
  2793. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2794. struct WolfSSLContext {
  2795. WOLFSSL_CTX *ctx = nullptr;
  2796. bool is_server = false;
  2797. bool verify_client = false;
  2798. bool has_verify_callback = false;
  2799. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2800. WolfSSLContext();
  2801. ~WolfSSLContext();
  2802. WolfSSLContext(const WolfSSLContext &) = delete;
  2803. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2804. };
  2805. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2806. struct WolfSSLCAStore {
  2807. std::string pem_data;
  2808. };
  2809. } // namespace impl
  2810. } // namespace tls
  2811. #endif
  2812. #endif // CPPHTTPLIB_SSL_ENABLED
  2813. namespace stream {
  2814. class Result {
  2815. public:
  2816. Result();
  2817. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2818. Result(Result &&other) noexcept;
  2819. Result &operator=(Result &&other) noexcept;
  2820. Result(const Result &) = delete;
  2821. Result &operator=(const Result &) = delete;
  2822. // Response info
  2823. bool is_valid() const;
  2824. explicit operator bool() const;
  2825. int status() const;
  2826. const Headers &headers() const;
  2827. std::string get_header_value(const std::string &key,
  2828. const char *def = "") const;
  2829. bool has_header(const std::string &key) const;
  2830. Error error() const;
  2831. Error read_error() const;
  2832. bool has_read_error() const;
  2833. // Stream reading
  2834. bool next();
  2835. const char *data() const;
  2836. size_t size() const;
  2837. std::string read_all();
  2838. private:
  2839. ClientImpl::StreamHandle handle_;
  2840. std::string buffer_;
  2841. size_t current_size_ = 0;
  2842. size_t chunk_size_;
  2843. bool finished_ = false;
  2844. };
  2845. // GET
  2846. template <typename ClientType>
  2847. inline Result Get(ClientType &cli, const std::string &path,
  2848. size_t chunk_size = 8192) {
  2849. return Result{cli.open_stream("GET", path), chunk_size};
  2850. }
  2851. template <typename ClientType>
  2852. inline Result Get(ClientType &cli, const std::string &path,
  2853. const Headers &headers, size_t chunk_size = 8192) {
  2854. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2855. }
  2856. template <typename ClientType>
  2857. inline Result Get(ClientType &cli, const std::string &path,
  2858. const Params &params, size_t chunk_size = 8192) {
  2859. return Result{cli.open_stream("GET", path, params), chunk_size};
  2860. }
  2861. template <typename ClientType>
  2862. inline Result Get(ClientType &cli, const std::string &path,
  2863. const Params &params, const Headers &headers,
  2864. size_t chunk_size = 8192) {
  2865. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2866. }
  2867. // POST
  2868. template <typename ClientType>
  2869. inline Result Post(ClientType &cli, const std::string &path,
  2870. const std::string &body, const std::string &content_type,
  2871. size_t chunk_size = 8192) {
  2872. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2873. chunk_size};
  2874. }
  2875. template <typename ClientType>
  2876. inline Result Post(ClientType &cli, const std::string &path,
  2877. const Headers &headers, const std::string &body,
  2878. const std::string &content_type, size_t chunk_size = 8192) {
  2879. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2880. chunk_size};
  2881. }
  2882. template <typename ClientType>
  2883. inline Result Post(ClientType &cli, const std::string &path,
  2884. const Params &params, const std::string &body,
  2885. const std::string &content_type, size_t chunk_size = 8192) {
  2886. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2887. chunk_size};
  2888. }
  2889. template <typename ClientType>
  2890. inline Result Post(ClientType &cli, const std::string &path,
  2891. const Params &params, const Headers &headers,
  2892. const std::string &body, const std::string &content_type,
  2893. size_t chunk_size = 8192) {
  2894. return Result{
  2895. cli.open_stream("POST", path, params, headers, body, content_type),
  2896. chunk_size};
  2897. }
  2898. // PUT
  2899. template <typename ClientType>
  2900. inline Result Put(ClientType &cli, const std::string &path,
  2901. const std::string &body, const std::string &content_type,
  2902. size_t chunk_size = 8192) {
  2903. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2904. chunk_size};
  2905. }
  2906. template <typename ClientType>
  2907. inline Result Put(ClientType &cli, const std::string &path,
  2908. const Headers &headers, const std::string &body,
  2909. const std::string &content_type, size_t chunk_size = 8192) {
  2910. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2911. chunk_size};
  2912. }
  2913. template <typename ClientType>
  2914. inline Result Put(ClientType &cli, const std::string &path,
  2915. const Params &params, const std::string &body,
  2916. const std::string &content_type, size_t chunk_size = 8192) {
  2917. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2918. chunk_size};
  2919. }
  2920. template <typename ClientType>
  2921. inline Result Put(ClientType &cli, const std::string &path,
  2922. const Params &params, const Headers &headers,
  2923. const std::string &body, const std::string &content_type,
  2924. size_t chunk_size = 8192) {
  2925. return Result{
  2926. cli.open_stream("PUT", path, params, headers, body, content_type),
  2927. chunk_size};
  2928. }
  2929. // PATCH
  2930. template <typename ClientType>
  2931. inline Result Patch(ClientType &cli, const std::string &path,
  2932. const std::string &body, const std::string &content_type,
  2933. size_t chunk_size = 8192) {
  2934. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2935. chunk_size};
  2936. }
  2937. template <typename ClientType>
  2938. inline Result Patch(ClientType &cli, const std::string &path,
  2939. const Headers &headers, const std::string &body,
  2940. const std::string &content_type, size_t chunk_size = 8192) {
  2941. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2942. chunk_size};
  2943. }
  2944. template <typename ClientType>
  2945. inline Result Patch(ClientType &cli, const std::string &path,
  2946. const Params &params, const std::string &body,
  2947. const std::string &content_type, size_t chunk_size = 8192) {
  2948. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2949. chunk_size};
  2950. }
  2951. template <typename ClientType>
  2952. inline Result Patch(ClientType &cli, const std::string &path,
  2953. const Params &params, const Headers &headers,
  2954. const std::string &body, const std::string &content_type,
  2955. size_t chunk_size = 8192) {
  2956. return Result{
  2957. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2958. chunk_size};
  2959. }
  2960. // DELETE
  2961. template <typename ClientType>
  2962. inline Result Delete(ClientType &cli, const std::string &path,
  2963. size_t chunk_size = 8192) {
  2964. return Result{cli.open_stream("DELETE", path), chunk_size};
  2965. }
  2966. template <typename ClientType>
  2967. inline Result Delete(ClientType &cli, const std::string &path,
  2968. const Headers &headers, size_t chunk_size = 8192) {
  2969. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2970. }
  2971. template <typename ClientType>
  2972. inline Result Delete(ClientType &cli, const std::string &path,
  2973. const std::string &body, const std::string &content_type,
  2974. size_t chunk_size = 8192) {
  2975. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2976. chunk_size};
  2977. }
  2978. template <typename ClientType>
  2979. inline Result Delete(ClientType &cli, const std::string &path,
  2980. const Headers &headers, const std::string &body,
  2981. const std::string &content_type,
  2982. size_t chunk_size = 8192) {
  2983. return Result{
  2984. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2985. chunk_size};
  2986. }
  2987. template <typename ClientType>
  2988. inline Result Delete(ClientType &cli, const std::string &path,
  2989. const Params &params, size_t chunk_size = 8192) {
  2990. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2991. }
  2992. template <typename ClientType>
  2993. inline Result Delete(ClientType &cli, const std::string &path,
  2994. const Params &params, const Headers &headers,
  2995. size_t chunk_size = 8192) {
  2996. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2997. }
  2998. template <typename ClientType>
  2999. inline Result Delete(ClientType &cli, const std::string &path,
  3000. const Params &params, const std::string &body,
  3001. const std::string &content_type,
  3002. size_t chunk_size = 8192) {
  3003. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3004. chunk_size};
  3005. }
  3006. template <typename ClientType>
  3007. inline Result Delete(ClientType &cli, const std::string &path,
  3008. const Params &params, const Headers &headers,
  3009. const std::string &body, const std::string &content_type,
  3010. size_t chunk_size = 8192) {
  3011. return Result{
  3012. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3013. chunk_size};
  3014. }
  3015. // HEAD
  3016. template <typename ClientType>
  3017. inline Result Head(ClientType &cli, const std::string &path,
  3018. size_t chunk_size = 8192) {
  3019. return Result{cli.open_stream("HEAD", path), chunk_size};
  3020. }
  3021. template <typename ClientType>
  3022. inline Result Head(ClientType &cli, const std::string &path,
  3023. const Headers &headers, size_t chunk_size = 8192) {
  3024. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3025. }
  3026. template <typename ClientType>
  3027. inline Result Head(ClientType &cli, const std::string &path,
  3028. const Params &params, size_t chunk_size = 8192) {
  3029. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3030. }
  3031. template <typename ClientType>
  3032. inline Result Head(ClientType &cli, const std::string &path,
  3033. const Params &params, const Headers &headers,
  3034. size_t chunk_size = 8192) {
  3035. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3036. }
  3037. // OPTIONS
  3038. template <typename ClientType>
  3039. inline Result Options(ClientType &cli, const std::string &path,
  3040. size_t chunk_size = 8192) {
  3041. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3042. }
  3043. template <typename ClientType>
  3044. inline Result Options(ClientType &cli, const std::string &path,
  3045. const Headers &headers, size_t chunk_size = 8192) {
  3046. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3047. }
  3048. template <typename ClientType>
  3049. inline Result Options(ClientType &cli, const std::string &path,
  3050. const Params &params, size_t chunk_size = 8192) {
  3051. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3052. }
  3053. template <typename ClientType>
  3054. inline Result Options(ClientType &cli, const std::string &path,
  3055. const Params &params, const Headers &headers,
  3056. size_t chunk_size = 8192) {
  3057. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3058. }
  3059. } // namespace stream
  3060. namespace sse {
  3061. struct SSEMessage {
  3062. std::string event; // Event type (default: "message")
  3063. std::string data; // Event payload
  3064. std::string id; // Event ID for Last-Event-ID header
  3065. SSEMessage();
  3066. void clear();
  3067. };
  3068. class SSEClient {
  3069. public:
  3070. using MessageHandler = std::function<void(const SSEMessage &)>;
  3071. using ErrorHandler = std::function<void(Error)>;
  3072. using OpenHandler = std::function<void()>;
  3073. SSEClient(Client &client, const std::string &path);
  3074. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3075. ~SSEClient();
  3076. SSEClient(const SSEClient &) = delete;
  3077. SSEClient &operator=(const SSEClient &) = delete;
  3078. // Event handlers
  3079. SSEClient &on_message(MessageHandler handler);
  3080. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3081. SSEClient &on_open(OpenHandler handler);
  3082. SSEClient &on_error(ErrorHandler handler);
  3083. SSEClient &set_reconnect_interval(int ms);
  3084. SSEClient &set_max_reconnect_attempts(int n);
  3085. // Update headers (thread-safe)
  3086. SSEClient &set_headers(const Headers &headers);
  3087. // State accessors
  3088. bool is_connected() const;
  3089. const std::string &last_event_id() const;
  3090. // Blocking start - runs event loop with auto-reconnect
  3091. void start();
  3092. // Non-blocking start - runs in background thread
  3093. void start_async();
  3094. // Stop the client (thread-safe)
  3095. void stop();
  3096. private:
  3097. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3098. void run_event_loop();
  3099. void dispatch_event(const SSEMessage &msg);
  3100. bool should_reconnect(int count) const;
  3101. void wait_for_reconnect();
  3102. // Client and path
  3103. Client &client_;
  3104. std::string path_;
  3105. Headers headers_;
  3106. mutable std::mutex headers_mutex_;
  3107. // Callbacks
  3108. MessageHandler on_message_;
  3109. std::map<std::string, MessageHandler> event_handlers_;
  3110. OpenHandler on_open_;
  3111. ErrorHandler on_error_;
  3112. // Configuration
  3113. int reconnect_interval_ms_ = 3000;
  3114. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3115. // State
  3116. std::atomic<bool> running_{false};
  3117. std::atomic<bool> connected_{false};
  3118. std::string last_event_id_;
  3119. // Async support
  3120. std::thread async_thread_;
  3121. };
  3122. } // namespace sse
  3123. namespace ws {
  3124. enum class Opcode : uint8_t {
  3125. Continuation = 0x0,
  3126. Text = 0x1,
  3127. Binary = 0x2,
  3128. Close = 0x8,
  3129. Ping = 0x9,
  3130. Pong = 0xA,
  3131. };
  3132. enum class CloseStatus : uint16_t {
  3133. Normal = 1000,
  3134. GoingAway = 1001,
  3135. ProtocolError = 1002,
  3136. UnsupportedData = 1003,
  3137. NoStatus = 1005,
  3138. Abnormal = 1006,
  3139. InvalidPayload = 1007,
  3140. PolicyViolation = 1008,
  3141. MessageTooBig = 1009,
  3142. MandatoryExtension = 1010,
  3143. InternalError = 1011,
  3144. };
  3145. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3146. class WebSocket {
  3147. public:
  3148. WebSocket(const WebSocket &) = delete;
  3149. WebSocket &operator=(const WebSocket &) = delete;
  3150. ~WebSocket();
  3151. ReadResult read(std::string &msg);
  3152. bool send(const std::string &data);
  3153. bool send(const char *data, size_t len);
  3154. void close(CloseStatus status = CloseStatus::Normal,
  3155. const std::string &reason = "");
  3156. const Request &request() const;
  3157. bool is_open() const;
  3158. private:
  3159. friend class httplib::Server;
  3160. friend class WebSocketClient;
  3161. WebSocket(
  3162. Stream &strm, const Request &req, bool is_server,
  3163. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3164. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3165. : strm_(strm), req_(req), is_server_(is_server),
  3166. ping_interval_sec_(ping_interval_sec),
  3167. max_missed_pongs_(max_missed_pongs) {
  3168. start_heartbeat();
  3169. }
  3170. WebSocket(
  3171. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3172. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3173. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3174. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3175. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3176. max_missed_pongs_(max_missed_pongs) {
  3177. start_heartbeat();
  3178. }
  3179. void start_heartbeat();
  3180. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3181. Stream &strm_;
  3182. std::unique_ptr<Stream> owned_strm_;
  3183. Request req_;
  3184. bool is_server_;
  3185. time_t ping_interval_sec_;
  3186. int max_missed_pongs_;
  3187. int unacked_pings_ = 0;
  3188. std::atomic<bool> closed_{false};
  3189. std::mutex write_mutex_;
  3190. std::thread ping_thread_;
  3191. std::mutex ping_mutex_;
  3192. std::condition_variable ping_cv_;
  3193. };
  3194. class WebSocketClient {
  3195. public:
  3196. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3197. const Headers &headers = {});
  3198. ~WebSocketClient();
  3199. WebSocketClient(const WebSocketClient &) = delete;
  3200. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3201. bool is_valid() const;
  3202. bool connect();
  3203. ReadResult read(std::string &msg);
  3204. bool send(const std::string &data);
  3205. bool send(const char *data, size_t len);
  3206. void close(CloseStatus status = CloseStatus::Normal,
  3207. const std::string &reason = "");
  3208. bool is_open() const;
  3209. const std::string &subprotocol() const;
  3210. void set_read_timeout(time_t sec, time_t usec = 0);
  3211. void set_write_timeout(time_t sec, time_t usec = 0);
  3212. void set_websocket_ping_interval(time_t sec);
  3213. void set_websocket_max_missed_pongs(int count);
  3214. void set_tcp_nodelay(bool on);
  3215. void set_address_family(int family);
  3216. void set_ipv6_v6only(bool on);
  3217. void set_socket_options(SocketOptions socket_options);
  3218. void set_connection_timeout(time_t sec, time_t usec = 0);
  3219. void set_interface(const std::string &intf);
  3220. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3221. #ifdef CPPHTTPLIB_SSL_ENABLED
  3222. void set_ca_cert_path(const std::string &path);
  3223. void set_ca_cert_store(tls::ca_store_t store);
  3224. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3225. void enable_server_certificate_verification(bool enabled);
  3226. void enable_system_ca(bool enabled);
  3227. #endif
  3228. private:
  3229. void shutdown_and_close();
  3230. bool create_stream(std::unique_ptr<Stream> &strm);
  3231. std::string host_;
  3232. int port_;
  3233. std::string path_;
  3234. Headers headers_;
  3235. std::string subprotocol_;
  3236. bool is_valid_ = false;
  3237. socket_t sock_ = INVALID_SOCKET;
  3238. std::unique_ptr<WebSocket> ws_;
  3239. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3240. time_t read_timeout_usec_ = 0;
  3241. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3242. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3243. time_t websocket_ping_interval_sec_ =
  3244. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3245. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3246. int address_family_ = AF_UNSPEC;
  3247. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3248. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3249. SocketOptions socket_options_ = nullptr;
  3250. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3251. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3252. std::string interface_;
  3253. // Hostname-IP map
  3254. std::map<std::string, std::string> addr_map_;
  3255. #ifdef CPPHTTPLIB_SSL_ENABLED
  3256. bool is_ssl_ = false;
  3257. tls::ctx_t tls_ctx_ = nullptr;
  3258. tls::session_t tls_session_ = nullptr;
  3259. std::string ca_cert_file_path_;
  3260. bool custom_ca_loaded_ = false;
  3261. bool certs_loaded_ = false;
  3262. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3263. bool server_certificate_verification_ = true;
  3264. #endif
  3265. };
  3266. namespace impl {
  3267. bool is_valid_utf8(const std::string &s);
  3268. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3269. bool &fin, bool expect_masked, size_t max_len);
  3270. } // namespace impl
  3271. } // namespace ws
  3272. // ----------------------------------------------------------------------------
  3273. /*
  3274. * Implementation that will be part of the .cc file if split into .h + .cc.
  3275. */
  3276. namespace stream {
  3277. // stream::Result implementations
  3278. inline Result::Result() : chunk_size_(8192) {}
  3279. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3280. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3281. inline Result::Result(Result &&other) noexcept
  3282. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3283. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3284. finished_(other.finished_) {
  3285. other.current_size_ = 0;
  3286. other.finished_ = true;
  3287. }
  3288. inline Result &Result::operator=(Result &&other) noexcept {
  3289. if (this != &other) {
  3290. handle_ = std::move(other.handle_);
  3291. buffer_ = std::move(other.buffer_);
  3292. current_size_ = other.current_size_;
  3293. chunk_size_ = other.chunk_size_;
  3294. finished_ = other.finished_;
  3295. other.current_size_ = 0;
  3296. other.finished_ = true;
  3297. }
  3298. return *this;
  3299. }
  3300. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3301. inline Result::operator bool() const { return is_valid(); }
  3302. inline int Result::status() const {
  3303. return handle_.response ? handle_.response->status : -1;
  3304. }
  3305. inline const Headers &Result::headers() const {
  3306. static const Headers empty_headers;
  3307. return handle_.response ? handle_.response->headers : empty_headers;
  3308. }
  3309. inline std::string Result::get_header_value(const std::string &key,
  3310. const char *def) const {
  3311. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3312. }
  3313. inline bool Result::has_header(const std::string &key) const {
  3314. return handle_.response ? handle_.response->has_header(key) : false;
  3315. }
  3316. inline Error Result::error() const { return handle_.error; }
  3317. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3318. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3319. inline bool Result::next() {
  3320. if (!handle_.is_valid() || finished_) { return false; }
  3321. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3322. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3323. if (n > 0) {
  3324. current_size_ = static_cast<size_t>(n);
  3325. return true;
  3326. }
  3327. current_size_ = 0;
  3328. finished_ = true;
  3329. return false;
  3330. }
  3331. inline const char *Result::data() const { return buffer_.data(); }
  3332. inline size_t Result::size() const { return current_size_; }
  3333. inline std::string Result::read_all() {
  3334. std::string result;
  3335. while (next()) {
  3336. result.append(data(), size());
  3337. }
  3338. return result;
  3339. }
  3340. } // namespace stream
  3341. namespace sse {
  3342. // SSEMessage implementations
  3343. inline SSEMessage::SSEMessage() : event("message") {}
  3344. inline void SSEMessage::clear() {
  3345. event = "message";
  3346. data.clear();
  3347. id.clear();
  3348. }
  3349. // SSEClient implementations
  3350. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3351. : client_(client), path_(path) {}
  3352. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3353. const Headers &headers)
  3354. : client_(client), path_(path), headers_(headers) {}
  3355. inline SSEClient::~SSEClient() { stop(); }
  3356. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3357. on_message_ = std::move(handler);
  3358. return *this;
  3359. }
  3360. inline SSEClient &SSEClient::on_event(const std::string &type,
  3361. MessageHandler handler) {
  3362. event_handlers_[type] = std::move(handler);
  3363. return *this;
  3364. }
  3365. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3366. on_open_ = std::move(handler);
  3367. return *this;
  3368. }
  3369. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3370. on_error_ = std::move(handler);
  3371. return *this;
  3372. }
  3373. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3374. reconnect_interval_ms_ = ms;
  3375. return *this;
  3376. }
  3377. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3378. max_reconnect_attempts_ = n;
  3379. return *this;
  3380. }
  3381. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3382. std::lock_guard<std::mutex> lock(headers_mutex_);
  3383. headers_ = headers;
  3384. return *this;
  3385. }
  3386. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3387. inline const std::string &SSEClient::last_event_id() const {
  3388. return last_event_id_;
  3389. }
  3390. inline void SSEClient::start() {
  3391. running_.store(true);
  3392. run_event_loop();
  3393. }
  3394. inline void SSEClient::start_async() {
  3395. running_.store(true);
  3396. async_thread_ = std::thread([this]() { run_event_loop(); });
  3397. }
  3398. inline void SSEClient::stop() {
  3399. running_.store(false);
  3400. client_.stop(); // Cancel any pending operations
  3401. if (async_thread_.joinable()) { async_thread_.join(); }
  3402. }
  3403. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3404. int &retry_ms) {
  3405. // Blank line signals end of event
  3406. if (line.empty() || line == "\r") { return true; }
  3407. // Lines starting with ':' are comments (ignored)
  3408. if (!line.empty() && line[0] == ':') { return false; }
  3409. // Find the colon separator
  3410. auto colon_pos = line.find(':');
  3411. if (colon_pos == std::string::npos) {
  3412. // Line with no colon is treated as field name with empty value
  3413. return false;
  3414. }
  3415. auto field = line.substr(0, colon_pos);
  3416. std::string value;
  3417. // Value starts after colon, skip optional single space
  3418. if (colon_pos + 1 < line.size()) {
  3419. auto value_start = colon_pos + 1;
  3420. if (line[value_start] == ' ') { value_start++; }
  3421. value = line.substr(value_start);
  3422. // Remove trailing \r if present
  3423. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3424. }
  3425. // Handle known fields
  3426. if (field == "event") {
  3427. msg.event = value;
  3428. } else if (field == "data") {
  3429. // Multiple data lines are concatenated with newlines
  3430. if (!msg.data.empty()) { msg.data += "\n"; }
  3431. msg.data += value;
  3432. } else if (field == "id") {
  3433. // Empty id is valid (clears the last event ID)
  3434. msg.id = value;
  3435. } else if (field == "retry") {
  3436. // Parse retry interval in milliseconds
  3437. {
  3438. int v = 0;
  3439. auto res =
  3440. detail::from_chars(value.data(), value.data() + value.size(), v);
  3441. if (res.ec == std::errc{}) { retry_ms = v; }
  3442. }
  3443. }
  3444. // Unknown fields are ignored per SSE spec
  3445. return false;
  3446. }
  3447. inline void SSEClient::run_event_loop() {
  3448. auto reconnect_count = 0;
  3449. while (running_.load()) {
  3450. // Build headers, including Last-Event-ID if we have one
  3451. Headers request_headers;
  3452. {
  3453. std::lock_guard<std::mutex> lock(headers_mutex_);
  3454. request_headers = headers_;
  3455. }
  3456. if (!last_event_id_.empty()) {
  3457. request_headers.emplace("Last-Event-ID", last_event_id_);
  3458. }
  3459. // Open streaming connection
  3460. auto result = stream::Get(client_, path_, request_headers);
  3461. // Connection error handling
  3462. if (!result) {
  3463. connected_.store(false);
  3464. if (on_error_) { on_error_(result.error()); }
  3465. if (!should_reconnect(reconnect_count)) { break; }
  3466. wait_for_reconnect();
  3467. reconnect_count++;
  3468. continue;
  3469. }
  3470. if (result.status() != StatusCode::OK_200) {
  3471. connected_.store(false);
  3472. if (on_error_) { on_error_(Error::Connection); }
  3473. // For certain errors, don't reconnect.
  3474. // Note: 401 is intentionally absent so that handlers can refresh
  3475. // credentials via set_headers() and let the client reconnect.
  3476. if (result.status() == StatusCode::NoContent_204 ||
  3477. result.status() == StatusCode::NotFound_404 ||
  3478. result.status() == StatusCode::Forbidden_403) {
  3479. break;
  3480. }
  3481. if (!should_reconnect(reconnect_count)) { break; }
  3482. wait_for_reconnect();
  3483. reconnect_count++;
  3484. continue;
  3485. }
  3486. // Connection successful
  3487. connected_.store(true);
  3488. reconnect_count = 0;
  3489. if (on_open_) { on_open_(); }
  3490. // Event receiving loop
  3491. std::string buffer;
  3492. SSEMessage current_msg;
  3493. while (running_.load() && result.next()) {
  3494. buffer.append(result.data(), result.size());
  3495. // Process complete lines in the buffer
  3496. size_t line_start = 0;
  3497. size_t newline_pos;
  3498. while ((newline_pos = buffer.find('\n', line_start)) !=
  3499. std::string::npos) {
  3500. auto line = buffer.substr(line_start, newline_pos - line_start);
  3501. line_start = newline_pos + 1;
  3502. // Parse the line and check if event is complete
  3503. auto event_complete =
  3504. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3505. if (event_complete && !current_msg.data.empty()) {
  3506. // Update last_event_id for reconnection
  3507. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3508. // Dispatch event to appropriate handler
  3509. dispatch_event(current_msg);
  3510. current_msg.clear();
  3511. }
  3512. }
  3513. // Keep unprocessed data in buffer
  3514. buffer.erase(0, line_start);
  3515. }
  3516. // Connection ended
  3517. connected_.store(false);
  3518. if (!running_.load()) { break; }
  3519. // Check for read errors
  3520. if (result.has_read_error()) {
  3521. if (on_error_) { on_error_(result.read_error()); }
  3522. }
  3523. if (!should_reconnect(reconnect_count)) { break; }
  3524. wait_for_reconnect();
  3525. reconnect_count++;
  3526. }
  3527. connected_.store(false);
  3528. }
  3529. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3530. // Check for specific event type handler first
  3531. auto it = event_handlers_.find(msg.event);
  3532. if (it != event_handlers_.end()) {
  3533. it->second(msg);
  3534. return;
  3535. }
  3536. // Fall back to generic message handler
  3537. if (on_message_) { on_message_(msg); }
  3538. }
  3539. inline bool SSEClient::should_reconnect(int count) const {
  3540. if (!running_.load()) { return false; }
  3541. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3542. return count < max_reconnect_attempts_;
  3543. }
  3544. inline void SSEClient::wait_for_reconnect() {
  3545. // Use small increments to check running_ flag frequently
  3546. auto waited = 0;
  3547. while (running_.load() && waited < reconnect_interval_ms_) {
  3548. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3549. waited += 100;
  3550. }
  3551. }
  3552. } // namespace sse
  3553. #ifdef CPPHTTPLIB_SSL_ENABLED
  3554. /*
  3555. * TLS abstraction layer - internal function declarations
  3556. * These are implementation details and not part of the public API.
  3557. */
  3558. namespace tls {
  3559. // Client context
  3560. ctx_t create_client_context();
  3561. void free_context(ctx_t ctx);
  3562. bool set_min_version(ctx_t ctx, Version version);
  3563. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3564. bool load_ca_file(ctx_t ctx, const char *file_path);
  3565. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3566. bool load_system_certs(ctx_t ctx);
  3567. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3568. const char *password);
  3569. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3570. const char *key_path, const char *password);
  3571. // Server context
  3572. ctx_t create_server_context();
  3573. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3574. const char *password);
  3575. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3576. const char *key_path, const char *password);
  3577. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3578. void set_verify_client(ctx_t ctx, bool require);
  3579. // Session management
  3580. session_t create_session(ctx_t ctx, socket_t sock);
  3581. void free_session(session_t session);
  3582. bool set_sni(session_t session, const char *hostname);
  3583. bool set_hostname(session_t session, const char *hostname);
  3584. // Handshake (non-blocking capable)
  3585. TlsError connect(session_t session);
  3586. TlsError accept(session_t session);
  3587. // Handshake with timeout (blocking until timeout)
  3588. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3589. time_t timeout_usec, TlsError *err);
  3590. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3591. time_t timeout_usec, TlsError *err);
  3592. // I/O (non-blocking capable)
  3593. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3594. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3595. int pending(const_session_t session);
  3596. void shutdown(session_t session, bool graceful);
  3597. // Connection state
  3598. bool is_peer_closed(session_t session, socket_t sock);
  3599. // Certificate verification
  3600. cert_t get_peer_cert(const_session_t session);
  3601. void free_cert(cert_t cert);
  3602. bool verify_hostname(cert_t cert, const char *hostname);
  3603. uint64_t hostname_mismatch_code();
  3604. long get_verify_result(const_session_t session);
  3605. // Certificate introspection
  3606. std::string get_cert_subject_cn(cert_t cert);
  3607. std::string get_cert_issuer_name(cert_t cert);
  3608. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3609. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3610. std::string get_cert_serial(cert_t cert);
  3611. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3612. const char *get_sni(const_session_t session);
  3613. // CA store management
  3614. ca_store_t create_ca_store(const char *pem, size_t len);
  3615. void free_ca_store(ca_store_t store);
  3616. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3617. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3618. std::vector<std::string> get_ca_names(ctx_t ctx);
  3619. // Dynamic certificate update (for servers)
  3620. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3621. const char *password);
  3622. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3623. // Certificate verification callback
  3624. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3625. long get_verify_error(const_session_t session);
  3626. std::string verify_error_string(long error_code);
  3627. // TlsError information
  3628. uint64_t peek_error();
  3629. uint64_t get_error();
  3630. std::string error_string(uint64_t code);
  3631. } // namespace tls
  3632. #endif // CPPHTTPLIB_SSL_ENABLED
  3633. /*
  3634. * Group 1: detail namespace - Non-SSL utilities
  3635. */
  3636. namespace detail {
  3637. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3638. const void *optval, socklen_t optlen) {
  3639. return setsockopt(sock, level, optname,
  3640. #ifdef _WIN32
  3641. reinterpret_cast<const char *>(optval),
  3642. #else
  3643. optval,
  3644. #endif
  3645. optlen) == 0;
  3646. }
  3647. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3648. time_t sec, time_t usec) {
  3649. #ifdef _WIN32
  3650. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3651. #else
  3652. timeval timeout;
  3653. timeout.tv_sec = static_cast<long>(sec);
  3654. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3655. #endif
  3656. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3657. }
  3658. inline bool is_hex(char c, int &v) {
  3659. if (isdigit(static_cast<unsigned char>(c))) {
  3660. v = c - '0';
  3661. return true;
  3662. } else if ('A' <= c && c <= 'F') {
  3663. v = c - 'A' + 10;
  3664. return true;
  3665. } else if ('a' <= c && c <= 'f') {
  3666. v = c - 'a' + 10;
  3667. return true;
  3668. }
  3669. return false;
  3670. }
  3671. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3672. int &val) {
  3673. if (i >= s.size()) { return false; }
  3674. val = 0;
  3675. for (; cnt; i++, cnt--) {
  3676. if (!s[i]) { return false; }
  3677. auto v = 0;
  3678. if (is_hex(s[i], v)) {
  3679. val = val * 16 + v;
  3680. } else {
  3681. return false;
  3682. }
  3683. }
  3684. return true;
  3685. }
  3686. inline std::string from_i_to_hex(size_t n) {
  3687. static const auto charset = "0123456789abcdef";
  3688. std::string ret;
  3689. do {
  3690. ret = charset[n & 15] + ret;
  3691. n >>= 4;
  3692. } while (n > 0);
  3693. return ret;
  3694. }
  3695. inline std::string compute_etag(const FileStat &fs) {
  3696. if (!fs.is_file()) { return std::string(); }
  3697. // If mtime cannot be determined (negative value indicates an error
  3698. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3699. // value like 0 could collide with a real file that legitimately has
  3700. // mtime == 0 (epoch) and lead to misleading validators.
  3701. auto mtime_raw = fs.mtime();
  3702. if (mtime_raw < 0) { return std::string(); }
  3703. auto mtime = static_cast<size_t>(mtime_raw);
  3704. auto size = fs.size();
  3705. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3706. from_i_to_hex(size) + "\"";
  3707. }
  3708. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3709. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3710. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3711. inline std::string file_mtime_to_http_date(time_t mtime) {
  3712. if (mtime < 0) { return std::string(); }
  3713. struct tm tm_buf;
  3714. #ifdef _WIN32
  3715. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3716. #else
  3717. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3718. #endif
  3719. char buf[64];
  3720. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3721. return std::string();
  3722. }
  3723. return std::string(buf);
  3724. }
  3725. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3726. inline time_t parse_http_date(const std::string &date_str) {
  3727. struct tm tm_buf;
  3728. // Create a classic locale object once for all parsing attempts
  3729. const std::locale classic_locale = std::locale::classic();
  3730. // Try to parse using std::get_time (C++11, cross-platform)
  3731. auto try_parse = [&](const char *fmt) -> bool {
  3732. std::istringstream ss(date_str);
  3733. ss.imbue(classic_locale);
  3734. memset(&tm_buf, 0, sizeof(tm_buf));
  3735. ss >> std::get_time(&tm_buf, fmt);
  3736. return !ss.fail();
  3737. };
  3738. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3739. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3740. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3741. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3742. // asctime format: "Sun Nov 6 08:49:37 1994"
  3743. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3744. return static_cast<time_t>(-1);
  3745. }
  3746. }
  3747. }
  3748. #ifdef _WIN32
  3749. return _mkgmtime(&tm_buf);
  3750. #elif defined _AIX
  3751. return mktime(&tm_buf);
  3752. #else
  3753. return timegm(&tm_buf);
  3754. #endif
  3755. }
  3756. inline bool is_weak_etag(const std::string &s) {
  3757. // Check if the string is a weak ETag (starts with 'W/"')
  3758. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3759. }
  3760. inline bool is_strong_etag(const std::string &s) {
  3761. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3762. // chars)
  3763. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3764. }
  3765. inline size_t to_utf8(int code, char *buff) {
  3766. if (code < 0x0080) {
  3767. buff[0] = static_cast<char>(code & 0x7F);
  3768. return 1;
  3769. } else if (code < 0x0800) {
  3770. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3771. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3772. return 2;
  3773. } else if (code < 0xD800) {
  3774. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3775. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3776. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3777. return 3;
  3778. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3779. return 0;
  3780. } else if (code < 0x10000) {
  3781. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3782. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3783. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3784. return 3;
  3785. } else if (code < 0x110000) {
  3786. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3787. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3788. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3789. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3790. return 4;
  3791. }
  3792. // NOTREACHED
  3793. return 0;
  3794. }
  3795. } // namespace detail
  3796. namespace ws {
  3797. namespace impl {
  3798. inline bool is_valid_utf8(const std::string &s) {
  3799. size_t i = 0;
  3800. auto n = s.size();
  3801. while (i < n) {
  3802. auto c = static_cast<unsigned char>(s[i]);
  3803. size_t len;
  3804. uint32_t cp;
  3805. if (c < 0x80) {
  3806. i++;
  3807. continue;
  3808. } else if ((c & 0xE0) == 0xC0) {
  3809. len = 2;
  3810. cp = c & 0x1F;
  3811. } else if ((c & 0xF0) == 0xE0) {
  3812. len = 3;
  3813. cp = c & 0x0F;
  3814. } else if ((c & 0xF8) == 0xF0) {
  3815. len = 4;
  3816. cp = c & 0x07;
  3817. } else {
  3818. return false;
  3819. }
  3820. if (i + len > n) { return false; }
  3821. for (size_t j = 1; j < len; j++) {
  3822. auto b = static_cast<unsigned char>(s[i + j]);
  3823. if ((b & 0xC0) != 0x80) { return false; }
  3824. cp = (cp << 6) | (b & 0x3F);
  3825. }
  3826. // Overlong encoding check
  3827. if (len == 2 && cp < 0x80) { return false; }
  3828. if (len == 3 && cp < 0x800) { return false; }
  3829. if (len == 4 && cp < 0x10000) { return false; }
  3830. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3831. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3832. if (cp > 0x10FFFF) { return false; }
  3833. i += len;
  3834. }
  3835. return true;
  3836. }
  3837. } // namespace impl
  3838. } // namespace ws
  3839. namespace detail {
  3840. // NOTE: This code came up with the following stackoverflow post:
  3841. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3842. inline std::string base64_encode(const std::string &in) {
  3843. static const auto lookup =
  3844. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3845. std::string out;
  3846. out.reserve(in.size());
  3847. // Unsigned: the accumulator is never masked, so with a signed int the
  3848. // `val << 8` below overflows once enough bytes are folded in (undefined
  3849. // behaviour before C++20). Only the low bits are ever emitted, so the
  3850. // wrap-around of an unsigned accumulator does not affect the output.
  3851. uint32_t val = 0;
  3852. auto valb = -6;
  3853. for (auto c : in) {
  3854. val = (val << 8) + static_cast<uint8_t>(c);
  3855. valb += 8;
  3856. while (valb >= 0) {
  3857. out.push_back(lookup[(val >> valb) & 0x3F]);
  3858. valb -= 6;
  3859. }
  3860. }
  3861. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3862. while (out.size() % 4) {
  3863. out.push_back('=');
  3864. }
  3865. return out;
  3866. }
  3867. inline std::string sha1(const std::string &input) {
  3868. // RFC 3174 SHA-1 implementation
  3869. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3870. return (x << n) | (x >> (32 - n));
  3871. };
  3872. uint32_t h0 = 0x67452301;
  3873. uint32_t h1 = 0xEFCDAB89;
  3874. uint32_t h2 = 0x98BADCFE;
  3875. uint32_t h3 = 0x10325476;
  3876. uint32_t h4 = 0xC3D2E1F0;
  3877. // Pre-processing: adding padding bits
  3878. std::string msg = input;
  3879. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3880. msg.push_back(static_cast<char>(0x80u));
  3881. while (msg.size() % 64 != 56) {
  3882. msg.push_back(0);
  3883. }
  3884. // Append original length in bits as 64-bit big-endian
  3885. for (int i = 56; i >= 0; i -= 8) {
  3886. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3887. }
  3888. // Process each 512-bit chunk
  3889. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3890. uint32_t w[80];
  3891. for (size_t i = 0; i < 16; i++) {
  3892. w[i] =
  3893. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3894. << 24) |
  3895. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3896. << 16) |
  3897. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3898. << 8) |
  3899. (static_cast<uint32_t>(
  3900. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3901. }
  3902. for (int i = 16; i < 80; i++) {
  3903. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3904. }
  3905. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3906. for (int i = 0; i < 80; i++) {
  3907. uint32_t f, k;
  3908. if (i < 20) {
  3909. f = (b & c) | ((~b) & d);
  3910. k = 0x5A827999;
  3911. } else if (i < 40) {
  3912. f = b ^ c ^ d;
  3913. k = 0x6ED9EBA1;
  3914. } else if (i < 60) {
  3915. f = (b & c) | (b & d) | (c & d);
  3916. k = 0x8F1BBCDC;
  3917. } else {
  3918. f = b ^ c ^ d;
  3919. k = 0xCA62C1D6;
  3920. }
  3921. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3922. e = d;
  3923. d = c;
  3924. c = left_rotate(b, 30);
  3925. b = a;
  3926. a = temp;
  3927. }
  3928. h0 += a;
  3929. h1 += b;
  3930. h2 += c;
  3931. h3 += d;
  3932. h4 += e;
  3933. }
  3934. // Produce the final hash as a 20-byte binary string
  3935. std::string hash(20, '\0');
  3936. for (size_t i = 0; i < 4; i++) {
  3937. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3938. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3939. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3940. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3941. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3942. }
  3943. return hash;
  3944. }
  3945. inline std::string websocket_accept_key(const std::string &client_key) {
  3946. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3947. return base64_encode(sha1(client_key + magic));
  3948. }
  3949. inline bool is_websocket_upgrade(const Request &req) {
  3950. if (req.method != "GET") { return false; }
  3951. // Check Upgrade: websocket (case-insensitive)
  3952. auto upgrade_it = req.headers.find("Upgrade");
  3953. if (upgrade_it == req.headers.end()) { return false; }
  3954. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3955. if (upgrade_val != "websocket") { return false; }
  3956. // Check Connection header contains "Upgrade"
  3957. auto connection_it = req.headers.find("Connection");
  3958. if (connection_it == req.headers.end()) { return false; }
  3959. auto connection_val = case_ignore::to_lower(connection_it->second);
  3960. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3961. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3962. // RFC 6455 Section 4.2.1
  3963. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3964. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3965. return false;
  3966. }
  3967. static const std::string b64chars =
  3968. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3969. for (size_t i = 0; i < 22; i++) {
  3970. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3971. }
  3972. // Check Sec-WebSocket-Version: 13
  3973. auto version = req.get_header_value("Sec-WebSocket-Version");
  3974. if (version != "13") { return false; }
  3975. return true;
  3976. }
  3977. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3978. const char *data, size_t len, bool fin,
  3979. bool mask) {
  3980. // First byte: FIN + opcode
  3981. uint8_t header[2];
  3982. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3983. (static_cast<uint8_t>(opcode) & 0x0F));
  3984. // Second byte: MASK + payload length
  3985. if (len < 126) {
  3986. header[1] = static_cast<uint8_t>(len);
  3987. if (mask) { header[1] |= 0x80; }
  3988. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3989. } else if (len <= 0xFFFF) {
  3990. header[1] = 126;
  3991. if (mask) { header[1] |= 0x80; }
  3992. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3993. uint8_t ext[2];
  3994. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  3995. ext[1] = static_cast<uint8_t>(len & 0xFF);
  3996. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  3997. } else {
  3998. header[1] = 127;
  3999. if (mask) { header[1] |= 0x80; }
  4000. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4001. uint8_t ext[8];
  4002. for (int i = 7; i >= 0; i--) {
  4003. ext[7 - i] =
  4004. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4005. }
  4006. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4007. }
  4008. if (mask) {
  4009. // Generate random mask key
  4010. thread_local std::mt19937 rng(std::random_device{}());
  4011. uint8_t mask_key[4];
  4012. auto r = rng();
  4013. std::memcpy(mask_key, &r, 4);
  4014. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4015. // Write masked payload in chunks
  4016. const size_t chunk_size = 4096;
  4017. std::vector<char> buf((std::min)(len, chunk_size));
  4018. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4019. size_t n = (std::min)(chunk_size, len - offset);
  4020. for (size_t i = 0; i < n; i++) {
  4021. buf[i] =
  4022. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4023. }
  4024. if (strm.write(buf.data(), n) < 0) { return false; }
  4025. }
  4026. } else {
  4027. if (len > 0) {
  4028. if (strm.write(data, len) < 0) { return false; }
  4029. }
  4030. }
  4031. return true;
  4032. }
  4033. } // namespace detail
  4034. namespace ws {
  4035. namespace impl {
  4036. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4037. std::string &payload, bool &fin,
  4038. bool expect_masked, size_t max_len) {
  4039. // Read first 2 bytes
  4040. uint8_t header[2];
  4041. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4042. fin = (header[0] & 0x80) != 0;
  4043. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4044. if (header[0] & 0x70) { return false; }
  4045. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4046. bool masked = (header[1] & 0x80) != 0;
  4047. uint64_t payload_len = header[1] & 0x7F;
  4048. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4049. // MUST have a payload length of 125 bytes or less
  4050. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4051. if (is_control) {
  4052. if (!fin) { return false; }
  4053. if (payload_len > 125) { return false; }
  4054. }
  4055. if (masked != expect_masked) { return false; }
  4056. // Extended payload length
  4057. if (payload_len == 126) {
  4058. uint8_t ext[2];
  4059. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4060. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4061. } else if (payload_len == 127) {
  4062. uint8_t ext[8];
  4063. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4064. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4065. if (ext[0] & 0x80) { return false; }
  4066. payload_len = 0;
  4067. for (int i = 0; i < 8; i++) {
  4068. payload_len = (payload_len << 8) | ext[i];
  4069. }
  4070. }
  4071. if (payload_len > max_len) { return false; }
  4072. // Read mask key if present
  4073. uint8_t mask_key[4] = {0};
  4074. if (masked) {
  4075. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4076. }
  4077. // Read payload
  4078. payload.resize(static_cast<size_t>(payload_len));
  4079. if (payload_len > 0) {
  4080. size_t total_read = 0;
  4081. while (total_read < payload_len) {
  4082. auto n = strm.read(&payload[total_read],
  4083. static_cast<size_t>(payload_len - total_read));
  4084. if (n <= 0) { return false; }
  4085. total_read += static_cast<size_t>(n);
  4086. }
  4087. }
  4088. // Unmask if needed
  4089. if (masked) {
  4090. for (size_t i = 0; i < payload.size(); i++) {
  4091. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4092. }
  4093. }
  4094. return true;
  4095. }
  4096. } // namespace impl
  4097. } // namespace ws
  4098. namespace detail {
  4099. inline bool is_valid_path(const std::string &path) {
  4100. size_t level = 0;
  4101. size_t i = 0;
  4102. // Skip slash
  4103. while (i < path.size() && path[i] == '/') {
  4104. i++;
  4105. }
  4106. while (i < path.size()) {
  4107. // Read component
  4108. auto beg = i;
  4109. while (i < path.size() && path[i] != '/') {
  4110. if (path[i] == '\0') {
  4111. return false;
  4112. } else if (path[i] == '\\') {
  4113. return false;
  4114. }
  4115. i++;
  4116. }
  4117. auto len = i - beg;
  4118. assert(len > 0);
  4119. if (!path.compare(beg, len, ".")) {
  4120. ;
  4121. } else if (!path.compare(beg, len, "..")) {
  4122. if (level == 0) { return false; }
  4123. level--;
  4124. } else {
  4125. level++;
  4126. }
  4127. // Skip slash
  4128. while (i < path.size() && path[i] == '/') {
  4129. i++;
  4130. }
  4131. }
  4132. return true;
  4133. }
  4134. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4135. #if defined(_WIN32)
  4136. char buf[_MAX_PATH];
  4137. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4138. resolved = buf;
  4139. #elif defined(PATH_MAX)
  4140. char buf[PATH_MAX];
  4141. if (realpath(path, buf) == nullptr) { return false; }
  4142. resolved = buf;
  4143. #else
  4144. auto buf = realpath(path, nullptr);
  4145. auto guard = scope_exit([&]() { std::free(buf); });
  4146. if (buf == nullptr) { return false; }
  4147. resolved = buf;
  4148. #endif
  4149. return true;
  4150. }
  4151. inline bool is_path_within_base(const std::string &resolved_path,
  4152. const std::string &resolved_base) {
  4153. #if defined(_WIN32)
  4154. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4155. resolved_base.size()) == 0;
  4156. #else
  4157. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4158. resolved_base.size()) == 0;
  4159. #endif
  4160. }
  4161. inline FileStat::FileStat(const std::string &path) {
  4162. #if defined(_WIN32)
  4163. auto wpath = u8string_to_wstring(path.c_str());
  4164. ret_ = _wstat(wpath.c_str(), &st_);
  4165. #else
  4166. ret_ = stat(path.c_str(), &st_);
  4167. #endif
  4168. }
  4169. inline bool FileStat::is_file() const {
  4170. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4171. }
  4172. inline bool FileStat::is_dir() const {
  4173. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4174. }
  4175. inline time_t FileStat::mtime() const {
  4176. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4177. : static_cast<time_t>(-1);
  4178. }
  4179. inline size_t FileStat::size() const {
  4180. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4181. }
  4182. inline std::string encode_path(const std::string &s) {
  4183. std::string result;
  4184. result.reserve(s.size());
  4185. for (size_t i = 0; s[i]; i++) {
  4186. switch (s[i]) {
  4187. case ' ': result += "%20"; break;
  4188. case '+': result += "%2B"; break;
  4189. case '\r': result += "%0D"; break;
  4190. case '\n': result += "%0A"; break;
  4191. case '\'': result += "%27"; break;
  4192. case ',': result += "%2C"; break;
  4193. // case ':': result += "%3A"; break; // ok? probably...
  4194. case ';': result += "%3B"; break;
  4195. default:
  4196. auto c = static_cast<uint8_t>(s[i]);
  4197. if (c >= 0x80) {
  4198. result += '%';
  4199. char hex[4];
  4200. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4201. assert(len == 2);
  4202. result.append(hex, static_cast<size_t>(len));
  4203. } else {
  4204. result += s[i];
  4205. }
  4206. break;
  4207. }
  4208. }
  4209. return result;
  4210. }
  4211. inline std::string file_extension(const std::string &path) {
  4212. std::smatch m;
  4213. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4214. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4215. return std::string();
  4216. }
  4217. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4218. template <typename T>
  4219. inline bool parse_header(const char *beg, const char *end, T fn);
  4220. template <typename T>
  4221. inline bool parse_header(const char *beg, const char *end, T fn) {
  4222. // Skip trailing spaces and tabs.
  4223. while (beg < end && is_space_or_tab(end[-1])) {
  4224. end--;
  4225. }
  4226. auto p = beg;
  4227. while (p < end && *p != ':') {
  4228. p++;
  4229. }
  4230. auto name = std::string(beg, p);
  4231. if (!detail::fields::is_field_name(name)) { return false; }
  4232. if (p == end) { return false; }
  4233. auto key_end = p;
  4234. if (*p++ != ':') { return false; }
  4235. while (p < end && is_space_or_tab(*p)) {
  4236. p++;
  4237. }
  4238. if (p <= end) {
  4239. auto key_len = key_end - beg;
  4240. if (!key_len) { return false; }
  4241. auto key = std::string(beg, key_end);
  4242. auto val = std::string(p, end);
  4243. if (!detail::fields::is_field_value(val)) { return false; }
  4244. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4245. // percent-decoded by the recipient. Applications that need to interpret a
  4246. // value as a URI component should call httplib::decode_uri_component()
  4247. // (or decode_path_component()) explicitly.
  4248. fn(key, val);
  4249. return true;
  4250. }
  4251. return false;
  4252. }
  4253. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4254. const Headers &src_headers) {
  4255. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4256. // transfer coding is complete when a chunk with a chunk-size of zero is
  4257. // received, possibly followed by a trailer section, and finally terminated by
  4258. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4259. //
  4260. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4261. // doesn't care for the existence of the final CRLF. In other words, it seems
  4262. // to be ok whether the final CRLF exists or not in the chunked data.
  4263. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4264. //
  4265. // According to the reference code in RFC 9112, cpp-httplib now allows
  4266. // chunked transfer coding data without the final CRLF.
  4267. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4268. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4269. "transfer-encoding",
  4270. "content-length",
  4271. "host",
  4272. "authorization",
  4273. "www-authenticate",
  4274. "proxy-authenticate",
  4275. "proxy-authorization",
  4276. "cookie",
  4277. "set-cookie",
  4278. "cache-control",
  4279. "expect",
  4280. "max-forwards",
  4281. "pragma",
  4282. "range",
  4283. "te",
  4284. "age",
  4285. "expires",
  4286. "date",
  4287. "location",
  4288. "retry-after",
  4289. "vary",
  4290. "warning",
  4291. "content-encoding",
  4292. "content-type",
  4293. "content-range",
  4294. "trailer"};
  4295. case_ignore::unordered_set<std::string> declared_trailers;
  4296. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4297. if (trailer_header && std::strlen(trailer_header)) {
  4298. auto len = std::strlen(trailer_header);
  4299. split(trailer_header, trailer_header + len, ',',
  4300. [&](const char *b, const char *e) {
  4301. const char *kbeg = b;
  4302. const char *kend = e;
  4303. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4304. ++kbeg;
  4305. }
  4306. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4307. --kend;
  4308. }
  4309. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4310. if (!key.empty() &&
  4311. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4312. declared_trailers.insert(key);
  4313. }
  4314. });
  4315. }
  4316. size_t trailer_header_count = 0;
  4317. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4318. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4319. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4320. constexpr auto line_terminator_len = 2;
  4321. auto line_beg = line_reader.ptr();
  4322. auto line_end =
  4323. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4324. if (!parse_header(line_beg, line_end,
  4325. [&](const std::string &key, const std::string &val) {
  4326. if (declared_trailers.find(key) !=
  4327. declared_trailers.end()) {
  4328. dest.emplace(key, val);
  4329. trailer_header_count++;
  4330. }
  4331. })) {
  4332. return false;
  4333. }
  4334. if (!line_reader.getline()) { return false; }
  4335. }
  4336. return true;
  4337. }
  4338. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4339. size_t right) {
  4340. while (b + left < e && is_space_or_tab(b[left])) {
  4341. left++;
  4342. }
  4343. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4344. right--;
  4345. }
  4346. return std::make_pair(left, right);
  4347. }
  4348. inline std::string trim_copy(const std::string &s) {
  4349. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4350. return s.substr(r.first, r.second - r.first);
  4351. }
  4352. inline std::string trim_double_quotes_copy(const std::string &s) {
  4353. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4354. return s.substr(1, s.size() - 2);
  4355. }
  4356. return s;
  4357. }
  4358. inline void
  4359. divide(const char *data, std::size_t size, char d,
  4360. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4361. fn) {
  4362. const auto it = std::find(data, data + size, d);
  4363. const auto found = static_cast<std::size_t>(it != data + size);
  4364. const auto lhs_data = data;
  4365. const auto lhs_size = static_cast<std::size_t>(it - data);
  4366. const auto rhs_data = it + found;
  4367. const auto rhs_size = size - lhs_size - found;
  4368. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4369. }
  4370. inline void
  4371. divide(const std::string &str, char d,
  4372. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4373. fn) {
  4374. divide(str.data(), str.size(), d, std::move(fn));
  4375. }
  4376. inline void split(const char *b, const char *e, char d,
  4377. std::function<void(const char *, const char *)> fn) {
  4378. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4379. }
  4380. inline void split(const char *b, const char *e, char d, size_t m,
  4381. std::function<void(const char *, const char *)> fn) {
  4382. size_t i = 0;
  4383. size_t beg = 0;
  4384. size_t count = 1;
  4385. while (e ? (b + i < e) : (b[i] != '\0')) {
  4386. if (b[i] == d && count < m) {
  4387. auto r = trim(b, e, beg, i);
  4388. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4389. beg = i + 1;
  4390. count++;
  4391. }
  4392. i++;
  4393. }
  4394. if (i) {
  4395. auto r = trim(b, e, beg, i);
  4396. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4397. }
  4398. }
  4399. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4400. std::function<bool(const char *, const char *)> fn) {
  4401. size_t i = 0;
  4402. size_t beg = 0;
  4403. size_t count = 1;
  4404. while (e ? (b + i < e) : (b[i] != '\0')) {
  4405. if (b[i] == d && count < m) {
  4406. auto r = trim(b, e, beg, i);
  4407. if (r.first < r.second) {
  4408. auto found = fn(&b[r.first], &b[r.second]);
  4409. if (found) { return true; }
  4410. }
  4411. beg = i + 1;
  4412. count++;
  4413. }
  4414. i++;
  4415. }
  4416. if (i) {
  4417. auto r = trim(b, e, beg, i);
  4418. if (r.first < r.second) {
  4419. auto found = fn(&b[r.first], &b[r.second]);
  4420. if (found) { return true; }
  4421. }
  4422. }
  4423. return false;
  4424. }
  4425. inline bool split_find(const char *b, const char *e, char d,
  4426. std::function<bool(const char *, const char *)> fn) {
  4427. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4428. std::move(fn));
  4429. }
  4430. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4431. size_t fixed_buffer_size)
  4432. : strm_(strm), fixed_buffer_(fixed_buffer),
  4433. fixed_buffer_size_(fixed_buffer_size) {}
  4434. inline const char *stream_line_reader::ptr() const {
  4435. if (growable_buffer_.empty()) {
  4436. return fixed_buffer_;
  4437. } else {
  4438. return growable_buffer_.data();
  4439. }
  4440. }
  4441. inline size_t stream_line_reader::size() const {
  4442. if (growable_buffer_.empty()) {
  4443. return fixed_buffer_used_size_;
  4444. } else {
  4445. return growable_buffer_.size();
  4446. }
  4447. }
  4448. inline bool stream_line_reader::end_with_crlf() const {
  4449. auto end = ptr() + size();
  4450. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4451. }
  4452. inline bool stream_line_reader::getline() {
  4453. fixed_buffer_used_size_ = 0;
  4454. growable_buffer_.clear();
  4455. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4456. char prev_byte = 0;
  4457. #endif
  4458. for (size_t i = 0;; i++) {
  4459. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4460. // Treat exceptionally long lines as an error to
  4461. // prevent infinite loops/memory exhaustion
  4462. return false;
  4463. }
  4464. char byte;
  4465. auto n = strm_.read(&byte, 1);
  4466. if (n < 0) {
  4467. return false;
  4468. } else if (n == 0) {
  4469. if (i == 0) {
  4470. return false;
  4471. } else {
  4472. break;
  4473. }
  4474. }
  4475. append(byte);
  4476. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4477. if (byte == '\n') { break; }
  4478. #else
  4479. if (prev_byte == '\r' && byte == '\n') { break; }
  4480. prev_byte = byte;
  4481. #endif
  4482. }
  4483. return true;
  4484. }
  4485. inline void stream_line_reader::append(char c) {
  4486. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4487. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4488. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4489. } else {
  4490. if (growable_buffer_.empty()) {
  4491. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4492. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4493. }
  4494. growable_buffer_ += c;
  4495. }
  4496. }
  4497. inline mmap::mmap(const char *path) { open(path); }
  4498. inline mmap::~mmap() { close(); }
  4499. inline bool mmap::open(const char *path) {
  4500. close();
  4501. #if defined(_WIN32)
  4502. auto wpath = u8string_to_wstring(path);
  4503. if (wpath.empty()) { return false; }
  4504. hFile_ =
  4505. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4506. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4507. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4508. LARGE_INTEGER size{};
  4509. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4510. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4511. // See:
  4512. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4513. if (static_cast<ULONGLONG>(size.QuadPart) >
  4514. (std::numeric_limits<decltype(size_)>::max)()) {
  4515. // `size_t` might be 32-bits, on 32-bits Windows.
  4516. return false;
  4517. }
  4518. size_ = static_cast<size_t>(size.QuadPart);
  4519. hMapping_ =
  4520. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4521. // Special treatment for an empty file...
  4522. if (hMapping_ == NULL && size_ == 0) {
  4523. close();
  4524. is_open_empty_file = true;
  4525. return true;
  4526. }
  4527. if (hMapping_ == NULL) {
  4528. close();
  4529. return false;
  4530. }
  4531. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4532. if (addr_ == nullptr) {
  4533. close();
  4534. return false;
  4535. }
  4536. #else
  4537. fd_ = ::open(path, O_RDONLY);
  4538. if (fd_ == -1) { return false; }
  4539. struct stat sb;
  4540. if (fstat(fd_, &sb) == -1) {
  4541. close();
  4542. return false;
  4543. }
  4544. size_ = static_cast<size_t>(sb.st_size);
  4545. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4546. // Special treatment for an empty file...
  4547. if (addr_ == MAP_FAILED && size_ == 0) {
  4548. close();
  4549. is_open_empty_file = true;
  4550. return false;
  4551. }
  4552. #endif
  4553. return true;
  4554. }
  4555. inline bool mmap::is_open() const {
  4556. return is_open_empty_file ? true : addr_ != nullptr;
  4557. }
  4558. inline size_t mmap::size() const { return size_; }
  4559. inline const char *mmap::data() const {
  4560. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4561. }
  4562. inline void mmap::close() {
  4563. #if defined(_WIN32)
  4564. if (addr_) {
  4565. ::UnmapViewOfFile(addr_);
  4566. addr_ = nullptr;
  4567. }
  4568. if (hMapping_) {
  4569. ::CloseHandle(hMapping_);
  4570. hMapping_ = NULL;
  4571. }
  4572. if (hFile_ != INVALID_HANDLE_VALUE) {
  4573. ::CloseHandle(hFile_);
  4574. hFile_ = INVALID_HANDLE_VALUE;
  4575. }
  4576. is_open_empty_file = false;
  4577. #else
  4578. if (addr_ != nullptr) {
  4579. munmap(addr_, size_);
  4580. addr_ = nullptr;
  4581. }
  4582. if (fd_ != -1) {
  4583. ::close(fd_);
  4584. fd_ = -1;
  4585. }
  4586. #endif
  4587. size_ = 0;
  4588. }
  4589. inline int close_socket(socket_t sock) noexcept {
  4590. #ifdef _WIN32
  4591. return closesocket(sock);
  4592. #else
  4593. return close(sock);
  4594. #endif
  4595. }
  4596. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4597. ssize_t res = 0;
  4598. while (true) {
  4599. res = fn();
  4600. if (res < 0 && errno == EINTR) {
  4601. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4602. continue;
  4603. }
  4604. break;
  4605. }
  4606. return res;
  4607. }
  4608. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4609. return handle_EINTR([&]() {
  4610. return recv(sock,
  4611. #ifdef _WIN32
  4612. static_cast<char *>(ptr), static_cast<int>(size),
  4613. #else
  4614. ptr, size,
  4615. #endif
  4616. flags);
  4617. });
  4618. }
  4619. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4620. int flags) {
  4621. return handle_EINTR([&]() {
  4622. return send(sock,
  4623. #ifdef _WIN32
  4624. static_cast<const char *>(ptr), static_cast<int>(size),
  4625. #else
  4626. ptr, size,
  4627. #endif
  4628. flags);
  4629. });
  4630. }
  4631. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4632. #ifdef _WIN32
  4633. return ::WSAPoll(fds, nfds, timeout);
  4634. #else
  4635. return ::poll(fds, nfds, timeout);
  4636. #endif
  4637. }
  4638. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4639. time_t usec) {
  4640. struct pollfd pfd;
  4641. pfd.fd = sock;
  4642. pfd.events = events;
  4643. pfd.revents = 0;
  4644. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4645. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4646. }
  4647. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4648. return select_impl(sock, POLLIN, sec, usec);
  4649. }
  4650. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4651. return select_impl(sock, POLLOUT, sec, usec);
  4652. }
  4653. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4654. time_t usec) {
  4655. struct pollfd pfd_read;
  4656. pfd_read.fd = sock;
  4657. pfd_read.events = POLLIN | POLLOUT;
  4658. pfd_read.revents = 0;
  4659. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4660. auto poll_res =
  4661. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4662. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4663. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4664. auto error = 0;
  4665. socklen_t len = sizeof(error);
  4666. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4667. reinterpret_cast<char *>(&error), &len);
  4668. auto successful = res >= 0 && !error;
  4669. return successful ? Error::Success : Error::Connection;
  4670. }
  4671. return Error::Connection;
  4672. }
  4673. inline bool is_socket_alive(socket_t sock) {
  4674. const auto val = detail::select_read(sock, 0, 0);
  4675. if (val == 0) {
  4676. return true;
  4677. } else if (val < 0 && errno == EBADF) {
  4678. return false;
  4679. }
  4680. char buf[1];
  4681. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4682. }
  4683. class SocketStream final : public Stream {
  4684. public:
  4685. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4686. time_t write_timeout_sec, time_t write_timeout_usec,
  4687. time_t max_timeout_msec = 0,
  4688. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4689. (std::chrono::steady_clock::time_point::min)());
  4690. ~SocketStream() override;
  4691. bool is_readable() const override;
  4692. bool wait_readable() const override;
  4693. bool wait_writable() const override;
  4694. bool is_peer_alive() const override;
  4695. ssize_t read(char *ptr, size_t size) override;
  4696. ssize_t write(const char *ptr, size_t size) override;
  4697. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4698. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4699. socket_t socket() const override;
  4700. time_t duration() const override;
  4701. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4702. private:
  4703. socket_t sock_;
  4704. time_t read_timeout_sec_;
  4705. time_t read_timeout_usec_;
  4706. time_t write_timeout_sec_;
  4707. time_t write_timeout_usec_;
  4708. time_t max_timeout_msec_;
  4709. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4710. std::vector<char> read_buff_;
  4711. size_t read_buff_off_ = 0;
  4712. size_t read_buff_content_size_ = 0;
  4713. static const size_t read_buff_size_ = 1024l * 4;
  4714. };
  4715. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4716. time_t keep_alive_timeout_sec) {
  4717. using namespace std::chrono;
  4718. const auto interval_usec =
  4719. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4720. // Avoid expensive `steady_clock::now()` call for the first time
  4721. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4722. const auto start = steady_clock::now() - microseconds{interval_usec};
  4723. const auto timeout = seconds{keep_alive_timeout_sec};
  4724. while (true) {
  4725. if (svr_sock == INVALID_SOCKET) {
  4726. break; // Server socket is closed
  4727. }
  4728. auto val = select_read(sock, 0, interval_usec);
  4729. if (val < 0) {
  4730. break; // Ssocket error
  4731. } else if (val == 0) {
  4732. if (steady_clock::now() - start > timeout) {
  4733. break; // Timeout
  4734. }
  4735. } else {
  4736. return true; // Ready for read
  4737. }
  4738. }
  4739. return false;
  4740. }
  4741. template <typename T>
  4742. inline bool
  4743. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4744. size_t keep_alive_max_count,
  4745. time_t keep_alive_timeout_sec, T callback) {
  4746. assert(keep_alive_max_count > 0);
  4747. auto ret = false;
  4748. auto count = keep_alive_max_count;
  4749. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4750. auto close_connection = count == 1;
  4751. auto connection_closed = false;
  4752. ret = callback(close_connection, connection_closed);
  4753. if (!ret || connection_closed) { break; }
  4754. count--;
  4755. }
  4756. return ret;
  4757. }
  4758. template <typename T>
  4759. inline bool
  4760. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4761. size_t keep_alive_max_count,
  4762. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4763. time_t read_timeout_usec, time_t write_timeout_sec,
  4764. time_t write_timeout_usec, T callback) {
  4765. return process_server_socket_core(
  4766. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4767. [&](bool close_connection, bool &connection_closed) {
  4768. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4769. write_timeout_sec, write_timeout_usec);
  4770. return callback(strm, close_connection, connection_closed);
  4771. });
  4772. }
  4773. inline bool process_client_socket(
  4774. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4775. time_t write_timeout_sec, time_t write_timeout_usec,
  4776. time_t max_timeout_msec,
  4777. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4778. std::function<bool(Stream &)> callback) {
  4779. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4780. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4781. start_time);
  4782. return callback(strm);
  4783. }
  4784. inline int shutdown_socket(socket_t sock) noexcept {
  4785. #ifdef _WIN32
  4786. return shutdown(sock, SD_BOTH);
  4787. #else
  4788. return shutdown(sock, SHUT_RDWR);
  4789. #endif
  4790. }
  4791. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4792. if (s.size() > 1 && s[0] == '\0') {
  4793. auto ret = s;
  4794. ret[0] = '@';
  4795. return ret;
  4796. }
  4797. return s;
  4798. }
  4799. inline std::string
  4800. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4801. if (s.size() > 1 && s[0] == '@') {
  4802. auto ret = s;
  4803. ret[0] = '\0';
  4804. return ret;
  4805. }
  4806. return s;
  4807. }
  4808. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4809. const struct addrinfo *hints,
  4810. struct addrinfo **res, time_t timeout_sec) {
  4811. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4812. if (timeout_sec <= 0) {
  4813. // No timeout specified, use standard getaddrinfo
  4814. return getaddrinfo(node, service, hints, res);
  4815. }
  4816. #ifdef _WIN32
  4817. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4818. OVERLAPPED overlapped = {};
  4819. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4820. if (!event) { return EAI_FAIL; }
  4821. overlapped.hEvent = event;
  4822. PADDRINFOEXW result_addrinfo = nullptr;
  4823. HANDLE cancel_handle = nullptr;
  4824. ADDRINFOEXW hints_ex = {};
  4825. if (hints) {
  4826. hints_ex.ai_flags = hints->ai_flags;
  4827. hints_ex.ai_family = hints->ai_family;
  4828. hints_ex.ai_socktype = hints->ai_socktype;
  4829. hints_ex.ai_protocol = hints->ai_protocol;
  4830. }
  4831. auto wnode = u8string_to_wstring(node);
  4832. auto wservice = u8string_to_wstring(service);
  4833. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4834. hints ? &hints_ex : nullptr, &result_addrinfo,
  4835. nullptr, &overlapped, nullptr, &cancel_handle);
  4836. if (ret == WSA_IO_PENDING) {
  4837. auto wait_result =
  4838. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4839. if (wait_result == WAIT_TIMEOUT) {
  4840. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4841. ::CloseHandle(event);
  4842. return EAI_AGAIN;
  4843. }
  4844. DWORD bytes_returned;
  4845. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4846. &bytes_returned, FALSE)) {
  4847. ::CloseHandle(event);
  4848. return ::WSAGetLastError();
  4849. }
  4850. }
  4851. ::CloseHandle(event);
  4852. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4853. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4854. return 0;
  4855. }
  4856. return ret;
  4857. #elif TARGET_OS_MAC && defined(__clang__)
  4858. if (!node) { return EAI_NONAME; }
  4859. // macOS implementation using CFHost API for asynchronous DNS resolution
  4860. CFStringRef hostname_ref = CFStringCreateWithCString(
  4861. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4862. if (!hostname_ref) { return EAI_MEMORY; }
  4863. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4864. CFRelease(hostname_ref);
  4865. if (!host_ref) { return EAI_MEMORY; }
  4866. // Set up context for callback
  4867. struct CFHostContext {
  4868. bool completed = false;
  4869. bool success = false;
  4870. CFArrayRef addresses = nullptr;
  4871. std::mutex mutex;
  4872. std::condition_variable cv;
  4873. } context;
  4874. CFHostClientContext client_context;
  4875. memset(&client_context, 0, sizeof(client_context));
  4876. client_context.info = &context;
  4877. // Set callback
  4878. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4879. const CFStreamError *error, void *info) {
  4880. auto ctx = static_cast<CFHostContext *>(info);
  4881. std::lock_guard<std::mutex> lock(ctx->mutex);
  4882. if (error && error->error != 0) {
  4883. ctx->success = false;
  4884. } else {
  4885. Boolean hasBeenResolved;
  4886. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4887. if (ctx->addresses && hasBeenResolved) {
  4888. CFRetain(ctx->addresses);
  4889. ctx->success = true;
  4890. } else {
  4891. ctx->success = false;
  4892. }
  4893. }
  4894. ctx->completed = true;
  4895. ctx->cv.notify_one();
  4896. };
  4897. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4898. CFRelease(host_ref);
  4899. return EAI_SYSTEM;
  4900. }
  4901. // Schedule on run loop
  4902. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4903. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4904. // Start resolution
  4905. CFStreamError stream_error;
  4906. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4907. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4908. CFRelease(host_ref);
  4909. return EAI_FAIL;
  4910. }
  4911. // Wait for completion with timeout
  4912. auto timeout_time =
  4913. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4914. bool timed_out = false;
  4915. {
  4916. std::unique_lock<std::mutex> lock(context.mutex);
  4917. while (!context.completed) {
  4918. auto now = std::chrono::steady_clock::now();
  4919. if (now >= timeout_time) {
  4920. timed_out = true;
  4921. break;
  4922. }
  4923. // Run the runloop for a short time
  4924. lock.unlock();
  4925. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4926. lock.lock();
  4927. }
  4928. }
  4929. // Clean up
  4930. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4931. CFHostSetClient(host_ref, nullptr, nullptr);
  4932. if (timed_out || !context.completed) {
  4933. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4934. CFRelease(host_ref);
  4935. return EAI_AGAIN;
  4936. }
  4937. if (!context.success || !context.addresses) {
  4938. CFRelease(host_ref);
  4939. return EAI_NODATA;
  4940. }
  4941. // Convert CFArray to addrinfo
  4942. CFIndex count = CFArrayGetCount(context.addresses);
  4943. if (count == 0) {
  4944. CFRelease(context.addresses);
  4945. CFRelease(host_ref);
  4946. return EAI_NODATA;
  4947. }
  4948. struct addrinfo *result_addrinfo = nullptr;
  4949. struct addrinfo **current = &result_addrinfo;
  4950. for (CFIndex i = 0; i < count; i++) {
  4951. CFDataRef addr_data =
  4952. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4953. if (!addr_data) continue;
  4954. const struct sockaddr *sockaddr_ptr =
  4955. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4956. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4957. // Allocate addrinfo structure
  4958. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4959. if (!*current) {
  4960. freeaddrinfo(result_addrinfo);
  4961. CFRelease(context.addresses);
  4962. CFRelease(host_ref);
  4963. return EAI_MEMORY;
  4964. }
  4965. memset(*current, 0, sizeof(struct addrinfo));
  4966. // Set up addrinfo fields
  4967. (*current)->ai_family = sockaddr_ptr->sa_family;
  4968. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4969. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4970. (*current)->ai_addrlen = sockaddr_len;
  4971. // Copy sockaddr
  4972. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4973. if (!(*current)->ai_addr) {
  4974. freeaddrinfo(result_addrinfo);
  4975. CFRelease(context.addresses);
  4976. CFRelease(host_ref);
  4977. return EAI_MEMORY;
  4978. }
  4979. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4980. // Set port if service is specified
  4981. if (service && *service) {
  4982. int port = 0;
  4983. if (parse_port(service, strlen(service), port)) {
  4984. if (sockaddr_ptr->sa_family == AF_INET) {
  4985. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4986. ->sin_port = htons(static_cast<uint16_t>(port));
  4987. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4988. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4989. ->sin6_port = htons(static_cast<uint16_t>(port));
  4990. }
  4991. }
  4992. }
  4993. current = &((*current)->ai_next);
  4994. }
  4995. CFRelease(context.addresses);
  4996. CFRelease(host_ref);
  4997. *res = result_addrinfo;
  4998. return 0;
  4999. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5000. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5001. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5002. // the resolver worker still references the stack-local gaicb. The cancel
  5003. // path therefore waits (gai_suspend with no timeout) for the worker to
  5004. // actually finish before letting the stack frame go. The trade-off is that
  5005. // a wedged DNS server can hold this thread for the system resolver timeout
  5006. // (~30s by default) past the caller's connection timeout.
  5007. struct gaicb request {};
  5008. struct gaicb *requests[1] = {&request};
  5009. struct sigevent sevp {};
  5010. struct timespec timeout {
  5011. timeout_sec, 0
  5012. };
  5013. request.ar_name = node;
  5014. request.ar_service = service;
  5015. request.ar_request = hints;
  5016. sevp.sigev_notify = SIGEV_NONE;
  5017. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5018. if (rc != 0) { return rc; }
  5019. auto cleanup = scope_exit([&] {
  5020. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5021. });
  5022. int wait_result = gai_suspend(requests, 1, &timeout);
  5023. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5024. int gai_result = gai_error(&request);
  5025. if (gai_result == 0) {
  5026. *res = request.ar_result;
  5027. request.ar_result = nullptr;
  5028. return 0;
  5029. }
  5030. return gai_result;
  5031. }
  5032. gai_cancel(&request);
  5033. while (gai_error(&request) == EAI_INPROGRESS) {
  5034. gai_suspend(requests, 1, nullptr);
  5035. }
  5036. return wait_result;
  5037. #else
  5038. // Fallback implementation using thread-based timeout for other Unix systems.
  5039. struct GetAddrInfoState {
  5040. ~GetAddrInfoState() {
  5041. if (info) { freeaddrinfo(info); }
  5042. }
  5043. std::mutex mutex;
  5044. std::condition_variable result_cv;
  5045. bool completed = false;
  5046. int result = EAI_SYSTEM;
  5047. std::string node;
  5048. std::string service;
  5049. struct addrinfo hints;
  5050. struct addrinfo *info = nullptr;
  5051. };
  5052. // Allocate on the heap, so the resolver thread can keep using the data.
  5053. auto state = std::make_shared<GetAddrInfoState>();
  5054. if (node) { state->node = node; }
  5055. state->service = service;
  5056. state->hints = *hints;
  5057. std::thread resolve_thread([state]() {
  5058. auto thread_result =
  5059. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5060. &state->info);
  5061. std::lock_guard<std::mutex> lock(state->mutex);
  5062. state->result = thread_result;
  5063. state->completed = true;
  5064. state->result_cv.notify_one();
  5065. });
  5066. // Wait for completion or timeout
  5067. std::unique_lock<std::mutex> lock(state->mutex);
  5068. auto finished =
  5069. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5070. [&] { return state->completed; });
  5071. if (finished) {
  5072. // Operation completed within timeout
  5073. resolve_thread.join();
  5074. *res = state->info;
  5075. state->info = nullptr; // Pass ownership to caller
  5076. return state->result;
  5077. } else {
  5078. // Timeout occurred
  5079. resolve_thread.detach(); // Let the thread finish in background
  5080. return EAI_AGAIN; // Return timeout error
  5081. }
  5082. #endif
  5083. #else
  5084. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5085. return getaddrinfo(node, service, hints, res);
  5086. #endif
  5087. }
  5088. template <typename BindOrConnect>
  5089. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5090. int address_family, int socket_flags, bool tcp_nodelay,
  5091. bool ipv6_v6only, SocketOptions socket_options,
  5092. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5093. // Get address info
  5094. const char *node = nullptr;
  5095. struct addrinfo hints;
  5096. struct addrinfo *result;
  5097. memset(&hints, 0, sizeof(struct addrinfo));
  5098. hints.ai_socktype = SOCK_STREAM;
  5099. hints.ai_protocol = IPPROTO_IP;
  5100. if (!ip.empty()) {
  5101. node = ip.c_str();
  5102. // Ask getaddrinfo to convert IP in c-string to address
  5103. hints.ai_family = AF_UNSPEC;
  5104. hints.ai_flags = AI_NUMERICHOST;
  5105. } else {
  5106. if (!host.empty()) { node = host.c_str(); }
  5107. hints.ai_family = address_family;
  5108. hints.ai_flags = socket_flags;
  5109. }
  5110. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5111. if (hints.ai_family == AF_UNIX) {
  5112. const auto addrlen = host.length();
  5113. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5114. #ifdef SOCK_CLOEXEC
  5115. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5116. hints.ai_protocol);
  5117. #else
  5118. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5119. #endif
  5120. if (sock != INVALID_SOCKET) {
  5121. sockaddr_un addr{};
  5122. addr.sun_family = AF_UNIX;
  5123. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5124. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5125. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5126. hints.ai_addrlen = static_cast<socklen_t>(
  5127. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5128. #ifndef SOCK_CLOEXEC
  5129. #ifndef _WIN32
  5130. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5131. #endif
  5132. #endif
  5133. if (socket_options) { socket_options(sock); }
  5134. #ifdef _WIN32
  5135. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5136. // remove the option.
  5137. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5138. #endif
  5139. bool dummy;
  5140. if (!bind_or_connect(sock, hints, dummy)) {
  5141. close_socket(sock);
  5142. sock = INVALID_SOCKET;
  5143. }
  5144. }
  5145. return sock;
  5146. }
  5147. #endif
  5148. auto service = std::to_string(port);
  5149. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5150. timeout_sec)) {
  5151. #if defined __linux__ && !defined __ANDROID__
  5152. res_init();
  5153. #endif
  5154. return INVALID_SOCKET;
  5155. }
  5156. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5157. for (auto rp = result; rp; rp = rp->ai_next) {
  5158. // Create a socket
  5159. #ifdef _WIN32
  5160. auto sock =
  5161. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5162. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5163. /**
  5164. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5165. * and above the socket creation fails on older Windows Systems.
  5166. *
  5167. * Let's try to create a socket the old way in this case.
  5168. *
  5169. * Reference:
  5170. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5171. *
  5172. * WSA_FLAG_NO_HANDLE_INHERIT:
  5173. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5174. * SP1, and later
  5175. *
  5176. */
  5177. if (sock == INVALID_SOCKET) {
  5178. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5179. }
  5180. #else
  5181. #ifdef SOCK_CLOEXEC
  5182. auto sock =
  5183. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5184. #else
  5185. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5186. #endif
  5187. #endif
  5188. if (sock == INVALID_SOCKET) { continue; }
  5189. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5190. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5191. close_socket(sock);
  5192. continue;
  5193. }
  5194. #endif
  5195. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5196. if (rp->ai_family == AF_INET6) {
  5197. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5198. }
  5199. if (socket_options) { socket_options(sock); }
  5200. // bind or connect
  5201. auto quit = false;
  5202. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5203. close_socket(sock);
  5204. if (quit) { break; }
  5205. }
  5206. return INVALID_SOCKET;
  5207. }
  5208. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5209. #ifdef _WIN32
  5210. auto flags = nonblocking ? 1UL : 0UL;
  5211. ioctlsocket(sock, FIONBIO, &flags);
  5212. #else
  5213. auto flags = fcntl(sock, F_GETFL, 0);
  5214. fcntl(sock, F_SETFL,
  5215. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5216. #endif
  5217. }
  5218. inline bool is_connection_error() {
  5219. #ifdef _WIN32
  5220. return WSAGetLastError() != WSAEWOULDBLOCK;
  5221. #else
  5222. return errno != EINPROGRESS;
  5223. #endif
  5224. }
  5225. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5226. struct addrinfo hints;
  5227. struct addrinfo *result;
  5228. memset(&hints, 0, sizeof(struct addrinfo));
  5229. hints.ai_family = AF_UNSPEC;
  5230. hints.ai_socktype = SOCK_STREAM;
  5231. hints.ai_protocol = 0;
  5232. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5233. return false;
  5234. }
  5235. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5236. auto ret = false;
  5237. for (auto rp = result; rp; rp = rp->ai_next) {
  5238. const auto &ai = *rp;
  5239. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5240. ret = true;
  5241. break;
  5242. }
  5243. }
  5244. return ret;
  5245. }
  5246. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5247. #define USE_IF2IP
  5248. #endif
  5249. #ifdef USE_IF2IP
  5250. inline std::string if2ip(int address_family, const std::string &ifn) {
  5251. struct ifaddrs *ifap;
  5252. getifaddrs(&ifap);
  5253. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5254. std::string addr_candidate;
  5255. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5256. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5257. (AF_UNSPEC == address_family ||
  5258. ifa->ifa_addr->sa_family == address_family)) {
  5259. if (ifa->ifa_addr->sa_family == AF_INET) {
  5260. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5261. char buf[INET_ADDRSTRLEN];
  5262. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5263. return std::string(buf, INET_ADDRSTRLEN);
  5264. }
  5265. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5266. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5267. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5268. char buf[INET6_ADDRSTRLEN] = {};
  5269. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5270. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5271. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5272. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5273. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5274. } else {
  5275. return std::string(buf, INET6_ADDRSTRLEN);
  5276. }
  5277. }
  5278. }
  5279. }
  5280. }
  5281. }
  5282. return addr_candidate;
  5283. }
  5284. #endif
  5285. inline socket_t create_client_socket(
  5286. const std::string &host, const std::string &ip, int port,
  5287. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5288. SocketOptions socket_options, time_t connection_timeout_sec,
  5289. time_t connection_timeout_usec, time_t read_timeout_sec,
  5290. time_t read_timeout_usec, time_t write_timeout_sec,
  5291. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5292. auto sock = create_socket(
  5293. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5294. std::move(socket_options),
  5295. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5296. if (!intf.empty()) {
  5297. #ifdef USE_IF2IP
  5298. auto ip_from_if = if2ip(address_family, intf);
  5299. if (ip_from_if.empty()) { ip_from_if = intf; }
  5300. if (!bind_ip_address(sock2, ip_from_if)) {
  5301. error = Error::BindIPAddress;
  5302. return false;
  5303. }
  5304. #endif
  5305. }
  5306. set_nonblocking(sock2, true);
  5307. auto ret =
  5308. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5309. if (ret < 0) {
  5310. if (is_connection_error()) {
  5311. error = Error::Connection;
  5312. return false;
  5313. }
  5314. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5315. connection_timeout_usec);
  5316. if (error != Error::Success) {
  5317. if (error == Error::ConnectionTimeout) { quit = true; }
  5318. return false;
  5319. }
  5320. }
  5321. set_nonblocking(sock2, false);
  5322. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5323. read_timeout_usec);
  5324. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5325. write_timeout_usec);
  5326. error = Error::Success;
  5327. return true;
  5328. },
  5329. connection_timeout_sec); // Pass DNS timeout
  5330. if (sock != INVALID_SOCKET) {
  5331. error = Error::Success;
  5332. } else {
  5333. if (error == Error::Success) { error = Error::Connection; }
  5334. }
  5335. return sock;
  5336. }
  5337. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5338. socklen_t addr_len, std::string &ip, int &port) {
  5339. if (addr.ss_family == AF_INET) {
  5340. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5341. } else if (addr.ss_family == AF_INET6) {
  5342. port =
  5343. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5344. } else {
  5345. return false;
  5346. }
  5347. std::array<char, NI_MAXHOST> ipstr{};
  5348. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5349. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5350. 0, NI_NUMERICHOST)) {
  5351. return false;
  5352. }
  5353. ip = ipstr.data();
  5354. return true;
  5355. }
  5356. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5357. struct sockaddr_storage addr;
  5358. socklen_t addr_len = sizeof(addr);
  5359. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5360. &addr_len)) {
  5361. get_ip_and_port(addr, addr_len, ip, port);
  5362. }
  5363. }
  5364. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5365. struct sockaddr_storage addr;
  5366. socklen_t addr_len = sizeof(addr);
  5367. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5368. &addr_len)) {
  5369. #ifndef _WIN32
  5370. if (addr.ss_family == AF_UNIX) {
  5371. #if defined(__linux__)
  5372. struct ucred ucred;
  5373. socklen_t len = sizeof(ucred);
  5374. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5375. port = ucred.pid;
  5376. }
  5377. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5378. pid_t pid;
  5379. socklen_t len = sizeof(pid);
  5380. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5381. port = pid;
  5382. }
  5383. #endif
  5384. return;
  5385. }
  5386. #endif
  5387. get_ip_and_port(addr, addr_len, ip, port);
  5388. }
  5389. }
  5390. // Recursive form retained so operator""_t below can compute hashes for
  5391. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5392. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5393. // instead, which is iterative and stack-safe.
  5394. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5395. unsigned int h) {
  5396. return (l == 0)
  5397. ? h
  5398. : str2tag_core(
  5399. s + 1, l - 1,
  5400. // Unsets the 6 high bits of h, therefore no overflow happens
  5401. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5402. h * 33) ^
  5403. static_cast<unsigned char>(*s));
  5404. }
  5405. inline unsigned int str2tag(const std::string &s) {
  5406. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5407. // for compile-time UDL evaluation of short string literals, but at runtime
  5408. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5409. // would blow the stack with one frame per character.
  5410. unsigned int h = 0;
  5411. for (auto c : s) {
  5412. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5413. static_cast<unsigned char>(c);
  5414. }
  5415. return h;
  5416. }
  5417. namespace udl {
  5418. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5419. return str2tag_core(s, l, 0);
  5420. }
  5421. } // namespace udl
  5422. inline std::string
  5423. find_content_type(const std::string &path,
  5424. const std::map<std::string, std::string> &user_data,
  5425. const std::string &default_content_type) {
  5426. auto ext = file_extension(path);
  5427. auto it = user_data.find(ext);
  5428. if (it != user_data.end()) { return it->second; }
  5429. using udl::operator""_t;
  5430. switch (str2tag(ext)) {
  5431. default: return default_content_type;
  5432. case "css"_t: return "text/css";
  5433. case "csv"_t: return "text/csv";
  5434. case "htm"_t:
  5435. case "html"_t: return "text/html";
  5436. case "js"_t:
  5437. case "mjs"_t: return "text/javascript";
  5438. case "txt"_t: return "text/plain";
  5439. case "vtt"_t: return "text/vtt";
  5440. case "apng"_t: return "image/apng";
  5441. case "avif"_t: return "image/avif";
  5442. case "bmp"_t: return "image/bmp";
  5443. case "gif"_t: return "image/gif";
  5444. case "png"_t: return "image/png";
  5445. case "svg"_t: return "image/svg+xml";
  5446. case "webp"_t: return "image/webp";
  5447. case "ico"_t: return "image/x-icon";
  5448. case "tif"_t: return "image/tiff";
  5449. case "tiff"_t: return "image/tiff";
  5450. case "jpg"_t:
  5451. case "jpeg"_t: return "image/jpeg";
  5452. case "mp4"_t: return "video/mp4";
  5453. case "mpeg"_t: return "video/mpeg";
  5454. case "webm"_t: return "video/webm";
  5455. case "mp3"_t: return "audio/mp3";
  5456. case "mpga"_t: return "audio/mpeg";
  5457. case "weba"_t: return "audio/webm";
  5458. case "wav"_t: return "audio/wave";
  5459. case "otf"_t: return "font/otf";
  5460. case "ttf"_t: return "font/ttf";
  5461. case "woff"_t: return "font/woff";
  5462. case "woff2"_t: return "font/woff2";
  5463. case "7z"_t: return "application/x-7z-compressed";
  5464. case "atom"_t: return "application/atom+xml";
  5465. case "pdf"_t: return "application/pdf";
  5466. case "json"_t: return "application/json";
  5467. case "rss"_t: return "application/rss+xml";
  5468. case "tar"_t: return "application/x-tar";
  5469. case "xht"_t:
  5470. case "xhtml"_t: return "application/xhtml+xml";
  5471. case "xslt"_t: return "application/xslt+xml";
  5472. case "xml"_t: return "application/xml";
  5473. case "gz"_t: return "application/gzip";
  5474. case "zip"_t: return "application/zip";
  5475. case "wasm"_t: return "application/wasm";
  5476. }
  5477. }
  5478. inline std::string
  5479. extract_media_type(const std::string &content_type,
  5480. std::map<std::string, std::string> *params = nullptr) {
  5481. // Extract type/subtype from Content-Type value (RFC 2045)
  5482. // e.g. "application/json; charset=utf-8" -> "application/json"
  5483. auto media_type = content_type;
  5484. auto semicolon_pos = media_type.find(';');
  5485. if (semicolon_pos != std::string::npos) {
  5486. auto param_str = media_type.substr(semicolon_pos + 1);
  5487. media_type = media_type.substr(0, semicolon_pos);
  5488. if (params) {
  5489. // Parse parameters: key=value pairs separated by ';'
  5490. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5491. [&](const char *b, const char *e) {
  5492. std::string key;
  5493. std::string val;
  5494. split(b, e, '=', [&](const char *b2, const char *e2) {
  5495. if (key.empty()) {
  5496. key.assign(b2, e2);
  5497. } else {
  5498. val.assign(b2, e2);
  5499. }
  5500. });
  5501. if (!key.empty()) {
  5502. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5503. }
  5504. });
  5505. }
  5506. }
  5507. // Trim whitespace from media type
  5508. return trim_copy(media_type);
  5509. }
  5510. inline bool can_compress_content_type(const std::string &content_type) {
  5511. using udl::operator""_t;
  5512. auto mime_type = extract_media_type(content_type);
  5513. auto tag = str2tag(mime_type);
  5514. switch (tag) {
  5515. case "image/svg+xml"_t:
  5516. case "application/javascript"_t:
  5517. case "application/x-javascript"_t:
  5518. case "application/json"_t:
  5519. case "application/ld+json"_t:
  5520. case "application/xml"_t:
  5521. case "application/xhtml+xml"_t:
  5522. case "application/rss+xml"_t:
  5523. case "application/atom+xml"_t:
  5524. case "application/xslt+xml"_t:
  5525. case "application/protobuf"_t: return true;
  5526. case "text/event-stream"_t: return false;
  5527. default: return !mime_type.rfind("text/", 0);
  5528. }
  5529. }
  5530. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5531. double &quality) {
  5532. quality = 1.0;
  5533. token.clear();
  5534. // Split on first ';': left = token name, right = parameters
  5535. const char *params_b = nullptr;
  5536. std::size_t params_len = 0;
  5537. divide(
  5538. b, static_cast<std::size_t>(e - b), ';',
  5539. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5540. auto r = trim(lb, lb + llen, 0, llen);
  5541. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5542. params_b = rb;
  5543. params_len = rlen;
  5544. });
  5545. if (token.empty()) { return false; }
  5546. if (params_len == 0) { return true; }
  5547. // Scan parameters for q= (stops on first match)
  5548. bool invalid = false;
  5549. split_find(params_b, params_b + params_len, ';',
  5550. (std::numeric_limits<size_t>::max)(),
  5551. [&](const char *pb, const char *pe) -> bool {
  5552. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5553. auto len = static_cast<size_t>(pe - pb);
  5554. if (len < 2) { return false; }
  5555. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5556. return false;
  5557. }
  5558. // Trim the value portion
  5559. auto r = trim(pb, pe, 2, len);
  5560. if (r.first >= r.second) {
  5561. invalid = true;
  5562. return true;
  5563. }
  5564. double v = 0.0;
  5565. auto res = from_chars(pb + r.first, pb + r.second, v);
  5566. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5567. invalid = true;
  5568. return true;
  5569. }
  5570. quality = v;
  5571. return true;
  5572. });
  5573. return !invalid;
  5574. }
  5575. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5576. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5577. return EncodingType::None;
  5578. }
  5579. const auto &s = req.get_header_value("Accept-Encoding");
  5580. if (s.empty()) { return EncodingType::None; }
  5581. // Single-pass: iterate tokens and track the best supported encoding.
  5582. // Server preference breaks ties (br > gzip > zstd).
  5583. EncodingType best = EncodingType::None;
  5584. double best_q = 0.0; // q=0 means "not acceptable"
  5585. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5586. auto priority = [](EncodingType t) -> int {
  5587. switch (t) {
  5588. case EncodingType::Brotli: return 0;
  5589. case EncodingType::Gzip: return 1;
  5590. case EncodingType::Zstd: return 2;
  5591. default: return 3;
  5592. }
  5593. };
  5594. std::string name;
  5595. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5596. double quality = 1.0;
  5597. if (!parse_quality(b, e, name, quality)) { return; }
  5598. if (quality <= 0.0) { return; }
  5599. EncodingType type = EncodingType::None;
  5600. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5601. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5602. #endif
  5603. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5604. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5605. type = EncodingType::Gzip;
  5606. }
  5607. #endif
  5608. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5609. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5610. type = EncodingType::Zstd;
  5611. }
  5612. #endif
  5613. if (type == EncodingType::None) { return; }
  5614. // Higher q-value wins; for equal q, server preference breaks ties
  5615. if (quality > best_q ||
  5616. (quality == best_q && priority(type) < priority(best))) {
  5617. best_q = quality;
  5618. best = type;
  5619. }
  5620. });
  5621. return best;
  5622. }
  5623. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5624. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5625. if (type == EncodingType::Gzip) {
  5626. return detail::make_unique<gzip_compressor>();
  5627. }
  5628. #endif
  5629. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5630. if (type == EncodingType::Brotli) {
  5631. return detail::make_unique<brotli_compressor>();
  5632. }
  5633. #endif
  5634. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5635. if (type == EncodingType::Zstd) {
  5636. return detail::make_unique<zstd_compressor>();
  5637. }
  5638. #endif
  5639. (void)type;
  5640. return nullptr;
  5641. }
  5642. inline const char *encoding_name(EncodingType type) {
  5643. switch (type) {
  5644. case EncodingType::Gzip: return "gzip";
  5645. case EncodingType::Brotli: return "br";
  5646. case EncodingType::Zstd: return "zstd";
  5647. default: return "";
  5648. }
  5649. }
  5650. inline bool nocompressor::compress(const char *data, size_t data_length,
  5651. bool /*last*/, Callback callback) {
  5652. if (!data_length) { return true; }
  5653. return callback(data, data_length);
  5654. }
  5655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5656. inline gzip_compressor::gzip_compressor() {
  5657. std::memset(&strm_, 0, sizeof(strm_));
  5658. strm_.zalloc = Z_NULL;
  5659. strm_.zfree = Z_NULL;
  5660. strm_.opaque = Z_NULL;
  5661. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5662. Z_DEFAULT_STRATEGY) == Z_OK;
  5663. }
  5664. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5665. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5666. bool last, Callback callback) {
  5667. assert(is_valid_);
  5668. do {
  5669. constexpr size_t max_avail_in =
  5670. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5671. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5672. (std::min)(data_length, max_avail_in));
  5673. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5674. data_length -= strm_.avail_in;
  5675. data += strm_.avail_in;
  5676. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5677. auto ret = Z_OK;
  5678. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5679. do {
  5680. strm_.avail_out = static_cast<uInt>(buff.size());
  5681. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5682. ret = deflate(&strm_, flush);
  5683. if (ret == Z_STREAM_ERROR) { return false; }
  5684. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5685. return false;
  5686. }
  5687. } while (strm_.avail_out == 0);
  5688. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5689. (flush == Z_NO_FLUSH && ret == Z_OK));
  5690. assert(strm_.avail_in == 0);
  5691. } while (data_length > 0);
  5692. return true;
  5693. }
  5694. inline gzip_decompressor::gzip_decompressor() {
  5695. std::memset(&strm_, 0, sizeof(strm_));
  5696. strm_.zalloc = Z_NULL;
  5697. strm_.zfree = Z_NULL;
  5698. strm_.opaque = Z_NULL;
  5699. // 15 is the value of wbits, which should be at the maximum possible value
  5700. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5701. // that the stream type should be automatically detected either gzip or
  5702. // deflate.
  5703. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5704. }
  5705. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5706. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5707. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5708. Callback callback) {
  5709. assert(is_valid_);
  5710. auto ret = Z_OK;
  5711. do {
  5712. constexpr size_t max_avail_in =
  5713. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5714. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5715. (std::min)(data_length, max_avail_in));
  5716. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5717. data_length -= strm_.avail_in;
  5718. data += strm_.avail_in;
  5719. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5720. while (strm_.avail_in > 0 && ret == Z_OK) {
  5721. strm_.avail_out = static_cast<uInt>(buff.size());
  5722. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5723. ret = inflate(&strm_, Z_NO_FLUSH);
  5724. assert(ret != Z_STREAM_ERROR);
  5725. switch (ret) {
  5726. case Z_NEED_DICT:
  5727. case Z_DATA_ERROR:
  5728. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5729. }
  5730. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5731. return false;
  5732. }
  5733. }
  5734. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5735. } while (data_length > 0);
  5736. return true;
  5737. }
  5738. #endif
  5739. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5740. inline brotli_compressor::brotli_compressor() {
  5741. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5742. }
  5743. inline brotli_compressor::~brotli_compressor() {
  5744. BrotliEncoderDestroyInstance(state_);
  5745. }
  5746. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5747. bool last, Callback callback) {
  5748. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5749. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5750. auto available_in = data_length;
  5751. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5752. for (;;) {
  5753. if (last) {
  5754. if (BrotliEncoderIsFinished(state_)) { break; }
  5755. } else {
  5756. if (!available_in) { break; }
  5757. }
  5758. auto available_out = buff.size();
  5759. auto next_out = buff.data();
  5760. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5761. &available_out, &next_out, nullptr)) {
  5762. return false;
  5763. }
  5764. auto output_bytes = buff.size() - available_out;
  5765. if (output_bytes) {
  5766. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5767. }
  5768. }
  5769. return true;
  5770. }
  5771. inline brotli_decompressor::brotli_decompressor() {
  5772. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5773. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5774. : BROTLI_DECODER_RESULT_ERROR;
  5775. }
  5776. inline brotli_decompressor::~brotli_decompressor() {
  5777. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5778. }
  5779. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5780. inline bool brotli_decompressor::decompress(const char *data,
  5781. size_t data_length,
  5782. Callback callback) {
  5783. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5784. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5785. return 0;
  5786. }
  5787. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5788. size_t avail_in = data_length;
  5789. size_t total_out;
  5790. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5791. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5792. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5793. char *next_out = buff.data();
  5794. size_t avail_out = buff.size();
  5795. decoder_r = BrotliDecoderDecompressStream(
  5796. decoder_s, &avail_in, &next_in, &avail_out,
  5797. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5798. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5799. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5800. }
  5801. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5802. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5803. }
  5804. #endif
  5805. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5806. inline zstd_compressor::zstd_compressor() {
  5807. ctx_ = ZSTD_createCCtx();
  5808. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5809. }
  5810. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5811. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5812. bool last, Callback callback) {
  5813. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5814. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5815. ZSTD_inBuffer input = {data, data_length, 0};
  5816. bool finished;
  5817. do {
  5818. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5819. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5820. if (ZSTD_isError(remaining)) { return false; }
  5821. if (!callback(buff.data(), output.pos)) { return false; }
  5822. finished = last ? (remaining == 0) : (input.pos == input.size);
  5823. } while (!finished);
  5824. return true;
  5825. }
  5826. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5827. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5828. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5829. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5830. Callback callback) {
  5831. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5832. ZSTD_inBuffer input = {data, data_length, 0};
  5833. while (input.pos < input.size) {
  5834. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5835. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5836. if (ZSTD_isError(remaining)) { return false; }
  5837. if (!callback(buff.data(), output.pos)) { return false; }
  5838. }
  5839. return true;
  5840. }
  5841. #endif
  5842. inline std::unique_ptr<decompressor>
  5843. create_decompressor(const std::string &encoding) {
  5844. std::unique_ptr<decompressor> decompressor;
  5845. if (encoding == "gzip" || encoding == "deflate") {
  5846. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5847. decompressor = detail::make_unique<gzip_decompressor>();
  5848. #endif
  5849. } else if (encoding.find("br") != std::string::npos) {
  5850. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5851. decompressor = detail::make_unique<brotli_decompressor>();
  5852. #endif
  5853. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5854. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5855. decompressor = detail::make_unique<zstd_decompressor>();
  5856. #endif
  5857. }
  5858. return decompressor;
  5859. }
  5860. // Returns the best available compressor and its Content-Encoding name.
  5861. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5862. inline std::pair<std::unique_ptr<compressor>, const char *>
  5863. create_compressor() {
  5864. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5865. return {detail::make_unique<brotli_compressor>(), "br"};
  5866. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5867. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5868. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5869. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5870. #else
  5871. return {nullptr, nullptr};
  5872. #endif
  5873. }
  5874. inline bool is_prohibited_header_name(const std::string &name) {
  5875. using udl::operator""_t;
  5876. switch (str2tag(name)) {
  5877. case "REMOTE_ADDR"_t:
  5878. case "REMOTE_PORT"_t:
  5879. case "LOCAL_ADDR"_t:
  5880. case "LOCAL_PORT"_t: return true;
  5881. default: return false;
  5882. }
  5883. }
  5884. inline bool has_header(const Headers &headers, const std::string &key) {
  5885. if (is_prohibited_header_name(key)) { return false; }
  5886. return headers.find(key) != headers.end();
  5887. }
  5888. inline const char *get_header_value(const Headers &headers,
  5889. const std::string &key, const char *def,
  5890. size_t id) {
  5891. if (is_prohibited_header_name(key)) {
  5892. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5893. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5894. throw std::invalid_argument(msg);
  5895. #else
  5896. return "";
  5897. #endif
  5898. }
  5899. auto rng = headers.equal_range(key);
  5900. auto it = rng.first;
  5901. std::advance(it, static_cast<ssize_t>(id));
  5902. if (it != rng.second) { return it->second.c_str(); }
  5903. return def;
  5904. }
  5905. inline size_t get_header_value_count(const Headers &headers,
  5906. const std::string &key) {
  5907. auto r = headers.equal_range(key);
  5908. return static_cast<size_t>(std::distance(r.first, r.second));
  5909. }
  5910. template <typename Map>
  5911. inline typename Map::mapped_type
  5912. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5913. auto rng = m.equal_range(key);
  5914. auto it = rng.first;
  5915. std::advance(it, static_cast<ssize_t>(id));
  5916. if (it != rng.second) { return it->second; }
  5917. return typename Map::mapped_type();
  5918. }
  5919. inline void set_header(Headers &headers, const std::string &key,
  5920. const std::string &val) {
  5921. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5922. headers.emplace(key, val);
  5923. }
  5924. }
  5925. inline bool read_headers(Stream &strm, Headers &headers) {
  5926. const auto bufsiz = 2048;
  5927. char buf[bufsiz];
  5928. stream_line_reader line_reader(strm, buf, bufsiz);
  5929. size_t header_count = 0;
  5930. for (;;) {
  5931. if (!line_reader.getline()) { return false; }
  5932. // Check if the line ends with CRLF.
  5933. auto line_terminator_len = 2;
  5934. if (line_reader.end_with_crlf()) {
  5935. // Blank line indicates end of headers.
  5936. if (line_reader.size() == 2) { break; }
  5937. } else {
  5938. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5939. // Blank line indicates end of headers.
  5940. if (line_reader.size() == 1) { break; }
  5941. line_terminator_len = 1;
  5942. #else
  5943. continue; // Skip invalid line.
  5944. #endif
  5945. }
  5946. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5947. // Check header count limit
  5948. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5949. // Exclude line terminator
  5950. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5951. if (!parse_header(line_reader.ptr(), end,
  5952. [&](const std::string &key, const std::string &val) {
  5953. headers.emplace(key, val);
  5954. })) {
  5955. return false;
  5956. }
  5957. header_count++;
  5958. }
  5959. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5960. // headers that have different values to prevent request smuggling.
  5961. auto cl_range = headers.equal_range("Content-Length");
  5962. if (cl_range.first != cl_range.second) {
  5963. const auto &first_val = cl_range.first->second;
  5964. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5965. if (it->second != first_val) { return false; }
  5966. }
  5967. }
  5968. return true;
  5969. }
  5970. inline bool read_websocket_upgrade_response(Stream &strm,
  5971. const std::string &expected_accept,
  5972. std::string &selected_subprotocol) {
  5973. // Read status line
  5974. const auto bufsiz = 2048;
  5975. char buf[bufsiz];
  5976. stream_line_reader line_reader(strm, buf, bufsiz);
  5977. if (!line_reader.getline()) { return false; }
  5978. // Check for "HTTP/1.1 101"
  5979. auto line = std::string(line_reader.ptr(), line_reader.size());
  5980. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5981. // Parse headers using existing read_headers
  5982. Headers headers;
  5983. if (!read_headers(strm, headers)) { return false; }
  5984. // Verify Upgrade: websocket (case-insensitive)
  5985. auto upgrade_it = headers.find("Upgrade");
  5986. if (upgrade_it == headers.end()) { return false; }
  5987. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  5988. if (upgrade_val != "websocket") { return false; }
  5989. // Verify Connection header contains "Upgrade" (case-insensitive)
  5990. auto connection_it = headers.find("Connection");
  5991. if (connection_it == headers.end()) { return false; }
  5992. auto connection_val = case_ignore::to_lower(connection_it->second);
  5993. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  5994. // Verify Sec-WebSocket-Accept header value
  5995. auto it = headers.find("Sec-WebSocket-Accept");
  5996. if (it == headers.end() || it->second != expected_accept) { return false; }
  5997. // Extract negotiated subprotocol
  5998. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  5999. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6000. return true;
  6001. }
  6002. enum class ReadContentResult {
  6003. Success, // Successfully read the content
  6004. PayloadTooLarge, // The content exceeds the specified payload limit
  6005. Error // An error occurred while reading the content
  6006. };
  6007. inline ReadContentResult read_content_with_length(
  6008. Stream &strm, size_t len, DownloadProgress progress,
  6009. ContentReceiverWithProgress out,
  6010. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6011. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6012. detail::BodyReader br;
  6013. br.stream = &strm;
  6014. br.has_content_length = true;
  6015. br.content_length = len;
  6016. br.payload_max_length = payload_max_length;
  6017. br.chunked = false;
  6018. br.bytes_read = 0;
  6019. br.last_error = Error::Success;
  6020. size_t r = 0;
  6021. while (r < len) {
  6022. auto read_len = static_cast<size_t>(len - r);
  6023. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6024. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6025. if (n <= 0) {
  6026. // Check if it was a payload size error
  6027. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6028. return ReadContentResult::PayloadTooLarge;
  6029. }
  6030. return ReadContentResult::Error;
  6031. }
  6032. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6033. return ReadContentResult::Error;
  6034. }
  6035. r += static_cast<size_t>(n);
  6036. if (progress) {
  6037. if (!progress(r, len)) { return ReadContentResult::Error; }
  6038. }
  6039. }
  6040. return ReadContentResult::Success;
  6041. }
  6042. inline ReadContentResult
  6043. read_content_without_length(Stream &strm, size_t payload_max_length,
  6044. ContentReceiverWithProgress out) {
  6045. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6046. size_t r = 0;
  6047. for (;;) {
  6048. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6049. if (n == 0) { return ReadContentResult::Success; }
  6050. if (n < 0) { return ReadContentResult::Error; }
  6051. // Check if adding this data would exceed the payload limit
  6052. if (r > payload_max_length ||
  6053. payload_max_length - r < static_cast<size_t>(n)) {
  6054. return ReadContentResult::PayloadTooLarge;
  6055. }
  6056. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6057. return ReadContentResult::Error;
  6058. }
  6059. r += static_cast<size_t>(n);
  6060. }
  6061. return ReadContentResult::Success;
  6062. }
  6063. template <typename T>
  6064. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6065. size_t payload_max_length,
  6066. ContentReceiverWithProgress out) {
  6067. detail::ChunkedDecoder dec(strm);
  6068. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6069. size_t total_len = 0;
  6070. for (;;) {
  6071. size_t chunk_offset = 0;
  6072. size_t chunk_total = 0;
  6073. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6074. if (n < 0) { return ReadContentResult::Error; }
  6075. if (n == 0) {
  6076. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6077. return ReadContentResult::Error;
  6078. }
  6079. return ReadContentResult::Success;
  6080. }
  6081. if (total_len > payload_max_length ||
  6082. payload_max_length - total_len < static_cast<size_t>(n)) {
  6083. return ReadContentResult::PayloadTooLarge;
  6084. }
  6085. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6086. return ReadContentResult::Error;
  6087. }
  6088. total_len += static_cast<size_t>(n);
  6089. }
  6090. }
  6091. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6092. return case_ignore::equal(
  6093. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  6094. }
  6095. template <typename T, typename U>
  6096. bool prepare_content_receiver(T &x, int &status,
  6097. ContentReceiverWithProgress receiver,
  6098. bool decompress, size_t payload_max_length,
  6099. bool &exceed_payload_max_length, U callback) {
  6100. if (decompress) {
  6101. std::string encoding = x.get_header_value("Content-Encoding");
  6102. std::unique_ptr<decompressor> decompressor;
  6103. if (!encoding.empty()) {
  6104. decompressor = detail::create_decompressor(encoding);
  6105. if (!decompressor) {
  6106. // Unsupported encoding or no support compiled in
  6107. status = StatusCode::UnsupportedMediaType_415;
  6108. return false;
  6109. }
  6110. }
  6111. if (decompressor) {
  6112. if (decompressor->is_valid()) {
  6113. size_t decompressed_size = 0;
  6114. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6115. size_t off, size_t len) {
  6116. return decompressor->decompress(
  6117. buf, n, [&](const char *buf2, size_t n2) {
  6118. // Guard against zip-bomb: check
  6119. // decompressed size against limit.
  6120. if (payload_max_length > 0 &&
  6121. (decompressed_size >= payload_max_length ||
  6122. n2 > payload_max_length - decompressed_size)) {
  6123. exceed_payload_max_length = true;
  6124. return false;
  6125. }
  6126. decompressed_size += n2;
  6127. return receiver(buf2, n2, off, len);
  6128. });
  6129. };
  6130. return callback(std::move(out));
  6131. } else {
  6132. status = StatusCode::InternalServerError_500;
  6133. return false;
  6134. }
  6135. }
  6136. }
  6137. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6138. size_t len) {
  6139. return receiver(buf, n, off, len);
  6140. };
  6141. return callback(std::move(out));
  6142. }
  6143. template <typename T>
  6144. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6145. DownloadProgress progress,
  6146. ContentReceiverWithProgress receiver, bool decompress) {
  6147. bool exceed_payload_max_length = false;
  6148. return prepare_content_receiver(
  6149. x, status, std::move(receiver), decompress, payload_max_length,
  6150. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6151. auto ret = true;
  6152. // Note: exceed_payload_max_length may also be set by the decompressor
  6153. // wrapper in prepare_content_receiver when the decompressed payload
  6154. // size exceeds the limit.
  6155. if (is_chunked_transfer_encoding(x.headers)) {
  6156. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6157. if (result == ReadContentResult::Success) {
  6158. ret = true;
  6159. } else if (result == ReadContentResult::PayloadTooLarge) {
  6160. exceed_payload_max_length = true;
  6161. ret = false;
  6162. } else {
  6163. ret = false;
  6164. }
  6165. } else if (!has_header(x.headers, "Content-Length")) {
  6166. auto result =
  6167. read_content_without_length(strm, payload_max_length, out);
  6168. if (result == ReadContentResult::Success) {
  6169. ret = true;
  6170. } else if (result == ReadContentResult::PayloadTooLarge) {
  6171. exceed_payload_max_length = true;
  6172. ret = false;
  6173. } else {
  6174. ret = false;
  6175. }
  6176. } else {
  6177. auto is_invalid_value = false;
  6178. auto len = get_header_value_u64(x.headers, "Content-Length",
  6179. (std::numeric_limits<size_t>::max)(),
  6180. 0, is_invalid_value);
  6181. if (is_invalid_value) {
  6182. ret = false;
  6183. } else if (len > 0) {
  6184. auto result = read_content_with_length(
  6185. strm, len, std::move(progress), out, payload_max_length);
  6186. ret = (result == ReadContentResult::Success);
  6187. if (result == ReadContentResult::PayloadTooLarge) {
  6188. exceed_payload_max_length = true;
  6189. }
  6190. }
  6191. }
  6192. if (!ret) {
  6193. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6194. : StatusCode::BadRequest_400;
  6195. }
  6196. return ret;
  6197. });
  6198. }
  6199. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6200. const std::string &path) {
  6201. std::string s = method;
  6202. s += ' ';
  6203. s += path;
  6204. s += " HTTP/1.1\r\n";
  6205. return strm.write(s.data(), s.size());
  6206. }
  6207. inline ssize_t write_response_line(Stream &strm, int status) {
  6208. std::string s = "HTTP/1.1 ";
  6209. s += std::to_string(status);
  6210. s += ' ';
  6211. s += httplib::status_message(status);
  6212. s += "\r\n";
  6213. return strm.write(s.data(), s.size());
  6214. }
  6215. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6216. ssize_t write_len = 0;
  6217. for (const auto &x : headers) {
  6218. std::string s;
  6219. s = x.first;
  6220. s += ": ";
  6221. s += x.second;
  6222. s += "\r\n";
  6223. auto len = strm.write(s.data(), s.size());
  6224. if (len < 0) { return len; }
  6225. write_len += len;
  6226. }
  6227. auto len = strm.write("\r\n");
  6228. if (len < 0) { return len; }
  6229. write_len += len;
  6230. return write_len;
  6231. }
  6232. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6233. size_t offset = 0;
  6234. while (offset < l) {
  6235. auto length = strm.write(d + offset, l - offset);
  6236. if (length < 0) { return false; }
  6237. offset += static_cast<size_t>(length);
  6238. }
  6239. return true;
  6240. }
  6241. template <typename T>
  6242. inline bool write_content_with_progress(Stream &strm,
  6243. const ContentProvider &content_provider,
  6244. size_t offset, size_t length,
  6245. T is_shutting_down,
  6246. const UploadProgress &upload_progress,
  6247. Error &error) {
  6248. size_t end_offset = offset + length;
  6249. size_t start_offset = offset;
  6250. auto ok = true;
  6251. DataSink data_sink;
  6252. data_sink.write = [&](const char *d, size_t l) -> bool {
  6253. if (ok) {
  6254. if (write_data(strm, d, l)) {
  6255. offset += l;
  6256. if (upload_progress && length > 0) {
  6257. size_t current_written = offset - start_offset;
  6258. if (!upload_progress(current_written, length)) {
  6259. ok = false;
  6260. return false;
  6261. }
  6262. }
  6263. } else {
  6264. ok = false;
  6265. }
  6266. }
  6267. return ok;
  6268. };
  6269. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6270. while (offset < end_offset && !is_shutting_down()) {
  6271. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6272. error = Error::Write;
  6273. return false;
  6274. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6275. error = Error::Canceled;
  6276. return false;
  6277. } else if (!ok) {
  6278. error = Error::Write;
  6279. return false;
  6280. }
  6281. }
  6282. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6283. error = Error::Write;
  6284. return false;
  6285. }
  6286. error = Error::Success;
  6287. return true;
  6288. }
  6289. template <typename T>
  6290. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6291. size_t offset, size_t length, T is_shutting_down,
  6292. Error &error) {
  6293. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6294. is_shutting_down, nullptr, error);
  6295. }
  6296. template <typename T>
  6297. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6298. size_t offset, size_t length,
  6299. const T &is_shutting_down) {
  6300. auto error = Error::Success;
  6301. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6302. error);
  6303. }
  6304. template <typename T>
  6305. inline bool
  6306. write_content_without_length(Stream &strm,
  6307. const ContentProvider &content_provider,
  6308. const T &is_shutting_down) {
  6309. size_t offset = 0;
  6310. auto data_available = true;
  6311. auto ok = true;
  6312. DataSink data_sink;
  6313. data_sink.write = [&](const char *d, size_t l) -> bool {
  6314. if (ok) {
  6315. offset += l;
  6316. if (!write_data(strm, d, l)) { ok = false; }
  6317. }
  6318. return ok;
  6319. };
  6320. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6321. data_sink.done = [&](void) { data_available = false; };
  6322. while (data_available && !is_shutting_down()) {
  6323. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6324. return false;
  6325. } else if (!content_provider(offset, 0, data_sink)) {
  6326. return false;
  6327. } else if (!ok) {
  6328. return false;
  6329. }
  6330. }
  6331. return !data_available; // true only if done() was called, false if shutting
  6332. // down
  6333. }
  6334. template <typename T, typename U>
  6335. inline bool
  6336. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6337. const T &is_shutting_down, U &compressor, Error &error) {
  6338. size_t offset = 0;
  6339. auto data_available = true;
  6340. auto ok = true;
  6341. DataSink data_sink;
  6342. data_sink.write = [&](const char *d, size_t l) -> bool {
  6343. if (ok) {
  6344. data_available = l > 0;
  6345. offset += l;
  6346. std::string payload;
  6347. if (compressor.compress(d, l, false,
  6348. [&](const char *data, size_t data_len) {
  6349. payload.append(data, data_len);
  6350. return true;
  6351. })) {
  6352. if (!payload.empty()) {
  6353. // Emit chunked response header and footer for each chunk
  6354. auto chunk =
  6355. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6356. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6357. }
  6358. } else {
  6359. ok = false;
  6360. }
  6361. }
  6362. return ok;
  6363. };
  6364. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6365. auto done_with_trailer = [&](const Headers *trailer) {
  6366. if (!ok) { return; }
  6367. data_available = false;
  6368. std::string payload;
  6369. if (!compressor.compress(nullptr, 0, true,
  6370. [&](const char *data, size_t data_len) {
  6371. payload.append(data, data_len);
  6372. return true;
  6373. })) {
  6374. ok = false;
  6375. return;
  6376. }
  6377. if (!payload.empty()) {
  6378. // Emit chunked response header and footer for each chunk
  6379. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6380. if (!write_data(strm, chunk.data(), chunk.size())) {
  6381. ok = false;
  6382. return;
  6383. }
  6384. }
  6385. constexpr const char done_marker[] = "0\r\n";
  6386. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6387. // Trailer
  6388. if (trailer) {
  6389. for (const auto &kv : *trailer) {
  6390. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6391. if (!write_data(strm, field_line.data(), field_line.size())) {
  6392. ok = false;
  6393. }
  6394. }
  6395. }
  6396. constexpr const char crlf[] = "\r\n";
  6397. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6398. };
  6399. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6400. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6401. done_with_trailer(&trailer);
  6402. };
  6403. while (data_available && !is_shutting_down()) {
  6404. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6405. error = Error::Write;
  6406. return false;
  6407. } else if (!content_provider(offset, 0, data_sink)) {
  6408. error = Error::Canceled;
  6409. return false;
  6410. } else if (!ok) {
  6411. error = Error::Write;
  6412. return false;
  6413. }
  6414. }
  6415. if (data_available) { // exited due to is_shutting_down(), not done()
  6416. error = Error::Write;
  6417. return false;
  6418. }
  6419. error = Error::Success;
  6420. return true;
  6421. }
  6422. template <typename T, typename U>
  6423. inline bool write_content_chunked(Stream &strm,
  6424. const ContentProvider &content_provider,
  6425. const T &is_shutting_down, U &compressor) {
  6426. auto error = Error::Success;
  6427. return write_content_chunked(strm, content_provider, is_shutting_down,
  6428. compressor, error);
  6429. }
  6430. template <typename T>
  6431. inline bool redirect(T &cli, Request &req, Response &res,
  6432. const std::string &path, const std::string &location,
  6433. Error &error) {
  6434. Request new_req = req;
  6435. new_req.path = path;
  6436. new_req.redirect_count_ -= 1;
  6437. if (res.status == StatusCode::SeeOther_303 &&
  6438. (req.method != "GET" && req.method != "HEAD")) {
  6439. new_req.method = "GET";
  6440. new_req.body.clear();
  6441. new_req.headers.clear();
  6442. }
  6443. Response new_res;
  6444. auto ret = cli.send(new_req, new_res, error);
  6445. if (ret) {
  6446. req = std::move(new_req);
  6447. res = std::move(new_res);
  6448. if (res.location.empty()) { res.location = location; }
  6449. }
  6450. return ret;
  6451. }
  6452. inline std::string params_to_query_str(const Params &params) {
  6453. std::string query;
  6454. for (auto it = params.begin(); it != params.end(); ++it) {
  6455. if (it != params.begin()) { query += '&'; }
  6456. query += encode_query_component(it->first);
  6457. query += '=';
  6458. query += encode_query_component(it->second);
  6459. }
  6460. return query;
  6461. }
  6462. inline void parse_query_text(const char *data, std::size_t size,
  6463. Params &params) {
  6464. std::set<std::string> cache;
  6465. split(data, data + size, '&', [&](const char *b, const char *e) {
  6466. std::string kv(b, e);
  6467. if (cache.find(kv) != cache.end()) { return; }
  6468. cache.insert(std::move(kv));
  6469. std::string key;
  6470. std::string val;
  6471. divide(b, static_cast<std::size_t>(e - b), '=',
  6472. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6473. std::size_t rhs_size) {
  6474. key.assign(lhs_data, lhs_size);
  6475. val.assign(rhs_data, rhs_size);
  6476. });
  6477. if (!key.empty()) {
  6478. params.emplace(decode_query_component(key), decode_query_component(val));
  6479. }
  6480. });
  6481. }
  6482. inline void parse_query_text(const std::string &s, Params &params) {
  6483. parse_query_text(s.data(), s.size(), params);
  6484. }
  6485. // Normalize a query string by decoding and re-encoding each key/value pair
  6486. // while preserving the original parameter order. This avoids double-encoding
  6487. // and ensures consistent encoding without reordering (unlike Params which
  6488. // uses std::multimap and sorts keys).
  6489. inline std::string normalize_query_string(const std::string &query) {
  6490. std::string result;
  6491. split(query.data(), query.data() + query.size(), '&',
  6492. [&](const char *b, const char *e) {
  6493. std::string key;
  6494. std::string val;
  6495. divide(b, static_cast<std::size_t>(e - b), '=',
  6496. [&](const char *lhs_data, std::size_t lhs_size,
  6497. const char *rhs_data, std::size_t rhs_size) {
  6498. key.assign(lhs_data, lhs_size);
  6499. val.assign(rhs_data, rhs_size);
  6500. });
  6501. if (!key.empty()) {
  6502. auto dec_key = decode_query_component(key);
  6503. auto dec_val = decode_query_component(val);
  6504. if (!result.empty()) { result += '&'; }
  6505. result += encode_query_component(dec_key);
  6506. if (!val.empty() || std::find(b, e, '=') != e) {
  6507. result += '=';
  6508. result += encode_query_component(dec_val);
  6509. }
  6510. }
  6511. });
  6512. return result;
  6513. }
  6514. inline bool parse_multipart_boundary(const std::string &content_type,
  6515. std::string &boundary) {
  6516. std::map<std::string, std::string> params;
  6517. extract_media_type(content_type, &params);
  6518. auto it = params.find("boundary");
  6519. if (it == params.end()) { return false; }
  6520. boundary = it->second;
  6521. return !boundary.empty();
  6522. }
  6523. inline void parse_disposition_params(const std::string &s, Params &params) {
  6524. std::set<std::string> cache;
  6525. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6526. std::string kv(b, e);
  6527. if (cache.find(kv) != cache.end()) { return; }
  6528. cache.insert(kv);
  6529. std::string key;
  6530. std::string val;
  6531. split(b, e, '=', [&](const char *b2, const char *e2) {
  6532. if (key.empty()) {
  6533. key.assign(b2, e2);
  6534. } else {
  6535. val.assign(b2, e2);
  6536. }
  6537. });
  6538. if (!key.empty()) {
  6539. params.emplace(trim_double_quotes_copy((key)),
  6540. trim_double_quotes_copy((val)));
  6541. }
  6542. });
  6543. }
  6544. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6545. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6546. #else
  6547. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6548. #endif
  6549. auto is_valid = [](const std::string &str) {
  6550. return std::all_of(str.cbegin(), str.cend(),
  6551. [](unsigned char c) { return std::isdigit(c); });
  6552. };
  6553. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6554. const auto pos = static_cast<size_t>(6);
  6555. const auto len = static_cast<size_t>(s.size() - 6);
  6556. auto all_valid_ranges = true;
  6557. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6558. if (!all_valid_ranges) { return; }
  6559. const auto it = std::find(b, e, '-');
  6560. if (it == e) {
  6561. all_valid_ranges = false;
  6562. return;
  6563. }
  6564. const auto lhs = std::string(b, it);
  6565. const auto rhs = std::string(it + 1, e);
  6566. if (!is_valid(lhs) || !is_valid(rhs)) {
  6567. all_valid_ranges = false;
  6568. return;
  6569. }
  6570. ssize_t first = -1;
  6571. if (!lhs.empty()) {
  6572. ssize_t v;
  6573. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6574. if (res.ec == std::errc{}) { first = v; }
  6575. }
  6576. ssize_t last = -1;
  6577. if (!rhs.empty()) {
  6578. ssize_t v;
  6579. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6580. if (res.ec == std::errc{}) { last = v; }
  6581. }
  6582. if ((first == -1 && last == -1) ||
  6583. (first != -1 && last != -1 && first > last)) {
  6584. all_valid_ranges = false;
  6585. return;
  6586. }
  6587. ranges.emplace_back(first, last);
  6588. });
  6589. return all_valid_ranges && !ranges.empty();
  6590. }
  6591. return false;
  6592. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6593. }
  6594. #else
  6595. } catch (...) { return false; }
  6596. #endif
  6597. inline bool parse_accept_header(const std::string &s,
  6598. std::vector<std::string> &content_types) {
  6599. content_types.clear();
  6600. // Empty string is considered valid (no preference)
  6601. if (s.empty()) { return true; }
  6602. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6603. if (s.front() == ',' || s.back() == ',' ||
  6604. s.find(",,") != std::string::npos) {
  6605. return false;
  6606. }
  6607. struct AcceptEntry {
  6608. std::string media_type;
  6609. double quality;
  6610. int order;
  6611. };
  6612. std::vector<AcceptEntry> entries;
  6613. int order = 0;
  6614. bool has_invalid_entry = false;
  6615. // Split by comma and parse each entry
  6616. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6617. std::string entry(b, e);
  6618. entry = trim_copy(entry);
  6619. if (entry.empty()) {
  6620. has_invalid_entry = true;
  6621. return;
  6622. }
  6623. AcceptEntry accept_entry;
  6624. accept_entry.order = order++;
  6625. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6626. accept_entry.media_type, accept_entry.quality)) {
  6627. has_invalid_entry = true;
  6628. return;
  6629. }
  6630. // Remove additional parameters from media type
  6631. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6632. // Basic validation of media type format
  6633. if (accept_entry.media_type.empty()) {
  6634. has_invalid_entry = true;
  6635. return;
  6636. }
  6637. // Check for basic media type format (should contain '/' or be '*')
  6638. if (accept_entry.media_type != "*" &&
  6639. accept_entry.media_type.find('/') == std::string::npos) {
  6640. has_invalid_entry = true;
  6641. return;
  6642. }
  6643. entries.push_back(std::move(accept_entry));
  6644. });
  6645. // Return false if any invalid entry was found
  6646. if (has_invalid_entry) { return false; }
  6647. // Sort by quality (descending), then by original order (ascending)
  6648. std::sort(entries.begin(), entries.end(),
  6649. [](const AcceptEntry &a, const AcceptEntry &b) {
  6650. if (a.quality != b.quality) {
  6651. return a.quality > b.quality; // Higher quality first
  6652. }
  6653. return a.order < b.order; // Earlier order first for same quality
  6654. });
  6655. // Extract sorted media types
  6656. content_types.reserve(entries.size());
  6657. for (auto &entry : entries) {
  6658. content_types.push_back(std::move(entry.media_type));
  6659. }
  6660. return true;
  6661. }
  6662. class FormDataParser {
  6663. public:
  6664. FormDataParser() = default;
  6665. void set_boundary(std::string &&boundary) {
  6666. boundary_ = std::move(boundary);
  6667. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6668. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6669. }
  6670. bool is_valid() const { return is_valid_; }
  6671. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6672. const ContentReceiver &content_callback) {
  6673. buf_append(buf, n);
  6674. while (buf_size() > 0) {
  6675. switch (state_) {
  6676. case 0: { // Initial boundary
  6677. auto pos = buf_find(dash_boundary_crlf_);
  6678. if (pos == buf_size()) { return true; }
  6679. buf_erase(pos + dash_boundary_crlf_.size());
  6680. state_ = 1;
  6681. break;
  6682. }
  6683. case 1: { // New entry
  6684. clear_file_info();
  6685. state_ = 2;
  6686. break;
  6687. }
  6688. case 2: { // Headers
  6689. auto pos = buf_find(crlf_);
  6690. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6691. while (pos < buf_size()) {
  6692. // Empty line
  6693. if (pos == 0) {
  6694. if (!header_callback(file_)) {
  6695. is_valid_ = false;
  6696. return false;
  6697. }
  6698. buf_erase(crlf_.size());
  6699. state_ = 3;
  6700. break;
  6701. }
  6702. const auto header = buf_head(pos);
  6703. if (!parse_header(header.data(), header.data() + header.size(),
  6704. [&](const std::string &, const std::string &) {})) {
  6705. is_valid_ = false;
  6706. return false;
  6707. }
  6708. // Parse and emplace space trimmed headers into a map
  6709. if (!parse_header(
  6710. header.data(), header.data() + header.size(),
  6711. [&](const std::string &key, const std::string &val) {
  6712. file_.headers.emplace(key, val);
  6713. })) {
  6714. is_valid_ = false;
  6715. return false;
  6716. }
  6717. constexpr const char header_content_type[] = "Content-Type:";
  6718. if (start_with_case_ignore(header, header_content_type)) {
  6719. file_.content_type =
  6720. trim_copy(header.substr(str_len(header_content_type)));
  6721. } else {
  6722. std::string disposition_params;
  6723. if (parse_content_disposition(header, disposition_params)) {
  6724. Params params;
  6725. parse_disposition_params(disposition_params, params);
  6726. auto it = params.find("name");
  6727. if (it != params.end()) {
  6728. file_.name = it->second;
  6729. } else {
  6730. is_valid_ = false;
  6731. return false;
  6732. }
  6733. it = params.find("filename");
  6734. if (it != params.end()) { file_.filename = it->second; }
  6735. it = params.find("filename*");
  6736. if (it != params.end()) {
  6737. // RFC 5987: only UTF-8 encoding is allowed
  6738. const auto &val = it->second;
  6739. constexpr const char utf8_prefix[] = "UTF-8''";
  6740. constexpr size_t prefix_len = str_len(utf8_prefix);
  6741. if (val.size() > prefix_len &&
  6742. start_with_case_ignore(val, utf8_prefix)) {
  6743. file_.filename = decode_path_component(
  6744. val.substr(prefix_len)); // override...
  6745. } else {
  6746. is_valid_ = false;
  6747. return false;
  6748. }
  6749. }
  6750. }
  6751. }
  6752. buf_erase(pos + crlf_.size());
  6753. pos = buf_find(crlf_);
  6754. }
  6755. if (state_ != 3) { return true; }
  6756. break;
  6757. }
  6758. case 3: { // Body
  6759. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6760. auto pos = buf_find(crlf_dash_boundary_);
  6761. if (pos < buf_size()) {
  6762. if (!content_callback(buf_data(), pos)) {
  6763. is_valid_ = false;
  6764. return false;
  6765. }
  6766. buf_erase(pos + crlf_dash_boundary_.size());
  6767. state_ = 4;
  6768. } else {
  6769. auto len = buf_size() - crlf_dash_boundary_.size();
  6770. if (len > 0) {
  6771. if (!content_callback(buf_data(), len)) {
  6772. is_valid_ = false;
  6773. return false;
  6774. }
  6775. buf_erase(len);
  6776. }
  6777. return true;
  6778. }
  6779. break;
  6780. }
  6781. case 4: { // Boundary
  6782. if (crlf_.size() > buf_size()) { return true; }
  6783. if (buf_start_with(crlf_)) {
  6784. buf_erase(crlf_.size());
  6785. state_ = 1;
  6786. } else {
  6787. if (dash_.size() > buf_size()) { return true; }
  6788. if (buf_start_with(dash_)) {
  6789. buf_erase(dash_.size());
  6790. is_valid_ = true;
  6791. buf_erase(buf_size()); // Remove epilogue
  6792. } else {
  6793. return true;
  6794. }
  6795. }
  6796. break;
  6797. }
  6798. }
  6799. }
  6800. return true;
  6801. }
  6802. private:
  6803. void clear_file_info() {
  6804. file_.name.clear();
  6805. file_.filename.clear();
  6806. file_.content_type.clear();
  6807. file_.headers.clear();
  6808. }
  6809. bool start_with_case_ignore(const std::string &a, const char *b,
  6810. size_t offset = 0) const {
  6811. const auto b_len = strlen(b);
  6812. if (a.size() < offset + b_len) { return false; }
  6813. for (size_t i = 0; i < b_len; i++) {
  6814. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6815. return false;
  6816. }
  6817. }
  6818. return true;
  6819. }
  6820. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6821. // Returns true if header matches, with the params portion in `params_out`.
  6822. bool parse_content_disposition(const std::string &header,
  6823. std::string &params_out) const {
  6824. constexpr const char prefix[] = "Content-Disposition:";
  6825. constexpr size_t prefix_len = str_len(prefix);
  6826. if (!start_with_case_ignore(header, prefix)) { return false; }
  6827. // Skip whitespace after "Content-Disposition:"
  6828. auto pos = prefix_len;
  6829. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6830. pos++;
  6831. }
  6832. // Match "form-data;" (case-insensitive)
  6833. constexpr const char form_data[] = "form-data;";
  6834. constexpr size_t form_data_len = str_len(form_data);
  6835. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6836. pos += form_data_len;
  6837. // Skip whitespace after "form-data;"
  6838. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6839. pos++;
  6840. }
  6841. params_out = header.substr(pos);
  6842. return true;
  6843. }
  6844. const std::string dash_ = "--";
  6845. const std::string crlf_ = "\r\n";
  6846. std::string boundary_;
  6847. std::string dash_boundary_crlf_;
  6848. std::string crlf_dash_boundary_;
  6849. size_t state_ = 0;
  6850. bool is_valid_ = false;
  6851. FormData file_;
  6852. // Buffer
  6853. bool start_with(const std::string &a, size_t spos, size_t epos,
  6854. const std::string &b) const {
  6855. if (epos - spos < b.size()) { return false; }
  6856. for (size_t i = 0; i < b.size(); i++) {
  6857. if (a[i + spos] != b[i]) { return false; }
  6858. }
  6859. return true;
  6860. }
  6861. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6862. const char *buf_data() const { return &buf_[buf_spos_]; }
  6863. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6864. bool buf_start_with(const std::string &s) const {
  6865. return start_with(buf_, buf_spos_, buf_epos_, s);
  6866. }
  6867. size_t buf_find(const std::string &s) const {
  6868. auto c = s.front();
  6869. size_t off = buf_spos_;
  6870. while (off < buf_epos_) {
  6871. auto pos = off;
  6872. while (true) {
  6873. if (pos == buf_epos_) { return buf_size(); }
  6874. if (buf_[pos] == c) { break; }
  6875. pos++;
  6876. }
  6877. auto remaining_size = buf_epos_ - pos;
  6878. if (s.size() > remaining_size) { return buf_size(); }
  6879. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6880. off = pos + 1;
  6881. }
  6882. return buf_size();
  6883. }
  6884. void buf_append(const char *data, size_t n) {
  6885. auto remaining_size = buf_size();
  6886. if (remaining_size > 0 && buf_spos_ > 0) {
  6887. for (size_t i = 0; i < remaining_size; i++) {
  6888. buf_[i] = buf_[buf_spos_ + i];
  6889. }
  6890. }
  6891. buf_spos_ = 0;
  6892. buf_epos_ = remaining_size;
  6893. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6894. for (size_t i = 0; i < n; i++) {
  6895. buf_[buf_epos_ + i] = data[i];
  6896. }
  6897. buf_epos_ += n;
  6898. }
  6899. void buf_erase(size_t size) { buf_spos_ += size; }
  6900. std::string buf_;
  6901. size_t buf_spos_ = 0;
  6902. size_t buf_epos_ = 0;
  6903. };
  6904. inline std::string random_string(size_t length) {
  6905. constexpr const char data[] =
  6906. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6907. thread_local auto engine([]() {
  6908. // std::random_device might actually be deterministic on some
  6909. // platforms, but due to lack of support in the c++ standard library,
  6910. // doing better requires either some ugly hacks or breaking portability.
  6911. std::random_device seed_gen;
  6912. // Request 128 bits of entropy for initialization
  6913. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6914. return std::mt19937(seed_sequence);
  6915. }());
  6916. std::string result;
  6917. for (size_t i = 0; i < length; i++) {
  6918. result += data[engine() % (sizeof(data) - 1)];
  6919. }
  6920. return result;
  6921. }
  6922. inline std::string make_multipart_data_boundary() {
  6923. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6924. }
  6925. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6926. auto valid = true;
  6927. for (size_t i = 0; i < boundary.size(); i++) {
  6928. auto c = boundary[i];
  6929. if (!std::isalnum(static_cast<unsigned char>(c)) && c != '-' && c != '_') {
  6930. valid = false;
  6931. break;
  6932. }
  6933. }
  6934. return valid;
  6935. }
  6936. // Escape a multipart field name/filename following the WHATWG HTML standard
  6937. // ("escape a multipart form-data name"), which is what browsers send:
  6938. // '"' -> %22, CR -> %0D, LF -> %0A
  6939. inline std::string escape_multipart_field(const std::string &s) {
  6940. std::string result;
  6941. result.reserve(s.size());
  6942. for (auto c : s) {
  6943. switch (c) {
  6944. case '"': result += "%22"; break;
  6945. case '\r': result += "%0D"; break;
  6946. case '\n': result += "%0A"; break;
  6947. default: result += c; break;
  6948. }
  6949. }
  6950. return result;
  6951. }
  6952. template <typename T>
  6953. inline std::string
  6954. serialize_multipart_formdata_item_begin(const T &item,
  6955. const std::string &boundary) {
  6956. std::string body = "--" + boundary + "\r\n";
  6957. body += "Content-Disposition: form-data; name=\"" +
  6958. escape_multipart_field(item.name) + "\"";
  6959. if (!item.filename.empty()) {
  6960. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  6961. }
  6962. body += "\r\n";
  6963. if (!item.content_type.empty()) {
  6964. body += "Content-Type: " + item.content_type + "\r\n";
  6965. }
  6966. body += "\r\n";
  6967. return body;
  6968. }
  6969. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6970. inline std::string
  6971. serialize_multipart_formdata_finish(const std::string &boundary) {
  6972. return "--" + boundary + "--\r\n";
  6973. }
  6974. inline std::string
  6975. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6976. return "multipart/form-data; boundary=" + boundary;
  6977. }
  6978. inline std::string
  6979. serialize_multipart_formdata(const UploadFormDataItems &items,
  6980. const std::string &boundary, bool finish = true) {
  6981. std::string body;
  6982. for (const auto &item : items) {
  6983. body += serialize_multipart_formdata_item_begin(item, boundary);
  6984. body += item.content + serialize_multipart_formdata_item_end();
  6985. }
  6986. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  6987. return body;
  6988. }
  6989. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  6990. const std::string &boundary) {
  6991. size_t total = 0;
  6992. for (const auto &item : items) {
  6993. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  6994. total += item.content.size();
  6995. total += serialize_multipart_formdata_item_end().size();
  6996. }
  6997. total += serialize_multipart_formdata_finish(boundary).size();
  6998. return total;
  6999. }
  7000. struct MultipartSegment {
  7001. const char *data;
  7002. size_t size;
  7003. };
  7004. // NOTE: items must outlive the returned ContentProvider
  7005. // (safe for synchronous use inside Post/Put/Patch)
  7006. inline ContentProvider
  7007. make_multipart_content_provider(const UploadFormDataItems &items,
  7008. const std::string &boundary) {
  7009. // Own the per-item header strings and the finish string
  7010. std::vector<std::string> owned;
  7011. owned.reserve(items.size() + 1);
  7012. for (const auto &item : items)
  7013. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7014. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7015. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7016. std::vector<MultipartSegment> segs;
  7017. segs.reserve(items.size() * 3 + 1);
  7018. static const char crlf[] = "\r\n";
  7019. for (size_t i = 0; i < items.size(); i++) {
  7020. segs.push_back({owned[i].data(), owned[i].size()});
  7021. segs.push_back({items[i].content.data(), items[i].content.size()});
  7022. segs.push_back({crlf, 2});
  7023. }
  7024. segs.push_back({owned.back().data(), owned.back().size()});
  7025. struct MultipartState {
  7026. std::vector<std::string> owned;
  7027. std::vector<MultipartSegment> segs;
  7028. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7029. };
  7030. auto state = std::make_shared<MultipartState>();
  7031. state->owned = std::move(owned);
  7032. // `segs` holds raw pointers into owned strings; std::string move preserves
  7033. // the data pointer, so these pointers remain valid after the move above.
  7034. state->segs = std::move(segs);
  7035. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7036. // Buffer multiple small segments into fewer, larger writes to avoid
  7037. // excessive TCP packets when there are many form data items (#2410)
  7038. auto &buf = state->buf;
  7039. auto buf_size = buf.size();
  7040. size_t buf_len = 0;
  7041. size_t remaining = length;
  7042. // Find the first segment containing 'offset'
  7043. size_t pos = 0;
  7044. size_t seg_idx = 0;
  7045. for (; seg_idx < state->segs.size(); seg_idx++) {
  7046. const auto &seg = state->segs[seg_idx];
  7047. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7048. pos += seg.size;
  7049. }
  7050. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7051. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7052. const auto &seg = state->segs[seg_idx];
  7053. size_t available = seg.size - seg_offset;
  7054. size_t to_copy = (std::min)(available, remaining);
  7055. const char *src = seg.data + seg_offset;
  7056. seg_offset = 0; // only the first segment has a non-zero offset
  7057. while (to_copy > 0) {
  7058. size_t space = buf_size - buf_len;
  7059. size_t chunk = (std::min)(to_copy, space);
  7060. std::memcpy(buf.data() + buf_len, src, chunk);
  7061. buf_len += chunk;
  7062. src += chunk;
  7063. to_copy -= chunk;
  7064. remaining -= chunk;
  7065. if (buf_len == buf_size) {
  7066. if (!sink.write(buf.data(), buf_len)) { return false; }
  7067. buf_len = 0;
  7068. }
  7069. }
  7070. }
  7071. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7072. return true;
  7073. };
  7074. }
  7075. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7076. if (ranges.size() <= 1) return;
  7077. // Sort ranges by start position
  7078. std::sort(ranges.begin(), ranges.end(),
  7079. [](const Range &a, const Range &b) { return a.first < b.first; });
  7080. Ranges coalesced;
  7081. coalesced.reserve(ranges.size());
  7082. for (auto &r : ranges) {
  7083. auto first_pos = r.first;
  7084. auto last_pos = r.second;
  7085. // Handle special cases like in range_error
  7086. if (first_pos == -1 && last_pos == -1) {
  7087. first_pos = 0;
  7088. last_pos = static_cast<ssize_t>(content_length);
  7089. }
  7090. if (first_pos == -1) {
  7091. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7092. last_pos = static_cast<ssize_t>(content_length) - 1;
  7093. }
  7094. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7095. last_pos = static_cast<ssize_t>(content_length) - 1;
  7096. }
  7097. // Skip invalid ranges
  7098. if (!(0 <= first_pos && first_pos <= last_pos &&
  7099. last_pos < static_cast<ssize_t>(content_length))) {
  7100. continue;
  7101. }
  7102. // Coalesce with previous range if overlapping or adjacent (but not
  7103. // identical)
  7104. if (!coalesced.empty()) {
  7105. auto &prev = coalesced.back();
  7106. // Check if current range overlaps or is adjacent to previous range
  7107. // but don't coalesce identical ranges (allow duplicates)
  7108. if (first_pos <= prev.second + 1 &&
  7109. !(first_pos == prev.first && last_pos == prev.second)) {
  7110. // Extend the previous range
  7111. prev.second = (std::max)(prev.second, last_pos);
  7112. continue;
  7113. }
  7114. }
  7115. // Add new range
  7116. coalesced.emplace_back(first_pos, last_pos);
  7117. }
  7118. ranges = std::move(coalesced);
  7119. }
  7120. inline bool range_error(Request &req, Response &res) {
  7121. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7122. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7123. req.ranges.clear();
  7124. if (res.status == StatusCode::PartialContent_206) {
  7125. res.status = StatusCode::OK_200;
  7126. }
  7127. return false;
  7128. }
  7129. ssize_t content_len = static_cast<ssize_t>(
  7130. res.content_length_ ? res.content_length_ : res.body.size());
  7131. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7132. size_t overwrapping_count = 0;
  7133. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7134. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7135. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7136. // Too many ranges
  7137. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7138. for (auto &r : req.ranges) {
  7139. auto &first_pos = r.first;
  7140. auto &last_pos = r.second;
  7141. if (first_pos == -1 && last_pos == -1) {
  7142. first_pos = 0;
  7143. last_pos = content_len;
  7144. }
  7145. if (first_pos == -1) {
  7146. first_pos = content_len - last_pos;
  7147. last_pos = content_len - 1;
  7148. }
  7149. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7150. // A client can limit the number of bytes requested without knowing the
  7151. // size of the selected representation. If the last-pos value is absent,
  7152. // or if the value is greater than or equal to the current length of the
  7153. // representation data, the byte range is interpreted as the remainder of
  7154. // the representation (i.e., the server replaces the value of last-pos
  7155. // with a value that is one less than the current length of the selected
  7156. // representation).
  7157. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7158. if (last_pos == -1 || last_pos >= content_len) {
  7159. last_pos = content_len - 1;
  7160. }
  7161. // Range must be within content length
  7162. if (!(0 <= first_pos && first_pos <= last_pos &&
  7163. last_pos <= content_len - 1)) {
  7164. return true;
  7165. }
  7166. // Request must not have more than two overlapping ranges
  7167. for (const auto &processed_range : processed_ranges) {
  7168. if (!(last_pos < processed_range.first ||
  7169. first_pos > processed_range.second)) {
  7170. overwrapping_count++;
  7171. if (overwrapping_count > 2) { return true; }
  7172. break; // Only count once per range
  7173. }
  7174. }
  7175. processed_ranges.emplace_back(first_pos, last_pos);
  7176. }
  7177. // After validation, coalesce overlapping ranges as per RFC 9110
  7178. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7179. }
  7180. return false;
  7181. }
  7182. inline std::pair<size_t, size_t>
  7183. get_range_offset_and_length(Range r, size_t content_length) {
  7184. assert(r.first != -1 && r.second != -1);
  7185. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7186. assert(r.first <= r.second &&
  7187. r.second < static_cast<ssize_t>(content_length));
  7188. (void)(content_length);
  7189. return std::make_pair(static_cast<size_t>(r.first),
  7190. static_cast<size_t>(r.second - r.first) + 1);
  7191. }
  7192. inline std::string make_content_range_header_field(
  7193. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7194. auto st = offset_and_length.first;
  7195. auto ed = st + offset_and_length.second - 1;
  7196. std::string field = "bytes ";
  7197. field += std::to_string(st);
  7198. field += '-';
  7199. field += std::to_string(ed);
  7200. field += '/';
  7201. field += std::to_string(content_length);
  7202. return field;
  7203. }
  7204. template <typename SToken, typename CToken, typename Content>
  7205. bool process_multipart_ranges_data(const Request &req,
  7206. const std::string &boundary,
  7207. const std::string &content_type,
  7208. size_t content_length, SToken stoken,
  7209. CToken ctoken, Content content) {
  7210. for (size_t i = 0; i < req.ranges.size(); i++) {
  7211. ctoken("--");
  7212. stoken(boundary);
  7213. ctoken("\r\n");
  7214. if (!content_type.empty()) {
  7215. ctoken("Content-Type: ");
  7216. stoken(content_type);
  7217. ctoken("\r\n");
  7218. }
  7219. auto offset_and_length =
  7220. get_range_offset_and_length(req.ranges[i], content_length);
  7221. ctoken("Content-Range: ");
  7222. stoken(make_content_range_header_field(offset_and_length, content_length));
  7223. ctoken("\r\n");
  7224. ctoken("\r\n");
  7225. if (!content(offset_and_length.first, offset_and_length.second)) {
  7226. return false;
  7227. }
  7228. ctoken("\r\n");
  7229. }
  7230. ctoken("--");
  7231. stoken(boundary);
  7232. ctoken("--");
  7233. return true;
  7234. }
  7235. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7236. const std::string &boundary,
  7237. const std::string &content_type,
  7238. size_t content_length,
  7239. std::string &data) {
  7240. process_multipart_ranges_data(
  7241. req, boundary, content_type, content_length,
  7242. [&](const std::string &token) { data += token; },
  7243. [&](const std::string &token) { data += token; },
  7244. [&](size_t offset, size_t length) {
  7245. assert(offset + length <= content_length);
  7246. data += res.body.substr(offset, length);
  7247. return true;
  7248. });
  7249. }
  7250. inline size_t get_multipart_ranges_data_length(const Request &req,
  7251. const std::string &boundary,
  7252. const std::string &content_type,
  7253. size_t content_length) {
  7254. size_t data_length = 0;
  7255. process_multipart_ranges_data(
  7256. req, boundary, content_type, content_length,
  7257. [&](const std::string &token) { data_length += token.size(); },
  7258. [&](const std::string &token) { data_length += token.size(); },
  7259. [&](size_t /*offset*/, size_t length) {
  7260. data_length += length;
  7261. return true;
  7262. });
  7263. return data_length;
  7264. }
  7265. template <typename T>
  7266. inline bool
  7267. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7268. const std::string &boundary,
  7269. const std::string &content_type,
  7270. size_t content_length, const T &is_shutting_down) {
  7271. return process_multipart_ranges_data(
  7272. req, boundary, content_type, content_length,
  7273. [&](const std::string &token) { strm.write(token); },
  7274. [&](const std::string &token) { strm.write(token); },
  7275. [&](size_t offset, size_t length) {
  7276. return write_content(strm, res.content_provider_, offset, length,
  7277. is_shutting_down);
  7278. });
  7279. }
  7280. inline bool has_framed_body(const Request &req) {
  7281. return is_chunked_transfer_encoding(req.headers) ||
  7282. req.get_header_value_u64("Content-Length") > 0;
  7283. }
  7284. inline bool is_connection_persistent(const Request &req) {
  7285. auto conn = req.get_header_value("Connection");
  7286. if (conn == "close") { return false; }
  7287. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7288. return true;
  7289. }
  7290. inline bool expect_content(const Request &req) {
  7291. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7292. req.method == "DELETE") {
  7293. return true;
  7294. }
  7295. return has_framed_body(req);
  7296. }
  7297. #ifdef _WIN32
  7298. class WSInit {
  7299. public:
  7300. WSInit() {
  7301. WSADATA wsaData;
  7302. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7303. }
  7304. ~WSInit() {
  7305. if (is_valid_) WSACleanup();
  7306. }
  7307. bool is_valid_ = false;
  7308. };
  7309. static WSInit wsinit_;
  7310. #endif
  7311. inline bool parse_www_authenticate(const Response &res,
  7312. std::map<std::string, std::string> &auth,
  7313. bool is_proxy) {
  7314. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7315. if (res.has_header(auth_key)) {
  7316. thread_local auto re =
  7317. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7318. auto s = res.get_header_value(auth_key);
  7319. auto pos = s.find(' ');
  7320. if (pos != std::string::npos) {
  7321. auto type = s.substr(0, pos);
  7322. if (type == "Basic") {
  7323. return false;
  7324. } else if (type == "Digest") {
  7325. s = s.substr(pos + 1);
  7326. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7327. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7328. const auto &m = *i;
  7329. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7330. static_cast<size_t>(m.length(1)));
  7331. auto val = m.length(2) > 0
  7332. ? s.substr(static_cast<size_t>(m.position(2)),
  7333. static_cast<size_t>(m.length(2)))
  7334. : s.substr(static_cast<size_t>(m.position(3)),
  7335. static_cast<size_t>(m.length(3)));
  7336. auth[std::move(key)] = std::move(val);
  7337. }
  7338. return true;
  7339. }
  7340. }
  7341. }
  7342. return false;
  7343. }
  7344. class ContentProviderAdapter {
  7345. public:
  7346. explicit ContentProviderAdapter(
  7347. ContentProviderWithoutLength &&content_provider)
  7348. : content_provider_(std::move(content_provider)) {}
  7349. bool operator()(size_t offset, size_t, DataSink &sink) {
  7350. return content_provider_(offset, sink);
  7351. }
  7352. private:
  7353. ContentProviderWithoutLength content_provider_;
  7354. };
  7355. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7356. namespace fields {
  7357. inline bool is_token_char(char c) {
  7358. return std::isalnum(static_cast<unsigned char>(c)) || c == '!' || c == '#' ||
  7359. c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' ||
  7360. c == '+' || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' ||
  7361. c == '|' || c == '~';
  7362. }
  7363. inline bool is_token(const std::string &s) {
  7364. if (s.empty()) { return false; }
  7365. for (auto c : s) {
  7366. if (!is_token_char(c)) { return false; }
  7367. }
  7368. return true;
  7369. }
  7370. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7371. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7372. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7373. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7374. inline bool is_field_content(const std::string &s) {
  7375. if (s.empty()) { return true; }
  7376. if (s.size() == 1) {
  7377. return is_field_vchar(s[0]);
  7378. } else if (s.size() == 2) {
  7379. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7380. } else {
  7381. size_t i = 0;
  7382. if (!is_field_vchar(s[i])) { return false; }
  7383. i++;
  7384. while (i < s.size() - 1) {
  7385. auto c = s[i++];
  7386. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7387. } else {
  7388. return false;
  7389. }
  7390. }
  7391. return is_field_vchar(s[i]);
  7392. }
  7393. }
  7394. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7395. } // namespace fields
  7396. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7397. int port, const std::string &path,
  7398. const Headers &headers,
  7399. std::string &selected_subprotocol) {
  7400. // Validate path and host
  7401. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7402. return false;
  7403. }
  7404. // Validate user-provided headers
  7405. for (const auto &h : headers) {
  7406. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7407. return false;
  7408. }
  7409. }
  7410. // Generate random Sec-WebSocket-Key
  7411. thread_local std::mt19937 rng(std::random_device{}());
  7412. std::string key_bytes(16, '\0');
  7413. for (size_t i = 0; i < 16; i += 4) {
  7414. auto r = rng();
  7415. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7416. }
  7417. auto client_key = base64_encode(key_bytes);
  7418. // Build upgrade request
  7419. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7420. req_str += "Host: " + host + ":" + std::to_string(port) + "\r\n";
  7421. req_str += "Upgrade: websocket\r\n";
  7422. req_str += "Connection: Upgrade\r\n";
  7423. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7424. req_str += "Sec-WebSocket-Version: 13\r\n";
  7425. for (const auto &h : headers) {
  7426. req_str += h.first + ": " + h.second + "\r\n";
  7427. }
  7428. req_str += "\r\n";
  7429. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7430. // Verify 101 response and Sec-WebSocket-Accept header
  7431. auto expected_accept = websocket_accept_key(client_key);
  7432. return read_websocket_upgrade_response(strm, expected_accept,
  7433. selected_subprotocol);
  7434. }
  7435. } // namespace detail
  7436. /*
  7437. * Group 2: detail namespace - SSL common utilities
  7438. */
  7439. #ifdef CPPHTTPLIB_SSL_ENABLED
  7440. namespace detail {
  7441. class SSLSocketStream final : public Stream {
  7442. public:
  7443. SSLSocketStream(
  7444. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7445. time_t read_timeout_usec, time_t write_timeout_sec,
  7446. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7447. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7448. (std::chrono::steady_clock::time_point::min)());
  7449. ~SSLSocketStream() override;
  7450. bool is_readable() const override;
  7451. bool wait_readable() const override;
  7452. bool wait_writable() const override;
  7453. bool is_peer_alive() const override;
  7454. ssize_t read(char *ptr, size_t size) override;
  7455. ssize_t write(const char *ptr, size_t size) override;
  7456. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7457. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7458. socket_t socket() const override;
  7459. time_t duration() const override;
  7460. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7461. private:
  7462. socket_t sock_;
  7463. tls::session_t session_;
  7464. time_t read_timeout_sec_;
  7465. time_t read_timeout_usec_;
  7466. time_t write_timeout_sec_;
  7467. time_t write_timeout_usec_;
  7468. time_t max_timeout_msec_;
  7469. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7470. };
  7471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7472. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7473. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7474. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7475. unsigned int hash_length = 0;
  7476. unsigned char hash[EVP_MAX_MD_SIZE];
  7477. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7478. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7479. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7480. std::stringstream ss;
  7481. for (auto i = 0u; i < hash_length; ++i) {
  7482. ss << std::hex << std::setw(2) << std::setfill('0')
  7483. << static_cast<unsigned int>(hash[i]);
  7484. }
  7485. return ss.str();
  7486. }
  7487. inline std::string MD5(const std::string &s) {
  7488. return message_digest(s, EVP_md5());
  7489. }
  7490. inline std::string SHA_256(const std::string &s) {
  7491. return message_digest(s, EVP_sha256());
  7492. }
  7493. inline std::string SHA_512(const std::string &s) {
  7494. return message_digest(s, EVP_sha512());
  7495. }
  7496. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7497. namespace {
  7498. template <size_t N>
  7499. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7500. std::stringstream ss;
  7501. for (size_t i = 0; i < N; ++i) {
  7502. ss << std::hex << std::setw(2) << std::setfill('0')
  7503. << static_cast<unsigned int>(hash[i]);
  7504. }
  7505. return ss.str();
  7506. }
  7507. } // namespace
  7508. inline std::string MD5(const std::string &s) {
  7509. unsigned char hash[16];
  7510. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7511. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7512. hash);
  7513. #else
  7514. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7515. hash);
  7516. #endif
  7517. return hash_to_hex(hash);
  7518. }
  7519. inline std::string SHA_256(const std::string &s) {
  7520. unsigned char hash[32];
  7521. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7522. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7523. hash, 0);
  7524. #else
  7525. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7526. s.size(), hash, 0);
  7527. #endif
  7528. return hash_to_hex(hash);
  7529. }
  7530. inline std::string SHA_512(const std::string &s) {
  7531. unsigned char hash[64];
  7532. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7533. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7534. hash, 0);
  7535. #else
  7536. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7537. s.size(), hash, 0);
  7538. #endif
  7539. return hash_to_hex(hash);
  7540. }
  7541. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7542. namespace {
  7543. template <size_t N>
  7544. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7545. std::stringstream ss;
  7546. for (size_t i = 0; i < N; ++i) {
  7547. ss << std::hex << std::setw(2) << std::setfill('0')
  7548. << static_cast<unsigned int>(hash[i]);
  7549. }
  7550. return ss.str();
  7551. }
  7552. } // namespace
  7553. inline std::string MD5(const std::string &s) {
  7554. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7555. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7556. static_cast<word32>(s.size()), hash);
  7557. return hash_to_hex(hash);
  7558. }
  7559. inline std::string SHA_256(const std::string &s) {
  7560. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7561. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7562. static_cast<word32>(s.size()), hash);
  7563. return hash_to_hex(hash);
  7564. }
  7565. inline std::string SHA_512(const std::string &s) {
  7566. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7567. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7568. static_cast<word32>(s.size()), hash);
  7569. return hash_to_hex(hash);
  7570. }
  7571. #endif
  7572. inline bool is_ip_address(const std::string &host) {
  7573. struct in_addr addr4;
  7574. struct in6_addr addr6;
  7575. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7576. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7577. }
  7578. template <typename T>
  7579. inline bool process_server_socket_ssl(
  7580. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7581. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7582. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7583. time_t write_timeout_usec, T callback) {
  7584. return process_server_socket_core(
  7585. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7586. [&](bool close_connection, bool &connection_closed) {
  7587. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7588. write_timeout_sec, write_timeout_usec);
  7589. return callback(strm, close_connection, connection_closed);
  7590. });
  7591. }
  7592. template <typename T>
  7593. inline bool process_client_socket_ssl(
  7594. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7595. time_t read_timeout_usec, time_t write_timeout_sec,
  7596. time_t write_timeout_usec, time_t max_timeout_msec,
  7597. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7598. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7599. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7600. start_time);
  7601. return callback(strm);
  7602. }
  7603. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7604. const Request &req, const std::map<std::string, std::string> &auth,
  7605. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7606. const std::string &password, bool is_proxy = false) {
  7607. std::string nc;
  7608. {
  7609. std::stringstream ss;
  7610. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7611. nc = ss.str();
  7612. }
  7613. std::string qop;
  7614. if (auth.find("qop") != auth.end()) {
  7615. qop = auth.at("qop");
  7616. if (qop.find("auth-int") != std::string::npos) {
  7617. qop = "auth-int";
  7618. } else if (qop.find("auth") != std::string::npos) {
  7619. qop = "auth";
  7620. } else {
  7621. qop.clear();
  7622. }
  7623. }
  7624. std::string algo = "MD5";
  7625. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7626. std::string response;
  7627. {
  7628. auto H = algo == "SHA-256" ? detail::SHA_256
  7629. : algo == "SHA-512" ? detail::SHA_512
  7630. : detail::MD5;
  7631. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7632. auto A2 = req.method + ":" + req.path;
  7633. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7634. if (qop.empty()) {
  7635. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7636. } else {
  7637. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7638. ":" + qop + ":" + H(A2));
  7639. }
  7640. }
  7641. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7642. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7643. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7644. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7645. (qop.empty() ? ", response=\""
  7646. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7647. cnonce + "\", response=\"") +
  7648. response + "\"" +
  7649. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7650. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7651. return std::make_pair(key, field);
  7652. }
  7653. inline bool match_hostname(const std::string &pattern,
  7654. const std::string &hostname) {
  7655. // Exact match (case-insensitive)
  7656. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7657. // Split both pattern and hostname into components by '.'
  7658. std::vector<std::string> pattern_components;
  7659. if (!pattern.empty()) {
  7660. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7661. [&](const char *b, const char *e) {
  7662. pattern_components.emplace_back(b, e);
  7663. });
  7664. }
  7665. std::vector<std::string> host_components;
  7666. if (!hostname.empty()) {
  7667. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7668. [&](const char *b, const char *e) {
  7669. host_components.emplace_back(b, e);
  7670. });
  7671. }
  7672. // Component count must match
  7673. if (host_components.size() != pattern_components.size()) { return false; }
  7674. // Compare each component with wildcard support
  7675. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7676. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7677. auto itr = pattern_components.begin();
  7678. for (const auto &h : host_components) {
  7679. auto &p = *itr;
  7680. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7681. bool partial_match = false;
  7682. if (!p.empty() && p[p.size() - 1] == '*') {
  7683. const auto prefix_length = p.size() - 1;
  7684. if (prefix_length == 0) {
  7685. partial_match = true;
  7686. } else if (h.size() >= prefix_length) {
  7687. partial_match =
  7688. std::equal(p.begin(),
  7689. p.begin() + static_cast<std::string::difference_type>(
  7690. prefix_length),
  7691. h.begin(), [](const char ca, const char cb) {
  7692. return detail::case_ignore::to_lower(ca) ==
  7693. detail::case_ignore::to_lower(cb);
  7694. });
  7695. }
  7696. }
  7697. if (!partial_match) { return false; }
  7698. }
  7699. ++itr;
  7700. }
  7701. return true;
  7702. }
  7703. #ifdef _WIN32
  7704. // Verify certificate using Windows CertGetCertificateChain API.
  7705. // This provides real-time certificate validation with Windows Update
  7706. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7707. inline bool
  7708. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7709. const std::string &hostname,
  7710. bool verify_hostname, uint64_t &out_error) {
  7711. if (der_cert.empty()) { return false; }
  7712. out_error = 0;
  7713. // Create Windows certificate context from DER data
  7714. auto cert_context = CertCreateCertificateContext(
  7715. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7716. static_cast<DWORD>(der_cert.size()));
  7717. if (!cert_context) {
  7718. out_error = GetLastError();
  7719. return false;
  7720. }
  7721. auto cert_guard =
  7722. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7723. // Setup chain parameters
  7724. CERT_CHAIN_PARA chain_para = {};
  7725. chain_para.cbSize = sizeof(chain_para);
  7726. // Build certificate chain with revocation checking
  7727. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7728. auto chain_result = CertGetCertificateChain(
  7729. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7730. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7731. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7732. nullptr, &chain_context);
  7733. if (!chain_result || !chain_context) {
  7734. out_error = GetLastError();
  7735. return false;
  7736. }
  7737. auto chain_guard =
  7738. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7739. // Check if chain has errors
  7740. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7741. out_error = chain_context->TrustStatus.dwErrorStatus;
  7742. return false;
  7743. }
  7744. // Verify SSL policy
  7745. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7746. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7747. #ifdef AUTHTYPE_SERVER
  7748. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7749. #endif
  7750. std::wstring whost;
  7751. if (verify_hostname) {
  7752. whost = u8string_to_wstring(hostname.c_str());
  7753. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7754. }
  7755. CERT_CHAIN_POLICY_PARA policy_para = {};
  7756. policy_para.cbSize = sizeof(policy_para);
  7757. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7758. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7759. #else
  7760. policy_para.dwFlags = 0;
  7761. #endif
  7762. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7763. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7764. policy_status.cbSize = sizeof(policy_status);
  7765. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7766. &policy_para, &policy_status)) {
  7767. out_error = GetLastError();
  7768. return false;
  7769. }
  7770. if (policy_status.dwError != 0) {
  7771. out_error = policy_status.dwError;
  7772. return false;
  7773. }
  7774. return true;
  7775. }
  7776. #endif // _WIN32
  7777. // Loads CA file/dir configuration and applies the system CA policy to a
  7778. // client TLS context. PEM data and native stores are applied to the context
  7779. // directly at set time; has_custom_store reflects them for the Auto policy
  7780. // decision.
  7781. inline bool load_client_ca_config(tls::ctx_t ctx,
  7782. const std::string &ca_cert_file_path,
  7783. const std::string &ca_cert_dir_path,
  7784. bool has_custom_store, SystemCAMode mode,
  7785. uint64_t &backend_error) {
  7786. auto ret = true;
  7787. if (!ca_cert_file_path.empty()) {
  7788. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7789. backend_error = tls::get_error();
  7790. ret = false;
  7791. }
  7792. } else if (!ca_cert_dir_path.empty()) {
  7793. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7794. backend_error = tls::get_error();
  7795. ret = false;
  7796. }
  7797. }
  7798. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7799. !ca_cert_dir_path.empty() || has_custom_store;
  7800. if (mode == SystemCAMode::Enabled ||
  7801. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7802. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7803. }
  7804. return ret;
  7805. }
  7806. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7807. tls::session_t &session, socket_t sock,
  7808. bool server_certificate_verification,
  7809. time_t timeout_sec, time_t timeout_usec) {
  7810. using namespace tls;
  7811. if (!ctx) { return false; }
  7812. bool is_ip = is_ip_address(host);
  7813. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7814. // Chain verification happens during the handshake even for IP hosts; the
  7815. // certificate identity is verified post-handshake via verify_hostname()
  7816. set_verify_client(ctx, server_certificate_verification);
  7817. #endif
  7818. session = create_session(ctx, sock);
  7819. if (!session) { return false; }
  7820. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7821. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7822. // their identity is checked post-handshake below instead.
  7823. if (!is_ip) {
  7824. if (server_certificate_verification) {
  7825. set_hostname(session, host.c_str());
  7826. } else {
  7827. set_sni(session, host.c_str());
  7828. }
  7829. }
  7830. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7831. return false;
  7832. }
  7833. if (server_certificate_verification) {
  7834. if (get_verify_result(session) != 0) { return false; }
  7835. // Identity check against the peer certificate, post-handshake for all
  7836. // backends (same as SSLClient). For IP hosts this is the only identity
  7837. // verification since no hostname is bound during the handshake.
  7838. auto server_cert = get_peer_cert(session);
  7839. if (!server_cert) { return false; }
  7840. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7841. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7842. }
  7843. return true;
  7844. }
  7845. } // namespace detail
  7846. #endif // CPPHTTPLIB_SSL_ENABLED
  7847. /*
  7848. * Group 3: httplib namespace - Non-SSL public API implementations
  7849. */
  7850. inline void default_socket_options(socket_t sock) {
  7851. set_socket_opt(sock, SOL_SOCKET,
  7852. #ifdef SO_REUSEPORT
  7853. SO_REUSEPORT,
  7854. #else
  7855. SO_REUSEADDR,
  7856. #endif
  7857. 1);
  7858. }
  7859. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7860. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7861. sizeof(optval));
  7862. }
  7863. inline std::string get_bearer_token_auth(const Request &req) {
  7864. if (req.has_header("Authorization")) {
  7865. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7866. return req.get_header_value("Authorization")
  7867. .substr(bearer_header_prefix_len);
  7868. }
  7869. return "";
  7870. }
  7871. inline const char *status_message(int status) {
  7872. switch (status) {
  7873. case StatusCode::Continue_100: return "Continue";
  7874. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7875. case StatusCode::Processing_102: return "Processing";
  7876. case StatusCode::EarlyHints_103: return "Early Hints";
  7877. case StatusCode::OK_200: return "OK";
  7878. case StatusCode::Created_201: return "Created";
  7879. case StatusCode::Accepted_202: return "Accepted";
  7880. case StatusCode::NonAuthoritativeInformation_203:
  7881. return "Non-Authoritative Information";
  7882. case StatusCode::NoContent_204: return "No Content";
  7883. case StatusCode::ResetContent_205: return "Reset Content";
  7884. case StatusCode::PartialContent_206: return "Partial Content";
  7885. case StatusCode::MultiStatus_207: return "Multi-Status";
  7886. case StatusCode::AlreadyReported_208: return "Already Reported";
  7887. case StatusCode::IMUsed_226: return "IM Used";
  7888. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7889. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7890. case StatusCode::Found_302: return "Found";
  7891. case StatusCode::SeeOther_303: return "See Other";
  7892. case StatusCode::NotModified_304: return "Not Modified";
  7893. case StatusCode::UseProxy_305: return "Use Proxy";
  7894. case StatusCode::unused_306: return "unused";
  7895. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7896. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7897. case StatusCode::BadRequest_400: return "Bad Request";
  7898. case StatusCode::Unauthorized_401: return "Unauthorized";
  7899. case StatusCode::PaymentRequired_402: return "Payment Required";
  7900. case StatusCode::Forbidden_403: return "Forbidden";
  7901. case StatusCode::NotFound_404: return "Not Found";
  7902. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7903. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7904. case StatusCode::ProxyAuthenticationRequired_407:
  7905. return "Proxy Authentication Required";
  7906. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7907. case StatusCode::Conflict_409: return "Conflict";
  7908. case StatusCode::Gone_410: return "Gone";
  7909. case StatusCode::LengthRequired_411: return "Length Required";
  7910. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7911. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7912. case StatusCode::UriTooLong_414: return "URI Too Long";
  7913. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7914. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7915. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7916. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7917. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7918. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7919. case StatusCode::Locked_423: return "Locked";
  7920. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7921. case StatusCode::TooEarly_425: return "Too Early";
  7922. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7923. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7924. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7925. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7926. return "Request Header Fields Too Large";
  7927. case StatusCode::UnavailableForLegalReasons_451:
  7928. return "Unavailable For Legal Reasons";
  7929. case StatusCode::NotImplemented_501: return "Not Implemented";
  7930. case StatusCode::BadGateway_502: return "Bad Gateway";
  7931. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7932. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7933. case StatusCode::HttpVersionNotSupported_505:
  7934. return "HTTP Version Not Supported";
  7935. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7936. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7937. case StatusCode::LoopDetected_508: return "Loop Detected";
  7938. case StatusCode::NotExtended_510: return "Not Extended";
  7939. case StatusCode::NetworkAuthenticationRequired_511:
  7940. return "Network Authentication Required";
  7941. default:
  7942. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7943. }
  7944. }
  7945. inline std::string to_string(const Error error) {
  7946. switch (error) {
  7947. case Error::Success: return "Success (no error)";
  7948. case Error::Unknown: return "Unknown";
  7949. case Error::Connection: return "Could not establish connection";
  7950. case Error::BindIPAddress: return "Failed to bind IP address";
  7951. case Error::Read: return "Failed to read connection";
  7952. case Error::Write: return "Failed to write connection";
  7953. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7954. case Error::Canceled: return "Connection handling canceled";
  7955. case Error::SSLConnection: return "SSL connection failed";
  7956. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7957. case Error::SSLServerVerification: return "SSL server verification failed";
  7958. case Error::SSLServerHostnameVerification:
  7959. return "SSL server hostname verification failed";
  7960. case Error::UnsupportedMultipartBoundaryChars:
  7961. return "Unsupported HTTP multipart boundary characters";
  7962. case Error::Compression: return "Compression failed";
  7963. case Error::ConnectionTimeout: return "Connection timed out";
  7964. case Error::ProxyConnection: return "Proxy connection failed";
  7965. case Error::ConnectionClosed: return "Connection closed by server";
  7966. case Error::Timeout: return "Read timeout";
  7967. case Error::ResourceExhaustion: return "Resource exhaustion";
  7968. case Error::TooManyFormDataFiles: return "Too many form data files";
  7969. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7970. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7971. case Error::ExceedMaxSocketDescriptorCount:
  7972. return "Exceeded maximum socket descriptor count";
  7973. case Error::InvalidRequestLine: return "Invalid request line";
  7974. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7975. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7976. case Error::InvalidHeaders: return "Invalid headers";
  7977. case Error::MultipartParsing: return "Multipart parsing failed";
  7978. case Error::OpenFile: return "Failed to open file";
  7979. case Error::Listen: return "Failed to listen on socket";
  7980. case Error::GetSockName: return "Failed to get socket name";
  7981. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  7982. case Error::HTTPParsing: return "HTTP parsing failed";
  7983. case Error::InvalidRangeHeader: return "Invalid Range header";
  7984. default: break;
  7985. }
  7986. return "Invalid";
  7987. }
  7988. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  7989. os << to_string(obj);
  7990. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  7991. return os;
  7992. }
  7993. inline std::string hosted_at(const std::string &hostname) {
  7994. std::vector<std::string> addrs;
  7995. hosted_at(hostname, addrs);
  7996. if (addrs.empty()) { return std::string(); }
  7997. return addrs[0];
  7998. }
  7999. inline void hosted_at(const std::string &hostname,
  8000. std::vector<std::string> &addrs) {
  8001. struct addrinfo hints;
  8002. struct addrinfo *result;
  8003. memset(&hints, 0, sizeof(struct addrinfo));
  8004. hints.ai_family = AF_UNSPEC;
  8005. hints.ai_socktype = SOCK_STREAM;
  8006. hints.ai_protocol = 0;
  8007. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8008. &result, 0)) {
  8009. #if defined __linux__ && !defined __ANDROID__
  8010. res_init();
  8011. #endif
  8012. return;
  8013. }
  8014. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8015. for (auto rp = result; rp; rp = rp->ai_next) {
  8016. const auto &addr =
  8017. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8018. std::string ip;
  8019. auto dummy = -1;
  8020. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8021. dummy)) {
  8022. addrs.emplace_back(std::move(ip));
  8023. }
  8024. }
  8025. }
  8026. inline std::string encode_uri_component(const std::string &value) {
  8027. std::ostringstream escaped;
  8028. escaped.fill('0');
  8029. escaped << std::hex;
  8030. for (auto c : value) {
  8031. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  8032. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  8033. c == ')') {
  8034. escaped << c;
  8035. } else {
  8036. escaped << std::uppercase;
  8037. escaped << '%' << std::setw(2)
  8038. << static_cast<int>(static_cast<unsigned char>(c));
  8039. escaped << std::nouppercase;
  8040. }
  8041. }
  8042. return escaped.str();
  8043. }
  8044. inline std::string encode_uri(const std::string &value) {
  8045. std::ostringstream escaped;
  8046. escaped.fill('0');
  8047. escaped << std::hex;
  8048. for (auto c : value) {
  8049. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  8050. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  8051. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  8052. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8053. escaped << c;
  8054. } else {
  8055. escaped << std::uppercase;
  8056. escaped << '%' << std::setw(2)
  8057. << static_cast<int>(static_cast<unsigned char>(c));
  8058. escaped << std::nouppercase;
  8059. }
  8060. }
  8061. return escaped.str();
  8062. }
  8063. inline std::string decode_uri_component(const std::string &value) {
  8064. std::string result;
  8065. for (size_t i = 0; i < value.size(); i++) {
  8066. if (value[i] == '%' && i + 2 < value.size()) {
  8067. auto val = 0;
  8068. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8069. result += static_cast<char>(val);
  8070. i += 2;
  8071. } else {
  8072. result += value[i];
  8073. }
  8074. } else {
  8075. result += value[i];
  8076. }
  8077. }
  8078. return result;
  8079. }
  8080. inline std::string decode_uri(const std::string &value) {
  8081. std::string result;
  8082. for (size_t i = 0; i < value.size(); i++) {
  8083. if (value[i] == '%' && i + 2 < value.size()) {
  8084. auto val = 0;
  8085. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8086. result += static_cast<char>(val);
  8087. i += 2;
  8088. } else {
  8089. result += value[i];
  8090. }
  8091. } else {
  8092. result += value[i];
  8093. }
  8094. }
  8095. return result;
  8096. }
  8097. inline std::string encode_path_component(const std::string &component) {
  8098. std::string result;
  8099. result.reserve(component.size() * 3);
  8100. for (size_t i = 0; i < component.size(); i++) {
  8101. auto c = static_cast<unsigned char>(component[i]);
  8102. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8103. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  8104. result += static_cast<char>(c);
  8105. }
  8106. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8107. // "," / ";" / "="
  8108. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8109. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8110. c == '=') {
  8111. result += static_cast<char>(c);
  8112. }
  8113. // Colon is allowed in path segments except first segment
  8114. else if (c == ':') {
  8115. result += static_cast<char>(c);
  8116. }
  8117. // @ is allowed in path
  8118. else if (c == '@') {
  8119. result += static_cast<char>(c);
  8120. } else {
  8121. result += '%';
  8122. char hex[3];
  8123. snprintf(hex, sizeof(hex), "%02X", c);
  8124. result.append(hex, 2);
  8125. }
  8126. }
  8127. return result;
  8128. }
  8129. inline std::string decode_path_component(const std::string &component) {
  8130. std::string result;
  8131. result.reserve(component.size());
  8132. for (size_t i = 0; i < component.size(); i++) {
  8133. if (component[i] == '%' && i + 1 < component.size()) {
  8134. if (component[i + 1] == 'u') {
  8135. // Unicode %uXXXX encoding
  8136. auto val = 0;
  8137. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8138. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8139. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8140. char buff[4];
  8141. size_t len = detail::to_utf8(val, buff);
  8142. if (len > 0) { result.append(buff, len); }
  8143. i += 5; // 'u0000'
  8144. } else {
  8145. result += component[i];
  8146. }
  8147. } else {
  8148. // Standard %XX encoding
  8149. auto val = 0;
  8150. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8151. // 2 digits hex codes
  8152. result += static_cast<char>(val);
  8153. i += 2; // 'XX'
  8154. } else {
  8155. result += component[i];
  8156. }
  8157. }
  8158. } else {
  8159. result += component[i];
  8160. }
  8161. }
  8162. return result;
  8163. }
  8164. inline std::string encode_query_component(const std::string &component,
  8165. bool space_as_plus) {
  8166. std::string result;
  8167. result.reserve(component.size() * 3);
  8168. for (size_t i = 0; i < component.size(); i++) {
  8169. auto c = static_cast<unsigned char>(component[i]);
  8170. // Unreserved characters per RFC 3986
  8171. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  8172. result += static_cast<char>(c);
  8173. }
  8174. // Space handling
  8175. else if (c == ' ') {
  8176. if (space_as_plus) {
  8177. result += '+';
  8178. } else {
  8179. result += "%20";
  8180. }
  8181. }
  8182. // Plus sign handling
  8183. else if (c == '+') {
  8184. if (space_as_plus) {
  8185. result += "%2B";
  8186. } else {
  8187. result += static_cast<char>(c);
  8188. }
  8189. }
  8190. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8191. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8192. c == '*' || c == ',' || c == ';') {
  8193. result += static_cast<char>(c);
  8194. }
  8195. // Colon and @ are allowed in query
  8196. else if (c == ':' || c == '@') {
  8197. result += static_cast<char>(c);
  8198. }
  8199. // Forward slash is allowed in query values
  8200. else if (c == '/') {
  8201. result += static_cast<char>(c);
  8202. }
  8203. // Question mark is allowed in query values (after first ?)
  8204. else if (c == '?') {
  8205. result += static_cast<char>(c);
  8206. } else {
  8207. result += '%';
  8208. char hex[3];
  8209. snprintf(hex, sizeof(hex), "%02X", c);
  8210. result.append(hex, 2);
  8211. }
  8212. }
  8213. return result;
  8214. }
  8215. inline std::string decode_query_component(const std::string &component,
  8216. bool plus_as_space) {
  8217. std::string result;
  8218. result.reserve(component.size());
  8219. for (size_t i = 0; i < component.size(); i++) {
  8220. if (component[i] == '%' && i + 2 < component.size()) {
  8221. auto val = 0;
  8222. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8223. result += static_cast<char>(val);
  8224. i += 2;
  8225. } else {
  8226. result += component[i];
  8227. }
  8228. } else if (component[i] == '+' && plus_as_space) {
  8229. result += ' '; // + becomes space in form-urlencoded
  8230. } else {
  8231. result += component[i];
  8232. }
  8233. }
  8234. return result;
  8235. }
  8236. inline std::string sanitize_filename(const std::string &filename) {
  8237. // Extract basename: find the last path separator (/ or \)
  8238. auto pos = filename.find_last_of("/\\");
  8239. auto result =
  8240. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8241. // Strip null bytes
  8242. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8243. // Trim whitespace
  8244. {
  8245. auto start = result.find_first_not_of(" \t");
  8246. auto end = result.find_last_not_of(" \t");
  8247. result = (start == std::string::npos)
  8248. ? ""
  8249. : result.substr(start, end - start + 1);
  8250. }
  8251. // Reject . and ..
  8252. if (result == "." || result == "..") { return ""; }
  8253. return result;
  8254. }
  8255. inline std::string append_query_params(const std::string &path,
  8256. const Params &params) {
  8257. std::string path_with_query = path;
  8258. thread_local const std::regex re("[^?]+\\?.*");
  8259. auto delm = std::regex_match(path, re) ? '&' : '?';
  8260. path_with_query += delm + detail::params_to_query_str(params);
  8261. return path_with_query;
  8262. }
  8263. // Header utilities
  8264. inline std::pair<std::string, std::string>
  8265. make_range_header(const Ranges &ranges) {
  8266. std::string field = "bytes=";
  8267. auto i = 0;
  8268. for (const auto &r : ranges) {
  8269. if (i != 0) { field += ", "; }
  8270. if (r.first != -1) { field += std::to_string(r.first); }
  8271. field += '-';
  8272. if (r.second != -1) { field += std::to_string(r.second); }
  8273. i++;
  8274. }
  8275. return std::make_pair("Range", std::move(field));
  8276. }
  8277. inline std::pair<std::string, std::string>
  8278. make_basic_authentication_header(const std::string &username,
  8279. const std::string &password, bool is_proxy) {
  8280. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8281. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8282. return std::make_pair(key, std::move(field));
  8283. }
  8284. inline std::pair<std::string, std::string>
  8285. make_bearer_token_authentication_header(const std::string &token,
  8286. bool is_proxy = false) {
  8287. auto field = "Bearer " + token;
  8288. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8289. return std::make_pair(key, std::move(field));
  8290. }
  8291. // Request implementation
  8292. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8293. size_t id) const {
  8294. return detail::get_header_value_u64(headers, key, def, id);
  8295. }
  8296. inline bool Request::has_header(const std::string &key) const {
  8297. return detail::has_header(headers, key);
  8298. }
  8299. inline std::string Request::get_header_value(const std::string &key,
  8300. const char *def, size_t id) const {
  8301. return detail::get_header_value(headers, key, def, id);
  8302. }
  8303. inline size_t Request::get_header_value_count(const std::string &key) const {
  8304. return detail::get_header_value_count(headers, key);
  8305. }
  8306. inline void Request::set_header(const std::string &key,
  8307. const std::string &val) {
  8308. detail::set_header(headers, key, val);
  8309. }
  8310. inline bool Request::has_trailer(const std::string &key) const {
  8311. return trailers.find(key) != trailers.end();
  8312. }
  8313. inline std::string Request::get_trailer_value(const std::string &key,
  8314. size_t id) const {
  8315. return detail::get_multimap_value(trailers, key, id);
  8316. }
  8317. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8318. auto r = trailers.equal_range(key);
  8319. return static_cast<size_t>(std::distance(r.first, r.second));
  8320. }
  8321. inline bool Request::has_param(const std::string &key) const {
  8322. return params.find(key) != params.end();
  8323. }
  8324. inline std::string Request::get_param_value(const std::string &key,
  8325. size_t id) const {
  8326. return detail::get_multimap_value(params, key, id);
  8327. }
  8328. inline std::vector<std::string>
  8329. Request::get_param_values(const std::string &key) const {
  8330. auto rng = params.equal_range(key);
  8331. std::vector<std::string> values;
  8332. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8333. for (auto it = rng.first; it != rng.second; ++it) {
  8334. values.push_back(it->second);
  8335. }
  8336. return values;
  8337. }
  8338. inline size_t Request::get_param_value_count(const std::string &key) const {
  8339. auto r = params.equal_range(key);
  8340. return static_cast<size_t>(std::distance(r.first, r.second));
  8341. }
  8342. inline bool Request::is_multipart_form_data() const {
  8343. const auto &content_type = get_header_value("Content-Type");
  8344. return detail::extract_media_type(content_type) == "multipart/form-data";
  8345. }
  8346. // Multipart FormData implementation
  8347. inline std::string MultipartFormData::get_field(const std::string &key,
  8348. size_t id) const {
  8349. auto rng = fields.equal_range(key);
  8350. auto it = rng.first;
  8351. std::advance(it, static_cast<ssize_t>(id));
  8352. if (it != rng.second) { return it->second.content; }
  8353. return std::string();
  8354. }
  8355. inline std::vector<std::string>
  8356. MultipartFormData::get_fields(const std::string &key) const {
  8357. std::vector<std::string> values;
  8358. auto rng = fields.equal_range(key);
  8359. for (auto it = rng.first; it != rng.second; it++) {
  8360. values.push_back(it->second.content);
  8361. }
  8362. return values;
  8363. }
  8364. inline bool MultipartFormData::has_field(const std::string &key) const {
  8365. return fields.find(key) != fields.end();
  8366. }
  8367. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8368. auto r = fields.equal_range(key);
  8369. return static_cast<size_t>(std::distance(r.first, r.second));
  8370. }
  8371. inline FormData MultipartFormData::get_file(const std::string &key,
  8372. size_t id) const {
  8373. return detail::get_multimap_value(files, key, id);
  8374. }
  8375. inline std::vector<FormData>
  8376. MultipartFormData::get_files(const std::string &key) const {
  8377. std::vector<FormData> values;
  8378. auto rng = files.equal_range(key);
  8379. for (auto it = rng.first; it != rng.second; it++) {
  8380. values.push_back(it->second);
  8381. }
  8382. return values;
  8383. }
  8384. inline bool MultipartFormData::has_file(const std::string &key) const {
  8385. return files.find(key) != files.end();
  8386. }
  8387. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8388. auto r = files.equal_range(key);
  8389. return static_cast<size_t>(std::distance(r.first, r.second));
  8390. }
  8391. // Multipart FormData writer implementation
  8392. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8393. return detail::is_multipart_boundary_chars_valid(boundary);
  8394. }
  8395. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8396. : boundary_(detail::make_multipart_data_boundary()) {}
  8397. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8398. : boundary_(std::move(boundary)) {}
  8399. inline const std::string &MultipartFormDataWriter::boundary() const {
  8400. return boundary_;
  8401. }
  8402. inline std::string MultipartFormDataWriter::content_type() const {
  8403. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8404. }
  8405. inline std::string
  8406. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8407. return detail::serialize_multipart_formdata(items, boundary_);
  8408. }
  8409. inline size_t MultipartFormDataWriter::content_length(
  8410. const UploadFormDataItems &items) const {
  8411. return detail::get_multipart_content_length(items, boundary_);
  8412. }
  8413. inline std::string
  8414. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8415. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8416. }
  8417. inline std::string MultipartFormDataWriter::item_end() {
  8418. return detail::serialize_multipart_formdata_item_end();
  8419. }
  8420. inline std::string MultipartFormDataWriter::finish() const {
  8421. return detail::serialize_multipart_formdata_finish(boundary_);
  8422. }
  8423. // Response implementation
  8424. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8425. size_t id) const {
  8426. return detail::get_header_value_u64(headers, key, def, id);
  8427. }
  8428. inline bool Response::has_header(const std::string &key) const {
  8429. return headers.find(key) != headers.end();
  8430. }
  8431. inline std::string Response::get_header_value(const std::string &key,
  8432. const char *def,
  8433. size_t id) const {
  8434. return detail::get_header_value(headers, key, def, id);
  8435. }
  8436. inline size_t Response::get_header_value_count(const std::string &key) const {
  8437. return detail::get_header_value_count(headers, key);
  8438. }
  8439. inline void Response::set_header(const std::string &key,
  8440. const std::string &val) {
  8441. detail::set_header(headers, key, val);
  8442. }
  8443. inline bool Response::has_trailer(const std::string &key) const {
  8444. return trailers.find(key) != trailers.end();
  8445. }
  8446. inline std::string Response::get_trailer_value(const std::string &key,
  8447. size_t id) const {
  8448. return detail::get_multimap_value(trailers, key, id);
  8449. }
  8450. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8451. auto r = trailers.equal_range(key);
  8452. return static_cast<size_t>(std::distance(r.first, r.second));
  8453. }
  8454. inline void Response::set_redirect(const std::string &url, int stat) {
  8455. if (detail::fields::is_field_value(url)) {
  8456. set_header("Location", url);
  8457. if (300 <= stat && stat < 400) {
  8458. this->status = stat;
  8459. } else {
  8460. this->status = StatusCode::Found_302;
  8461. }
  8462. }
  8463. }
  8464. inline void Response::set_content(const char *s, size_t n,
  8465. const std::string &content_type) {
  8466. body.assign(s, n);
  8467. auto rng = headers.equal_range("Content-Type");
  8468. headers.erase(rng.first, rng.second);
  8469. set_header("Content-Type", content_type);
  8470. }
  8471. inline void Response::set_content(const std::string &s,
  8472. const std::string &content_type) {
  8473. set_content(s.data(), s.size(), content_type);
  8474. }
  8475. inline void Response::set_content(std::string &&s,
  8476. const std::string &content_type) {
  8477. body = std::move(s);
  8478. auto rng = headers.equal_range("Content-Type");
  8479. headers.erase(rng.first, rng.second);
  8480. set_header("Content-Type", content_type);
  8481. }
  8482. inline void Response::set_content_provider(
  8483. size_t in_length, const std::string &content_type, ContentProvider provider,
  8484. ContentProviderResourceReleaser resource_releaser) {
  8485. set_header("Content-Type", content_type);
  8486. content_length_ = in_length;
  8487. if (in_length > 0) { content_provider_ = std::move(provider); }
  8488. content_provider_resource_releaser_ = std::move(resource_releaser);
  8489. is_chunked_content_provider_ = false;
  8490. }
  8491. inline void Response::set_content_provider(
  8492. const std::string &content_type, ContentProviderWithoutLength provider,
  8493. ContentProviderResourceReleaser resource_releaser) {
  8494. set_header("Content-Type", content_type);
  8495. content_length_ = 0;
  8496. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8497. content_provider_resource_releaser_ = std::move(resource_releaser);
  8498. is_chunked_content_provider_ = false;
  8499. }
  8500. inline void Response::set_chunked_content_provider(
  8501. const std::string &content_type, ContentProviderWithoutLength provider,
  8502. ContentProviderResourceReleaser resource_releaser) {
  8503. set_header("Content-Type", content_type);
  8504. content_length_ = 0;
  8505. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8506. content_provider_resource_releaser_ = std::move(resource_releaser);
  8507. is_chunked_content_provider_ = true;
  8508. }
  8509. inline void Response::set_file_content(const std::string &path,
  8510. const std::string &content_type) {
  8511. file_content_path_ = path;
  8512. file_content_content_type_ = content_type;
  8513. }
  8514. inline void Response::set_file_content(const std::string &path) {
  8515. file_content_path_ = path;
  8516. }
  8517. // Result implementation
  8518. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8519. size_t def,
  8520. size_t id) const {
  8521. return detail::get_header_value_u64(request_headers_, key, def, id);
  8522. }
  8523. inline bool Result::has_request_header(const std::string &key) const {
  8524. return request_headers_.find(key) != request_headers_.end();
  8525. }
  8526. inline std::string Result::get_request_header_value(const std::string &key,
  8527. const char *def,
  8528. size_t id) const {
  8529. return detail::get_header_value(request_headers_, key, def, id);
  8530. }
  8531. inline size_t
  8532. Result::get_request_header_value_count(const std::string &key) const {
  8533. auto r = request_headers_.equal_range(key);
  8534. return static_cast<size_t>(std::distance(r.first, r.second));
  8535. }
  8536. // Stream implementation
  8537. inline ssize_t Stream::write(const char *ptr) {
  8538. return write(ptr, strlen(ptr));
  8539. }
  8540. inline ssize_t Stream::write(const std::string &s) {
  8541. return write(s.data(), s.size());
  8542. }
  8543. // BodyReader implementation
  8544. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8545. if (!stream) {
  8546. last_error = Error::Connection;
  8547. return -1;
  8548. }
  8549. if (eof) { return 0; }
  8550. if (!chunked) {
  8551. // Content-Length based reading
  8552. if (has_content_length && bytes_read >= content_length) {
  8553. eof = true;
  8554. return 0;
  8555. }
  8556. auto to_read = len;
  8557. if (has_content_length) {
  8558. auto remaining = content_length - bytes_read;
  8559. to_read = (std::min)(len, remaining);
  8560. }
  8561. auto n = stream->read(buf, to_read);
  8562. if (n < 0) {
  8563. last_error = stream->get_error();
  8564. if (last_error == Error::Success) { last_error = Error::Read; }
  8565. eof = true;
  8566. return n;
  8567. }
  8568. if (n == 0) {
  8569. // Unexpected EOF before content_length
  8570. last_error = stream->get_error();
  8571. if (last_error == Error::Success) { last_error = Error::Read; }
  8572. eof = true;
  8573. return 0;
  8574. }
  8575. bytes_read += static_cast<size_t>(n);
  8576. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8577. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8578. last_error = Error::ExceedMaxPayloadSize;
  8579. eof = true;
  8580. return -1;
  8581. }
  8582. return n;
  8583. }
  8584. // Chunked transfer encoding: delegate to shared decoder instance.
  8585. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8586. size_t chunk_offset = 0;
  8587. size_t chunk_total = 0;
  8588. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8589. if (n < 0) {
  8590. last_error = stream->get_error();
  8591. if (last_error == Error::Success) { last_error = Error::Read; }
  8592. eof = true;
  8593. return n;
  8594. }
  8595. if (n == 0) {
  8596. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8597. eof = true;
  8598. return 0;
  8599. }
  8600. bytes_read += static_cast<size_t>(n);
  8601. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8602. last_error = Error::ExceedMaxPayloadSize;
  8603. eof = true;
  8604. return -1;
  8605. }
  8606. return n;
  8607. }
  8608. // ThreadPool implementation
  8609. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr)
  8610. : base_thread_count_(n), max_queued_requests_(mqr), idle_thread_count_(0),
  8611. shutdown_(false) {
  8612. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8613. if (max_n != 0 && max_n < n) {
  8614. std::string msg = "max_threads must be >= base_threads";
  8615. throw std::invalid_argument(msg);
  8616. }
  8617. #endif
  8618. max_thread_count_ = max_n == 0 ? n : max_n;
  8619. threads_.reserve(base_thread_count_);
  8620. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8621. try {
  8622. #endif
  8623. for (size_t i = 0; i < base_thread_count_; i++) {
  8624. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8625. }
  8626. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8627. } catch (...) {
  8628. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8629. // signal the workers we already spawned to exit and join them so the
  8630. // vector destructor does not see joinable threads (which would call
  8631. // std::terminate). Then rethrow so the caller learns of the failure.
  8632. {
  8633. std::unique_lock<std::mutex> lock(mutex_);
  8634. shutdown_ = true;
  8635. }
  8636. cond_.notify_all();
  8637. for (auto &t : threads_) {
  8638. if (t.joinable()) { t.join(); }
  8639. }
  8640. throw;
  8641. }
  8642. #endif
  8643. }
  8644. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8645. {
  8646. std::unique_lock<std::mutex> lock(mutex_);
  8647. if (shutdown_) { return false; }
  8648. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8649. return false;
  8650. }
  8651. jobs_.push_back(std::move(fn));
  8652. // Spawn a dynamic thread if no idle threads and under max
  8653. if (idle_thread_count_ == 0 &&
  8654. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8655. cleanup_finished_threads();
  8656. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8657. }
  8658. }
  8659. cond_.notify_one();
  8660. return true;
  8661. }
  8662. inline void ThreadPool::shutdown() {
  8663. {
  8664. std::unique_lock<std::mutex> lock(mutex_);
  8665. shutdown_ = true;
  8666. }
  8667. cond_.notify_all();
  8668. for (auto &t : threads_) {
  8669. if (t.joinable()) { t.join(); }
  8670. }
  8671. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8672. // with worker threads that call move_to_finished() concurrently.
  8673. std::list<std::thread> remaining_dynamic;
  8674. {
  8675. std::unique_lock<std::mutex> lock(mutex_);
  8676. remaining_dynamic = std::move(dynamic_threads_);
  8677. }
  8678. for (auto &t : remaining_dynamic) {
  8679. if (t.joinable()) { t.join(); }
  8680. }
  8681. std::unique_lock<std::mutex> lock(mutex_);
  8682. cleanup_finished_threads();
  8683. }
  8684. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8685. // Must be called with mutex_ held
  8686. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8687. if (it->get_id() == id) {
  8688. finished_threads_.push_back(std::move(*it));
  8689. dynamic_threads_.erase(it);
  8690. return;
  8691. }
  8692. }
  8693. }
  8694. inline void ThreadPool::cleanup_finished_threads() {
  8695. // Must be called with mutex_ held
  8696. for (auto &t : finished_threads_) {
  8697. if (t.joinable()) { t.join(); }
  8698. }
  8699. finished_threads_.clear();
  8700. }
  8701. inline void ThreadPool::worker(bool is_dynamic) {
  8702. for (;;) {
  8703. std::function<void()> fn;
  8704. {
  8705. std::unique_lock<std::mutex> lock(mutex_);
  8706. idle_thread_count_++;
  8707. if (is_dynamic) {
  8708. auto has_work = cond_.wait_for(
  8709. lock, std::chrono::seconds(CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT),
  8710. [&] { return !jobs_.empty() || shutdown_; });
  8711. if (!has_work) {
  8712. // Timed out with no work - exit this dynamic thread
  8713. idle_thread_count_--;
  8714. move_to_finished(std::this_thread::get_id());
  8715. break;
  8716. }
  8717. } else {
  8718. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8719. }
  8720. idle_thread_count_--;
  8721. if (shutdown_ && jobs_.empty()) { break; }
  8722. fn = std::move(jobs_.front());
  8723. jobs_.pop_front();
  8724. }
  8725. assert(true == static_cast<bool>(fn));
  8726. fn();
  8727. }
  8728. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8729. !defined(LIBRESSL_VERSION_NUMBER)
  8730. OPENSSL_thread_stop();
  8731. #endif
  8732. }
  8733. /*
  8734. * Group 1 (continued): detail namespace - Stream implementations
  8735. */
  8736. namespace detail {
  8737. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8738. time_t timeout_sec, time_t timeout_usec,
  8739. time_t &actual_timeout_sec,
  8740. time_t &actual_timeout_usec) {
  8741. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8742. auto actual_timeout_msec =
  8743. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8744. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8745. actual_timeout_sec = actual_timeout_msec / 1000;
  8746. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8747. }
  8748. // Socket stream implementation
  8749. inline SocketStream::SocketStream(
  8750. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8751. time_t write_timeout_sec, time_t write_timeout_usec,
  8752. time_t max_timeout_msec,
  8753. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8754. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8755. read_timeout_usec_(read_timeout_usec),
  8756. write_timeout_sec_(write_timeout_sec),
  8757. write_timeout_usec_(write_timeout_usec),
  8758. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8759. read_buff_(read_buff_size_, 0) {}
  8760. inline SocketStream::~SocketStream() = default;
  8761. inline bool SocketStream::is_readable() const {
  8762. return read_buff_off_ < read_buff_content_size_;
  8763. }
  8764. inline bool SocketStream::wait_readable() const {
  8765. if (max_timeout_msec_ <= 0) {
  8766. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8767. }
  8768. time_t read_timeout_sec;
  8769. time_t read_timeout_usec;
  8770. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8771. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8772. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8773. }
  8774. inline bool SocketStream::wait_writable() const {
  8775. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8776. }
  8777. inline bool SocketStream::is_peer_alive() const {
  8778. return detail::is_socket_alive(sock_);
  8779. }
  8780. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8781. #ifdef _WIN32
  8782. size =
  8783. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8784. #else
  8785. size = (std::min)(size,
  8786. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8787. #endif
  8788. if (read_buff_off_ < read_buff_content_size_) {
  8789. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8790. if (size <= remaining_size) {
  8791. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8792. read_buff_off_ += size;
  8793. return static_cast<ssize_t>(size);
  8794. } else {
  8795. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8796. read_buff_off_ += remaining_size;
  8797. return static_cast<ssize_t>(remaining_size);
  8798. }
  8799. }
  8800. if (!wait_readable()) {
  8801. error_ = Error::Timeout;
  8802. return -1;
  8803. }
  8804. read_buff_off_ = 0;
  8805. read_buff_content_size_ = 0;
  8806. if (size < read_buff_size_) {
  8807. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8808. CPPHTTPLIB_RECV_FLAGS);
  8809. if (n <= 0) {
  8810. if (n == 0) {
  8811. error_ = Error::ConnectionClosed;
  8812. } else {
  8813. error_ = Error::Read;
  8814. }
  8815. return n;
  8816. } else if (n <= static_cast<ssize_t>(size)) {
  8817. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8818. return n;
  8819. } else {
  8820. memcpy(ptr, read_buff_.data(), size);
  8821. read_buff_off_ = size;
  8822. read_buff_content_size_ = static_cast<size_t>(n);
  8823. return static_cast<ssize_t>(size);
  8824. }
  8825. } else {
  8826. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8827. if (n <= 0) {
  8828. if (n == 0) {
  8829. error_ = Error::ConnectionClosed;
  8830. } else {
  8831. error_ = Error::Read;
  8832. }
  8833. }
  8834. return n;
  8835. }
  8836. }
  8837. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8838. if (!wait_writable()) { return -1; }
  8839. #if defined(_WIN32) && !defined(_WIN64)
  8840. size =
  8841. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8842. #endif
  8843. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8844. }
  8845. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8846. int &port) const {
  8847. return detail::get_remote_ip_and_port(sock_, ip, port);
  8848. }
  8849. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8850. int &port) const {
  8851. return detail::get_local_ip_and_port(sock_, ip, port);
  8852. }
  8853. inline socket_t SocketStream::socket() const { return sock_; }
  8854. inline time_t SocketStream::duration() const {
  8855. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8856. std::chrono::steady_clock::now() - start_time_)
  8857. .count();
  8858. }
  8859. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8860. read_timeout_sec_ = sec;
  8861. read_timeout_usec_ = usec;
  8862. }
  8863. // Buffer stream implementation
  8864. inline bool BufferStream::is_readable() const { return true; }
  8865. inline bool BufferStream::wait_readable() const { return true; }
  8866. inline bool BufferStream::wait_writable() const { return true; }
  8867. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8868. #if defined(_MSC_VER) && _MSC_VER < 1910
  8869. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8870. #else
  8871. auto len_read = buffer.copy(ptr, size, position);
  8872. #endif
  8873. position += static_cast<size_t>(len_read);
  8874. return static_cast<ssize_t>(len_read);
  8875. }
  8876. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8877. buffer.append(ptr, size);
  8878. return static_cast<ssize_t>(size);
  8879. }
  8880. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8881. int & /*port*/) const {}
  8882. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8883. int & /*port*/) const {}
  8884. inline socket_t BufferStream::socket() const { return 0; }
  8885. inline time_t BufferStream::duration() const { return 0; }
  8886. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8887. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8888. : MatcherBase(pattern) {
  8889. constexpr const char marker[] = "/:";
  8890. // One past the last ending position of a path param substring
  8891. std::size_t last_param_end = 0;
  8892. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8893. // Needed to ensure that parameter names are unique during matcher
  8894. // construction
  8895. // If exceptions are disabled, only last duplicate path
  8896. // parameter will be set
  8897. std::unordered_set<std::string> param_name_set;
  8898. #endif
  8899. while (true) {
  8900. const auto marker_pos = pattern.find(
  8901. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8902. if (marker_pos == std::string::npos) { break; }
  8903. static_fragments_.push_back(
  8904. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8905. const auto param_name_start = marker_pos + str_len(marker);
  8906. auto sep_pos = pattern.find(separator, param_name_start);
  8907. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8908. auto param_name =
  8909. pattern.substr(param_name_start, sep_pos - param_name_start);
  8910. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8911. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8912. std::string msg = "Encountered path parameter '" + param_name +
  8913. "' multiple times in route pattern '" + pattern + "'.";
  8914. throw std::invalid_argument(msg);
  8915. }
  8916. #endif
  8917. param_names_.push_back(std::move(param_name));
  8918. last_param_end = sep_pos + 1;
  8919. }
  8920. if (last_param_end < pattern.length()) {
  8921. static_fragments_.push_back(pattern.substr(last_param_end));
  8922. }
  8923. }
  8924. inline bool PathParamsMatcher::match(Request &request) const {
  8925. request.matches = std::smatch();
  8926. request.path_params.clear();
  8927. request.path_params.reserve(param_names_.size());
  8928. // One past the position at which the path matched the pattern last time
  8929. std::size_t starting_pos = 0;
  8930. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8931. const auto &fragment = static_fragments_[i];
  8932. if (starting_pos + fragment.length() > request.path.length()) {
  8933. return false;
  8934. }
  8935. // Avoid unnecessary allocation by using strncmp instead of substr +
  8936. // comparison
  8937. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8938. fragment.length()) != 0) {
  8939. return false;
  8940. }
  8941. starting_pos += fragment.length();
  8942. // Should only happen when we have a static fragment after a param
  8943. // Example: '/users/:id/subscriptions'
  8944. // The 'subscriptions' fragment here does not have a corresponding param
  8945. if (i >= param_names_.size()) { continue; }
  8946. auto sep_pos = request.path.find(separator, starting_pos);
  8947. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8948. const auto &param_name = param_names_[i];
  8949. request.path_params.emplace(
  8950. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8951. // Mark everything up to '/' as matched
  8952. starting_pos = sep_pos + 1;
  8953. }
  8954. // Returns false if the path is longer than the pattern
  8955. return starting_pos >= request.path.length();
  8956. }
  8957. inline bool RegexMatcher::match(Request &request) const {
  8958. request.path_params.clear();
  8959. return std::regex_match(request.path, request.matches, regex_);
  8960. }
  8961. // Enclose IPv6 address in brackets if needed
  8962. inline std::string prepare_host_string(const std::string &host) {
  8963. // Enclose IPv6 address in brackets (but not if already enclosed)
  8964. if (host.find(':') == std::string::npos ||
  8965. (!host.empty() && host[0] == '[')) {
  8966. // IPv4, hostname, or already bracketed IPv6
  8967. return host;
  8968. } else {
  8969. // IPv6 address without brackets
  8970. return "[" + host + "]";
  8971. }
  8972. }
  8973. inline std::string make_host_and_port_string(const std::string &host, int port,
  8974. bool is_ssl) {
  8975. auto result = prepare_host_string(host);
  8976. // Append port if not default
  8977. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  8978. ; // do nothing
  8979. } else {
  8980. result += ":" + std::to_string(port);
  8981. }
  8982. return result;
  8983. }
  8984. // Create "host:port" string always including port number (for CONNECT method)
  8985. inline std::string
  8986. make_host_and_port_string_always_port(const std::string &host, int port) {
  8987. return prepare_host_string(host) + ":" + std::to_string(port);
  8988. }
  8989. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  8990. NormalizedTarget normalize_target(const std::string &host);
  8991. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  8992. bool host_matches_no_proxy(const NormalizedTarget &target,
  8993. const std::vector<NoProxyEntry> &entries);
  8994. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  8995. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  8996. if (prefix_bits == 0) { return true; }
  8997. int full_bytes = prefix_bits / 8;
  8998. int rem_bits = prefix_bits % 8;
  8999. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9000. static_cast<size_t>(full_bytes)) != 0) {
  9001. return false;
  9002. }
  9003. if (rem_bits == 0) { return true; }
  9004. auto i = static_cast<size_t>(full_bytes);
  9005. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9006. return (ip[i] & mask) == (net[i] & mask);
  9007. }
  9008. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9009. if (token.empty()) { return false; }
  9010. if (token == "*") {
  9011. out.kind = NoProxyKind::Wildcard;
  9012. return true;
  9013. }
  9014. auto slash = token.find('/');
  9015. std::string addr_part =
  9016. (slash == std::string::npos) ? token : token.substr(0, slash);
  9017. std::string prefix_part =
  9018. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9019. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9020. // don't silently treat it as a /32 (or /128).
  9021. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9022. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9023. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9024. // when brackets are present.
  9025. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9026. addr_part.back() == ']';
  9027. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9028. if (!bracketed) {
  9029. struct in_addr v4;
  9030. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9031. int prefix = 32;
  9032. if (!prefix_part.empty()) {
  9033. auto r = from_chars(prefix_part.data(),
  9034. prefix_part.data() + prefix_part.size(), prefix);
  9035. if (r.ec != std::errc{} ||
  9036. r.ptr != prefix_part.data() + prefix_part.size()) {
  9037. return false;
  9038. }
  9039. if (prefix < 0 || prefix > 32) { return false; }
  9040. }
  9041. out.kind = NoProxyKind::IPv4Cidr;
  9042. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9043. out.prefix_bits = prefix;
  9044. return true;
  9045. }
  9046. }
  9047. struct in6_addr v6;
  9048. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9049. int prefix = 128;
  9050. if (!prefix_part.empty()) {
  9051. auto r = from_chars(prefix_part.data(),
  9052. prefix_part.data() + prefix_part.size(), prefix);
  9053. if (r.ec != std::errc{} ||
  9054. r.ptr != prefix_part.data() + prefix_part.size()) {
  9055. return false;
  9056. }
  9057. if (prefix < 0 || prefix > 128) { return false; }
  9058. }
  9059. out.kind = NoProxyKind::IPv6Cidr;
  9060. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9061. out.prefix_bits = prefix;
  9062. return true;
  9063. }
  9064. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9065. // the entry is malformed — don't fall through to the hostname branch.
  9066. if (bracketed) { return false; }
  9067. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9068. if (slash != std::string::npos) { return false; }
  9069. // Port-specific entries (host:port) are not supported.
  9070. if (token.find(':') != std::string::npos) { return false; }
  9071. std::string hostname = case_ignore::to_lower(token);
  9072. while (!hostname.empty() && hostname.front() == '.') {
  9073. hostname.erase(hostname.begin());
  9074. }
  9075. while (!hostname.empty() && hostname.back() == '.') {
  9076. hostname.pop_back();
  9077. }
  9078. if (hostname.empty()) { return false; }
  9079. out.kind = NoProxyKind::HostnameSuffix;
  9080. out.hostname_pattern = std::move(hostname);
  9081. return true;
  9082. }
  9083. inline NormalizedTarget normalize_target(const std::string &host) {
  9084. NormalizedTarget t;
  9085. std::string h = host;
  9086. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9087. h = h.substr(1, h.size() - 2);
  9088. }
  9089. // Strip a single trailing dot so "example.com." canonicalizes to
  9090. // "example.com".
  9091. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9092. t.hostname = case_ignore::to_lower(h);
  9093. if (!t.hostname.empty()) {
  9094. struct in_addr v4;
  9095. struct in6_addr v6;
  9096. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9097. t.is_ipv4 = true;
  9098. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9099. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9100. t.is_ipv6 = true;
  9101. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9102. }
  9103. }
  9104. return t;
  9105. }
  9106. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9107. const std::vector<NoProxyEntry> &entries) {
  9108. if (target.hostname.empty()) { return false; }
  9109. for (const auto &e : entries) {
  9110. switch (e.kind) {
  9111. case NoProxyKind::Wildcard: return true;
  9112. case NoProxyKind::IPv4Cidr:
  9113. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9114. return true;
  9115. }
  9116. break;
  9117. case NoProxyKind::IPv6Cidr:
  9118. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9119. return true;
  9120. }
  9121. break;
  9122. case NoProxyKind::HostnameSuffix:
  9123. if (target.is_ipv4 || target.is_ipv6) { break; }
  9124. if (target.hostname == e.hostname_pattern) { return true; }
  9125. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9126. // an entry of "example.com".
  9127. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9128. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9129. if (target.hostname[offset - 1] == '.' &&
  9130. target.hostname.compare(offset, e.hostname_pattern.size(),
  9131. e.hostname_pattern) == 0) {
  9132. return true;
  9133. }
  9134. }
  9135. break;
  9136. }
  9137. }
  9138. return false;
  9139. }
  9140. template <typename T>
  9141. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9142. T header_writer, Error &error) {
  9143. for (const auto &h : headers) {
  9144. if (!detail::fields::is_field_name(h.first) ||
  9145. !detail::fields::is_field_value(h.second)) {
  9146. error = Error::InvalidHeaders;
  9147. return false;
  9148. }
  9149. }
  9150. if (header_writer(strm, headers) <= 0) {
  9151. error = Error::Write;
  9152. return false;
  9153. }
  9154. return true;
  9155. }
  9156. } // namespace detail
  9157. /*
  9158. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9159. */
  9160. #ifdef CPPHTTPLIB_SSL_ENABLED
  9161. namespace detail {
  9162. // SSL socket stream implementation
  9163. inline SSLSocketStream::SSLSocketStream(
  9164. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9165. time_t read_timeout_usec, time_t write_timeout_sec,
  9166. time_t write_timeout_usec, time_t max_timeout_msec,
  9167. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9168. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9169. read_timeout_usec_(read_timeout_usec),
  9170. write_timeout_sec_(write_timeout_sec),
  9171. write_timeout_usec_(write_timeout_usec),
  9172. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9173. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9174. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9175. // Note: create_session() also clears this, but SSLClient currently
  9176. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9177. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9178. // SSL session was created.
  9179. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9180. #endif
  9181. }
  9182. inline SSLSocketStream::~SSLSocketStream() = default;
  9183. inline bool SSLSocketStream::is_readable() const {
  9184. return tls::pending(session_) > 0;
  9185. }
  9186. inline bool SSLSocketStream::wait_readable() const {
  9187. if (max_timeout_msec_ <= 0) {
  9188. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9189. }
  9190. time_t read_timeout_sec;
  9191. time_t read_timeout_usec;
  9192. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9193. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9194. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9195. }
  9196. inline bool SSLSocketStream::wait_writable() const {
  9197. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9198. !tls::is_peer_closed(session_, sock_);
  9199. }
  9200. inline bool SSLSocketStream::is_peer_alive() const {
  9201. return !tls::is_peer_closed(session_, sock_);
  9202. }
  9203. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9204. if (tls::pending(session_) > 0) {
  9205. tls::TlsError err;
  9206. auto ret = tls::read(session_, ptr, size, err);
  9207. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9208. error_ = Error::ConnectionClosed;
  9209. }
  9210. return ret;
  9211. } else if (wait_readable()) {
  9212. tls::TlsError err;
  9213. auto ret = tls::read(session_, ptr, size, err);
  9214. if (ret < 0) {
  9215. auto n = 1000;
  9216. #ifdef _WIN32
  9217. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9218. (err.code == tls::ErrorCode::SyscallError &&
  9219. WSAGetLastError() == WSAETIMEDOUT))) {
  9220. #else
  9221. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9222. #endif
  9223. if (tls::pending(session_) > 0) {
  9224. return tls::read(session_, ptr, size, err);
  9225. } else if (wait_readable()) {
  9226. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9227. ret = tls::read(session_, ptr, size, err);
  9228. if (ret >= 0) { return ret; }
  9229. } else {
  9230. break;
  9231. }
  9232. }
  9233. assert(ret < 0);
  9234. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9235. error_ = Error::ConnectionClosed;
  9236. }
  9237. return ret;
  9238. } else {
  9239. error_ = Error::Timeout;
  9240. return -1;
  9241. }
  9242. }
  9243. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9244. if (wait_writable()) {
  9245. auto handle_size =
  9246. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9247. tls::TlsError err;
  9248. auto ret = tls::write(session_, ptr, handle_size, err);
  9249. if (ret < 0) {
  9250. auto n = 1000;
  9251. #ifdef _WIN32
  9252. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9253. (err.code == tls::ErrorCode::SyscallError &&
  9254. WSAGetLastError() == WSAETIMEDOUT))) {
  9255. #else
  9256. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9257. #endif
  9258. if (wait_writable()) {
  9259. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9260. ret = tls::write(session_, ptr, handle_size, err);
  9261. if (ret >= 0) { return ret; }
  9262. } else {
  9263. break;
  9264. }
  9265. }
  9266. assert(ret < 0);
  9267. }
  9268. return ret;
  9269. }
  9270. return -1;
  9271. }
  9272. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9273. int &port) const {
  9274. detail::get_remote_ip_and_port(sock_, ip, port);
  9275. }
  9276. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9277. int &port) const {
  9278. detail::get_local_ip_and_port(sock_, ip, port);
  9279. }
  9280. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9281. inline time_t SSLSocketStream::duration() const {
  9282. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9283. std::chrono::steady_clock::now() - start_time_)
  9284. .count();
  9285. }
  9286. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9287. read_timeout_sec_ = sec;
  9288. read_timeout_usec_ = usec;
  9289. }
  9290. } // namespace detail
  9291. #endif // CPPHTTPLIB_SSL_ENABLED
  9292. /*
  9293. * Group 4: Server implementation
  9294. */
  9295. // HTTP server implementation
  9296. inline Server::Server()
  9297. : new_task_queue([] {
  9298. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9299. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9300. }) {
  9301. #ifndef _WIN32
  9302. signal(SIGPIPE, SIG_IGN);
  9303. #endif
  9304. }
  9305. inline Server::~Server() = default;
  9306. inline std::unique_ptr<detail::MatcherBase>
  9307. Server::make_matcher(const std::string &pattern) {
  9308. if (pattern.find("/:") != std::string::npos) {
  9309. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9310. } else {
  9311. return detail::make_unique<detail::RegexMatcher>(pattern);
  9312. }
  9313. }
  9314. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9315. return add_handler(get_handlers_, pattern, std::move(handler));
  9316. }
  9317. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9318. return add_handler(post_handlers_, pattern, std::move(handler));
  9319. }
  9320. inline Server &Server::Post(const std::string &pattern,
  9321. HandlerWithContentReader handler) {
  9322. return add_handler(post_handlers_for_content_reader_, pattern,
  9323. std::move(handler));
  9324. }
  9325. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9326. return add_handler(put_handlers_, pattern, std::move(handler));
  9327. }
  9328. inline Server &Server::Put(const std::string &pattern,
  9329. HandlerWithContentReader handler) {
  9330. return add_handler(put_handlers_for_content_reader_, pattern,
  9331. std::move(handler));
  9332. }
  9333. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9334. return add_handler(patch_handlers_, pattern, std::move(handler));
  9335. }
  9336. inline Server &Server::Patch(const std::string &pattern,
  9337. HandlerWithContentReader handler) {
  9338. return add_handler(patch_handlers_for_content_reader_, pattern,
  9339. std::move(handler));
  9340. }
  9341. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9342. return add_handler(delete_handlers_, pattern, std::move(handler));
  9343. }
  9344. inline Server &Server::Delete(const std::string &pattern,
  9345. HandlerWithContentReader handler) {
  9346. return add_handler(delete_handlers_for_content_reader_, pattern,
  9347. std::move(handler));
  9348. }
  9349. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9350. return add_handler(options_handlers_, pattern, std::move(handler));
  9351. }
  9352. inline Server &Server::WebSocket(const std::string &pattern,
  9353. WebSocketHandler handler) {
  9354. websocket_handlers_.push_back(
  9355. {make_matcher(pattern), std::move(handler), nullptr});
  9356. return *this;
  9357. }
  9358. inline Server &Server::WebSocket(const std::string &pattern,
  9359. WebSocketHandler handler,
  9360. SubProtocolSelector sub_protocol_selector) {
  9361. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9362. std::move(sub_protocol_selector)});
  9363. return *this;
  9364. }
  9365. inline bool Server::set_base_dir(const std::string &dir,
  9366. const std::string &mount_point) {
  9367. return set_mount_point(mount_point, dir);
  9368. }
  9369. inline bool Server::set_mount_point(const std::string &mount_point,
  9370. const std::string &dir, Headers headers) {
  9371. detail::FileStat stat(dir);
  9372. if (stat.is_dir()) {
  9373. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9374. if (!mnt.empty() && mnt[0] == '/') {
  9375. std::string resolved_base;
  9376. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9377. #if defined(_WIN32)
  9378. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9379. resolved_base += '\\';
  9380. }
  9381. #else
  9382. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9383. #endif
  9384. }
  9385. base_dirs_.push_back(
  9386. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9387. return true;
  9388. }
  9389. }
  9390. return false;
  9391. }
  9392. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9393. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9394. if (it->mount_point == mount_point) {
  9395. base_dirs_.erase(it);
  9396. return true;
  9397. }
  9398. }
  9399. return false;
  9400. }
  9401. inline Server &
  9402. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9403. const std::string &mime) {
  9404. file_extension_and_mimetype_map_[ext] = mime;
  9405. return *this;
  9406. }
  9407. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9408. default_file_mimetype_ = mime;
  9409. return *this;
  9410. }
  9411. inline Server &Server::set_file_request_handler(Handler handler) {
  9412. file_request_handler_ = std::move(handler);
  9413. return *this;
  9414. }
  9415. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9416. std::true_type) {
  9417. error_handler_ = std::move(handler);
  9418. return *this;
  9419. }
  9420. inline Server &Server::set_error_handler_core(Handler handler,
  9421. std::false_type) {
  9422. error_handler_ = [handler](const Request &req, Response &res) {
  9423. handler(req, res);
  9424. return HandlerResponse::Handled;
  9425. };
  9426. return *this;
  9427. }
  9428. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9429. exception_handler_ = std::move(handler);
  9430. return *this;
  9431. }
  9432. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9433. pre_routing_handler_ = std::move(handler);
  9434. return *this;
  9435. }
  9436. inline Server &Server::set_post_routing_handler(Handler handler) {
  9437. post_routing_handler_ = std::move(handler);
  9438. return *this;
  9439. }
  9440. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9441. pre_request_handler_ = std::move(handler);
  9442. return *this;
  9443. }
  9444. inline Server &Server::set_logger(Logger logger) {
  9445. logger_ = std::move(logger);
  9446. return *this;
  9447. }
  9448. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9449. error_logger_ = std::move(error_logger);
  9450. return *this;
  9451. }
  9452. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9453. pre_compression_logger_ = std::move(logger);
  9454. return *this;
  9455. }
  9456. inline Server &
  9457. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9458. expect_100_continue_handler_ = std::move(handler);
  9459. return *this;
  9460. }
  9461. inline Server &Server::set_start_handler(StartHandler handler) {
  9462. start_handler_ = std::move(handler);
  9463. return *this;
  9464. }
  9465. inline Server &Server::set_address_family(int family) {
  9466. address_family_ = family;
  9467. return *this;
  9468. }
  9469. inline Server &Server::set_tcp_nodelay(bool on) {
  9470. tcp_nodelay_ = on;
  9471. return *this;
  9472. }
  9473. inline Server &Server::set_ipv6_v6only(bool on) {
  9474. ipv6_v6only_ = on;
  9475. return *this;
  9476. }
  9477. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9478. socket_options_ = std::move(socket_options);
  9479. return *this;
  9480. }
  9481. inline Server &Server::set_default_headers(Headers headers) {
  9482. default_headers_ = std::move(headers);
  9483. return *this;
  9484. }
  9485. inline Server &Server::set_header_writer(
  9486. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9487. header_writer_ = writer;
  9488. return *this;
  9489. }
  9490. inline Server &
  9491. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9492. trusted_proxies_ = proxies;
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9496. keep_alive_max_count_ = count;
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9500. keep_alive_timeout_sec_ = sec;
  9501. return *this;
  9502. }
  9503. template <class Rep, class Period>
  9504. inline Server &Server::set_keep_alive_timeout(
  9505. const std::chrono::duration<Rep, Period> &duration) {
  9506. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9507. set_keep_alive_timeout(sec);
  9508. });
  9509. return *this;
  9510. }
  9511. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9512. read_timeout_sec_ = sec;
  9513. read_timeout_usec_ = usec;
  9514. return *this;
  9515. }
  9516. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9517. write_timeout_sec_ = sec;
  9518. write_timeout_usec_ = usec;
  9519. return *this;
  9520. }
  9521. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9522. idle_interval_sec_ = sec;
  9523. idle_interval_usec_ = usec;
  9524. return *this;
  9525. }
  9526. inline Server &Server::set_payload_max_length(size_t length) {
  9527. payload_max_length_ = length;
  9528. return *this;
  9529. }
  9530. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9531. websocket_max_missed_pongs_ = count;
  9532. return *this;
  9533. }
  9534. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9535. websocket_ping_interval_sec_ = sec;
  9536. return *this;
  9537. }
  9538. template <class Rep, class Period>
  9539. inline Server &Server::set_websocket_ping_interval(
  9540. const std::chrono::duration<Rep, Period> &duration) {
  9541. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9542. set_websocket_ping_interval(sec);
  9543. });
  9544. return *this;
  9545. }
  9546. inline bool Server::bind_to_port(const std::string &host, int port,
  9547. int socket_flags) {
  9548. auto ret = bind_internal(host, port, socket_flags);
  9549. if (ret == -1) { is_decommissioned = true; }
  9550. return ret >= 0;
  9551. }
  9552. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9553. auto ret = bind_internal(host, 0, socket_flags);
  9554. if (ret == -1) { is_decommissioned = true; }
  9555. return ret;
  9556. }
  9557. inline bool Server::listen_after_bind() { return listen_internal(); }
  9558. inline bool Server::listen(const std::string &host, int port,
  9559. int socket_flags) {
  9560. return bind_to_port(host, port, socket_flags) && listen_internal();
  9561. }
  9562. inline bool Server::is_running() const { return is_running_; }
  9563. inline void Server::wait_until_ready() const {
  9564. while (!is_running_ && !is_decommissioned) {
  9565. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9566. }
  9567. }
  9568. inline void Server::stop() noexcept {
  9569. if (is_running_) {
  9570. assert(svr_sock_ != INVALID_SOCKET);
  9571. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9572. detail::shutdown_socket(sock);
  9573. detail::close_socket(sock);
  9574. }
  9575. is_decommissioned = false;
  9576. }
  9577. inline void Server::decommission() { is_decommissioned = true; }
  9578. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9579. auto len = strlen(s);
  9580. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9581. len -= 2;
  9582. {
  9583. size_t count = 0;
  9584. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9585. switch (count) {
  9586. case 0: req.method = std::string(b, e); break;
  9587. case 1: req.target = std::string(b, e); break;
  9588. case 2: req.version = std::string(b, e); break;
  9589. default: break;
  9590. }
  9591. count++;
  9592. });
  9593. if (count != 3) { return false; }
  9594. }
  9595. thread_local const std::set<std::string> methods{
  9596. "GET", "HEAD", "POST", "PUT", "DELETE",
  9597. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9598. if (methods.find(req.method) == methods.end()) {
  9599. output_error_log(Error::InvalidHTTPMethod, &req);
  9600. return false;
  9601. }
  9602. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9603. output_error_log(Error::InvalidHTTPVersion, &req);
  9604. return false;
  9605. }
  9606. {
  9607. // Skip URL fragment
  9608. for (size_t i = 0; i < req.target.size(); i++) {
  9609. if (req.target[i] == '#') {
  9610. req.target.erase(i);
  9611. break;
  9612. }
  9613. }
  9614. detail::divide(req.target, '?',
  9615. [&](const char *lhs_data, std::size_t lhs_size,
  9616. const char *rhs_data, std::size_t rhs_size) {
  9617. req.path =
  9618. decode_path_component(std::string(lhs_data, lhs_size));
  9619. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9620. });
  9621. }
  9622. return true;
  9623. }
  9624. inline bool Server::write_response(Stream &strm, bool close_connection,
  9625. Request &req, Response &res) {
  9626. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9627. // incorrectly to the error content.
  9628. req.ranges.clear();
  9629. return write_response_core(strm, close_connection, req, res, false);
  9630. }
  9631. inline bool Server::write_response_with_content(Stream &strm,
  9632. bool close_connection,
  9633. const Request &req,
  9634. Response &res) {
  9635. return write_response_core(strm, close_connection, req, res, true);
  9636. }
  9637. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9638. const Request &req, Response &res,
  9639. bool need_apply_ranges) {
  9640. assert(res.status != -1);
  9641. if (400 <= res.status && error_handler_ &&
  9642. error_handler_(req, res) == HandlerResponse::Handled) {
  9643. need_apply_ranges = true;
  9644. }
  9645. std::string content_type;
  9646. std::string boundary;
  9647. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9648. // Prepare additional headers
  9649. if (close_connection || req.get_header_value("Connection") == "close" ||
  9650. 400 <= res.status) { // Don't leave connections open after errors
  9651. res.set_header("Connection", "close");
  9652. } else {
  9653. std::string s = "timeout=";
  9654. s += std::to_string(keep_alive_timeout_sec_);
  9655. s += ", max=";
  9656. s += std::to_string(keep_alive_max_count_);
  9657. res.set_header("Keep-Alive", s);
  9658. }
  9659. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9660. !res.has_header("Content-Type")) {
  9661. res.set_header("Content-Type", "text/plain");
  9662. }
  9663. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9664. !res.has_header("Content-Length")) {
  9665. res.set_header("Content-Length", "0");
  9666. }
  9667. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9668. res.set_header("Accept-Ranges", "bytes");
  9669. }
  9670. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9671. // Response line and headers
  9672. detail::BufferStream bstrm;
  9673. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9674. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9675. // Combine small body with headers to reduce write syscalls
  9676. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9677. bstrm.write(res.body.data(), res.body.size());
  9678. }
  9679. // Log before writing to avoid race condition with client-side code that
  9680. // accesses logger-captured data immediately after receiving the response.
  9681. output_log(req, res);
  9682. // Flush buffer
  9683. auto &data = bstrm.get_buffer();
  9684. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9685. // Streaming body
  9686. auto ret = true;
  9687. if (req.method != "HEAD" && res.content_provider_) {
  9688. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9689. res.content_provider_success_ = true;
  9690. } else {
  9691. ret = false;
  9692. }
  9693. }
  9694. return ret;
  9695. }
  9696. inline bool
  9697. Server::write_content_with_provider(Stream &strm, const Request &req,
  9698. Response &res, const std::string &boundary,
  9699. const std::string &content_type) {
  9700. auto is_shutting_down = [this]() {
  9701. return this->svr_sock_ == INVALID_SOCKET;
  9702. };
  9703. if (res.content_length_ > 0) {
  9704. if (req.ranges.empty()) {
  9705. return detail::write_content(strm, res.content_provider_, 0,
  9706. res.content_length_, is_shutting_down);
  9707. } else if (req.ranges.size() == 1) {
  9708. auto offset_and_length = detail::get_range_offset_and_length(
  9709. req.ranges[0], res.content_length_);
  9710. return detail::write_content(strm, res.content_provider_,
  9711. offset_and_length.first,
  9712. offset_and_length.second, is_shutting_down);
  9713. } else {
  9714. return detail::write_multipart_ranges_data(
  9715. strm, req, res, boundary, content_type, res.content_length_,
  9716. is_shutting_down);
  9717. }
  9718. } else {
  9719. if (res.is_chunked_content_provider_) {
  9720. auto type = detail::encoding_type(req, res);
  9721. auto compressor = detail::make_compressor(type);
  9722. if (!compressor) {
  9723. compressor = detail::make_unique<detail::nocompressor>();
  9724. }
  9725. return detail::write_content_chunked(strm, res.content_provider_,
  9726. is_shutting_down, *compressor);
  9727. } else {
  9728. return detail::write_content_without_length(strm, res.content_provider_,
  9729. is_shutting_down);
  9730. }
  9731. }
  9732. }
  9733. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9734. FormFields::iterator cur_field;
  9735. FormFiles::iterator cur_file;
  9736. auto is_text_field = false;
  9737. size_t count = 0;
  9738. if (read_content_core(
  9739. strm, req, res,
  9740. // Regular
  9741. [&](const char *buf, size_t n) {
  9742. // Prevent arithmetic overflow when checking sizes.
  9743. // Avoid computing (req.body.size() + n) directly because
  9744. // adding two unsigned `size_t` values can wrap around and
  9745. // produce a small result instead of indicating overflow.
  9746. // Instead, check using subtraction: ensure `n` does not
  9747. // exceed the remaining capacity `max_size() - size()`.
  9748. if (req.body.size() >= req.body.max_size() ||
  9749. n > req.body.max_size() - req.body.size()) {
  9750. return false;
  9751. }
  9752. // Limit decompressed body size to payload_max_length_ to protect
  9753. // against "zip bomb" attacks where a small compressed payload
  9754. // decompresses to a massive size.
  9755. if (payload_max_length_ > 0 &&
  9756. (req.body.size() >= payload_max_length_ ||
  9757. n > payload_max_length_ - req.body.size())) {
  9758. return false;
  9759. }
  9760. req.body.append(buf, n);
  9761. return true;
  9762. },
  9763. // Multipart FormData
  9764. [&](const FormData &file) {
  9765. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9766. output_error_log(Error::TooManyFormDataFiles, &req);
  9767. return false;
  9768. }
  9769. if (file.filename.empty()) {
  9770. cur_field = req.form.fields.emplace(
  9771. file.name, FormField{file.name, file.content, file.headers});
  9772. is_text_field = true;
  9773. } else {
  9774. cur_file = req.form.files.emplace(file.name, file);
  9775. is_text_field = false;
  9776. }
  9777. return true;
  9778. },
  9779. [&](const char *buf, size_t n) {
  9780. if (is_text_field) {
  9781. auto &content = cur_field->second.content;
  9782. if (content.size() + n > content.max_size()) { return false; }
  9783. content.append(buf, n);
  9784. } else {
  9785. auto &content = cur_file->second.content;
  9786. if (content.size() + n > content.max_size()) { return false; }
  9787. content.append(buf, n);
  9788. }
  9789. return true;
  9790. })) {
  9791. const auto &content_type = req.get_header_value("Content-Type");
  9792. if (detail::extract_media_type(content_type) ==
  9793. "application/x-www-form-urlencoded") {
  9794. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9795. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9796. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9797. return false;
  9798. }
  9799. detail::parse_query_text(req.body, req.params);
  9800. }
  9801. return true;
  9802. }
  9803. return false;
  9804. }
  9805. inline bool Server::read_content_with_content_receiver(
  9806. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9807. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9808. return read_content_core(strm, req, res, std::move(receiver),
  9809. std::move(multipart_header),
  9810. std::move(multipart_receiver));
  9811. }
  9812. inline bool Server::read_content_core(
  9813. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9814. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9815. detail::FormDataParser multipart_form_data_parser;
  9816. ContentReceiverWithProgress out;
  9817. if (req.is_multipart_form_data()) {
  9818. const auto &content_type = req.get_header_value("Content-Type");
  9819. std::string boundary;
  9820. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9821. res.status = StatusCode::BadRequest_400;
  9822. output_error_log(Error::MultipartParsing, &req);
  9823. return false;
  9824. }
  9825. multipart_form_data_parser.set_boundary(std::move(boundary));
  9826. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9827. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9828. multipart_receiver);
  9829. };
  9830. } else {
  9831. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9832. size_t /*len*/) { return receiver(buf, n); };
  9833. }
  9834. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9835. // For non-SSL builds we still scan non-persistent connections for stray
  9836. // body bytes so the payload limit is enforced (413). On keep-alive,
  9837. // pending bytes may be the next request (issue #2450), so skip.
  9838. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9839. if (!req.has_header("Content-Length") &&
  9840. !detail::is_chunked_transfer_encoding(req.headers)) {
  9841. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9842. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9843. auto has_data = strm.is_readable();
  9844. if (!has_data) {
  9845. auto s = strm.socket();
  9846. if (s != INVALID_SOCKET) {
  9847. has_data = detail::select_read(s, 0, 0) > 0;
  9848. }
  9849. }
  9850. if (has_data) {
  9851. auto result =
  9852. detail::read_content_without_length(strm, payload_max_length_, out);
  9853. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9854. res.status = StatusCode::PayloadTooLarge_413;
  9855. return false;
  9856. } else if (result != detail::ReadContentResult::Success) {
  9857. return false;
  9858. }
  9859. return true;
  9860. }
  9861. }
  9862. return true;
  9863. }
  9864. #else
  9865. if (!req.has_header("Content-Length") &&
  9866. !detail::is_chunked_transfer_encoding(req.headers)) {
  9867. return true;
  9868. }
  9869. #endif
  9870. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9871. out, true)) {
  9872. return false;
  9873. }
  9874. req.body_consumed_ = true;
  9875. if (req.is_multipart_form_data()) {
  9876. if (!multipart_form_data_parser.is_valid()) {
  9877. res.status = StatusCode::BadRequest_400;
  9878. output_error_log(Error::MultipartParsing, &req);
  9879. return false;
  9880. }
  9881. }
  9882. return true;
  9883. }
  9884. inline bool Server::handle_file_request(Request &req, Response &res) {
  9885. for (const auto &entry : base_dirs_) {
  9886. // Prefix match
  9887. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9888. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9889. if (detail::is_valid_path(sub_path)) {
  9890. auto path = entry.base_dir + sub_path;
  9891. if (path.back() == '/') { path += "index.html"; }
  9892. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9893. // but symlinks/junctions can still escape the base directory.
  9894. if (!entry.resolved_base_dir.empty()) {
  9895. std::string resolved_path;
  9896. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9897. !detail::is_path_within_base(resolved_path,
  9898. entry.resolved_base_dir)) {
  9899. res.status = StatusCode::Forbidden_403;
  9900. return true;
  9901. }
  9902. }
  9903. detail::FileStat stat(path);
  9904. if (stat.is_dir()) {
  9905. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9906. return true;
  9907. }
  9908. if (stat.is_file()) {
  9909. for (const auto &kv : entry.headers) {
  9910. res.set_header(kv.first, kv.second);
  9911. }
  9912. auto etag = detail::compute_etag(stat);
  9913. if (!etag.empty()) { res.set_header("ETag", etag); }
  9914. auto mtime = stat.mtime();
  9915. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9916. if (!last_modified.empty()) {
  9917. res.set_header("Last-Modified", last_modified);
  9918. }
  9919. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9920. check_if_range(req, etag, mtime);
  9921. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9922. if (!mm->is_open()) {
  9923. output_error_log(Error::OpenFile, &req);
  9924. return false;
  9925. }
  9926. res.set_content_provider(
  9927. mm->size(),
  9928. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9929. default_file_mimetype_),
  9930. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9931. sink.write(mm->data() + offset, length);
  9932. return true;
  9933. });
  9934. if (req.method != "HEAD" && file_request_handler_) {
  9935. file_request_handler_(req, res);
  9936. }
  9937. return true;
  9938. } else {
  9939. output_error_log(Error::OpenFile, &req);
  9940. }
  9941. }
  9942. }
  9943. }
  9944. return false;
  9945. }
  9946. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9947. const std::string &etag,
  9948. time_t mtime) const {
  9949. // Handle conditional GET:
  9950. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9951. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9952. if (req.has_header("If-None-Match")) {
  9953. if (!etag.empty()) {
  9954. auto val = req.get_header_value("If-None-Match");
  9955. // NOTE: We use exact string matching here. This works correctly
  9956. // because our server always generates weak ETags (W/"..."), and
  9957. // clients typically send back the same ETag they received.
  9958. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9959. // If-None-Match, where W/"x" and "x" would match, but this
  9960. // simplified implementation requires exact matches.
  9961. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9962. [&](const char *b, const char *e) {
  9963. auto seg_len = static_cast<size_t>(e - b);
  9964. return (seg_len == 1 && *b == '*') ||
  9965. (seg_len == etag.size() &&
  9966. std::equal(b, e, etag.begin()));
  9967. });
  9968. if (ret) {
  9969. res.status = StatusCode::NotModified_304;
  9970. return true;
  9971. }
  9972. }
  9973. } else if (req.has_header("If-Modified-Since")) {
  9974. auto val = req.get_header_value("If-Modified-Since");
  9975. auto t = detail::parse_http_date(val);
  9976. if (t != static_cast<time_t>(-1) && mtime <= t) {
  9977. res.status = StatusCode::NotModified_304;
  9978. return true;
  9979. }
  9980. }
  9981. return false;
  9982. }
  9983. inline bool Server::check_if_range(Request &req, const std::string &etag,
  9984. time_t mtime) const {
  9985. // Handle If-Range for partial content requests (RFC 9110
  9986. // Section 13.1.5). If-Range is only evaluated when Range header is
  9987. // present. If the validator matches, serve partial content; otherwise
  9988. // serve full content.
  9989. if (!req.ranges.empty() && req.has_header("If-Range")) {
  9990. auto val = req.get_header_value("If-Range");
  9991. auto is_valid_range = [&]() {
  9992. if (detail::is_strong_etag(val)) {
  9993. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  9994. // comparison.
  9995. return (!etag.empty() && val == etag);
  9996. } else if (detail::is_weak_etag(val)) {
  9997. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  9998. return false;
  9999. } else {
  10000. // HTTP-date comparison
  10001. auto t = detail::parse_http_date(val);
  10002. return (t != static_cast<time_t>(-1) && mtime <= t);
  10003. }
  10004. };
  10005. if (!is_valid_range()) {
  10006. // Validator doesn't match: ignore Range and serve full content
  10007. req.ranges.clear();
  10008. return false;
  10009. }
  10010. }
  10011. return true;
  10012. }
  10013. inline socket_t
  10014. Server::create_server_socket(const std::string &host, int port,
  10015. int socket_flags,
  10016. SocketOptions socket_options) const {
  10017. return detail::create_socket(
  10018. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10019. ipv6_v6only_, std::move(socket_options),
  10020. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10021. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10022. output_error_log(Error::BindIPAddress, nullptr);
  10023. return false;
  10024. }
  10025. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10026. output_error_log(Error::Listen, nullptr);
  10027. return false;
  10028. }
  10029. return true;
  10030. });
  10031. }
  10032. inline int Server::bind_internal(const std::string &host, int port,
  10033. int socket_flags) {
  10034. if (is_decommissioned) { return -1; }
  10035. if (!is_valid()) { return -1; }
  10036. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10037. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10038. if (port == 0) {
  10039. struct sockaddr_storage addr;
  10040. socklen_t addr_len = sizeof(addr);
  10041. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10042. &addr_len) == -1) {
  10043. output_error_log(Error::GetSockName, nullptr);
  10044. return -1;
  10045. }
  10046. if (addr.ss_family == AF_INET) {
  10047. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10048. } else if (addr.ss_family == AF_INET6) {
  10049. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10050. } else {
  10051. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10052. return -1;
  10053. }
  10054. } else {
  10055. return port;
  10056. }
  10057. }
  10058. inline bool Server::listen_internal() {
  10059. if (is_decommissioned) { return false; }
  10060. auto ret = true;
  10061. is_running_ = true;
  10062. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10063. if (start_handler_) { start_handler_(); }
  10064. {
  10065. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10066. while (svr_sock_ != INVALID_SOCKET) {
  10067. #ifndef _WIN32
  10068. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10069. #endif
  10070. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10071. idle_interval_usec_);
  10072. if (val == 0) { // Timeout
  10073. task_queue->on_idle();
  10074. continue;
  10075. }
  10076. #ifndef _WIN32
  10077. }
  10078. #endif
  10079. #if defined _WIN32
  10080. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10081. // OVERLAPPED
  10082. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10083. #elif defined SOCK_CLOEXEC
  10084. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10085. #else
  10086. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10087. #endif
  10088. if (sock == INVALID_SOCKET) {
  10089. if (errno == EMFILE) {
  10090. // The per-process limit of open file descriptors has been reached.
  10091. // Try to accept new connections after a short sleep.
  10092. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10093. continue;
  10094. } else if (errno == EINTR || errno == EAGAIN) {
  10095. continue;
  10096. }
  10097. if (svr_sock_ != INVALID_SOCKET) {
  10098. detail::close_socket(svr_sock_);
  10099. ret = false;
  10100. output_error_log(Error::Connection, nullptr);
  10101. } else {
  10102. ; // The server socket was closed by user.
  10103. }
  10104. break;
  10105. }
  10106. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10107. read_timeout_sec_, read_timeout_usec_);
  10108. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10109. write_timeout_sec_, write_timeout_usec_);
  10110. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10111. if (!task_queue->enqueue(
  10112. [this, sock]() { process_and_close_socket(sock); })) {
  10113. output_error_log(Error::ResourceExhaustion, nullptr);
  10114. detail::shutdown_socket(sock);
  10115. detail::close_socket(sock);
  10116. }
  10117. }
  10118. task_queue->shutdown();
  10119. }
  10120. is_decommissioned = !ret;
  10121. return ret;
  10122. }
  10123. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10124. if (pre_routing_handler_ &&
  10125. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10126. return true;
  10127. }
  10128. // File handler
  10129. if ((req.method == "GET" || req.method == "HEAD") &&
  10130. handle_file_request(req, res)) {
  10131. return true;
  10132. }
  10133. if (detail::expect_content(req)) {
  10134. // Content reader handler
  10135. {
  10136. // Track whether the ContentReader was aborted due to the decompressed
  10137. // payload exceeding `payload_max_length_`.
  10138. // The user handler runs after the lambda returns, so we must restore the
  10139. // 413 status if the handler overwrites it.
  10140. bool content_reader_payload_too_large = false;
  10141. ContentReader reader(
  10142. [&](ContentReceiver receiver) {
  10143. auto result = read_content_with_content_receiver(
  10144. strm, req, res, std::move(receiver), nullptr, nullptr);
  10145. if (!result) {
  10146. output_error_log(Error::Read, &req);
  10147. if (res.status == StatusCode::PayloadTooLarge_413) {
  10148. content_reader_payload_too_large = true;
  10149. }
  10150. }
  10151. return result;
  10152. },
  10153. [&](FormDataHeader header, ContentReceiver receiver) {
  10154. auto result = read_content_with_content_receiver(
  10155. strm, req, res, nullptr, std::move(header),
  10156. std::move(receiver));
  10157. if (!result) {
  10158. output_error_log(Error::Read, &req);
  10159. if (res.status == StatusCode::PayloadTooLarge_413) {
  10160. content_reader_payload_too_large = true;
  10161. }
  10162. }
  10163. return result;
  10164. });
  10165. bool dispatched = false;
  10166. if (req.method == "POST") {
  10167. dispatched = dispatch_request_for_content_reader(
  10168. req, res, std::move(reader), post_handlers_for_content_reader_);
  10169. } else if (req.method == "PUT") {
  10170. dispatched = dispatch_request_for_content_reader(
  10171. req, res, std::move(reader), put_handlers_for_content_reader_);
  10172. } else if (req.method == "PATCH") {
  10173. dispatched = dispatch_request_for_content_reader(
  10174. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10175. } else if (req.method == "DELETE") {
  10176. dispatched = dispatch_request_for_content_reader(
  10177. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10178. }
  10179. if (dispatched) {
  10180. if (content_reader_payload_too_large) {
  10181. // Enforce the limit: override any status the handler may have set
  10182. // and return false so the error path sends a plain 413 response.
  10183. res.status = StatusCode::PayloadTooLarge_413;
  10184. res.body.clear();
  10185. res.content_length_ = 0;
  10186. res.content_provider_ = nullptr;
  10187. return false;
  10188. }
  10189. return true;
  10190. }
  10191. }
  10192. // NOTE: `req.body` is not read here. For a regular handler the body is
  10193. // read inside dispatch_request(), after the route has matched and the
  10194. // pre-request handler has approved the request, so that a rejected
  10195. // request (e.g. failed authentication) never forces us to buffer a
  10196. // potentially large body.
  10197. }
  10198. // Regular handler
  10199. if (req.method == "GET" || req.method == "HEAD") {
  10200. return dispatch_request(req, res, get_handlers_, strm);
  10201. } else if (req.method == "POST") {
  10202. return dispatch_request(req, res, post_handlers_, strm);
  10203. } else if (req.method == "PUT") {
  10204. return dispatch_request(req, res, put_handlers_, strm);
  10205. } else if (req.method == "DELETE") {
  10206. return dispatch_request(req, res, delete_handlers_, strm);
  10207. } else if (req.method == "OPTIONS") {
  10208. return dispatch_request(req, res, options_handlers_, strm);
  10209. } else if (req.method == "PATCH") {
  10210. return dispatch_request(req, res, patch_handlers_, strm);
  10211. }
  10212. res.status = StatusCode::BadRequest_400;
  10213. return false;
  10214. }
  10215. inline bool Server::dispatch_request(Request &req, Response &res,
  10216. const Handlers &handlers, Stream &strm) {
  10217. for (const auto &x : handlers) {
  10218. const auto &matcher = x.first;
  10219. const auto &handler = x.second;
  10220. if (matcher->match(req)) {
  10221. req.matched_route = matcher->pattern();
  10222. // Run the pre-request handler before reading the body so a rejected
  10223. // request (e.g. failed authentication) never forces us to buffer a
  10224. // potentially large body. `req.matched_route` is available here.
  10225. if (pre_request_handler_ &&
  10226. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10227. return true;
  10228. }
  10229. // The route matched and the request was approved; read the body now.
  10230. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10231. output_error_log(Error::Read, &req);
  10232. return false;
  10233. }
  10234. handler(req, res);
  10235. return true;
  10236. }
  10237. }
  10238. return false;
  10239. }
  10240. inline void Server::apply_ranges(const Request &req, Response &res,
  10241. std::string &content_type,
  10242. std::string &boundary) const {
  10243. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10244. auto it = res.headers.find("Content-Type");
  10245. if (it != res.headers.end()) {
  10246. content_type = it->second;
  10247. res.headers.erase(it);
  10248. }
  10249. boundary = detail::make_multipart_data_boundary();
  10250. res.set_header("Content-Type",
  10251. "multipart/byteranges; boundary=" + boundary);
  10252. }
  10253. auto type = detail::encoding_type(req, res);
  10254. if (res.body.empty()) {
  10255. if (res.content_length_ > 0) {
  10256. size_t length = 0;
  10257. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10258. length = res.content_length_;
  10259. } else if (req.ranges.size() == 1) {
  10260. auto offset_and_length = detail::get_range_offset_and_length(
  10261. req.ranges[0], res.content_length_);
  10262. length = offset_and_length.second;
  10263. auto content_range = detail::make_content_range_header_field(
  10264. offset_and_length, res.content_length_);
  10265. res.set_header("Content-Range", content_range);
  10266. } else {
  10267. length = detail::get_multipart_ranges_data_length(
  10268. req, boundary, content_type, res.content_length_);
  10269. }
  10270. res.set_header("Content-Length", std::to_string(length));
  10271. } else {
  10272. if (res.content_provider_) {
  10273. if (res.is_chunked_content_provider_) {
  10274. res.set_header("Transfer-Encoding", "chunked");
  10275. if (type != detail::EncodingType::None) {
  10276. res.set_header("Content-Encoding", detail::encoding_name(type));
  10277. res.set_header("Vary", "Accept-Encoding");
  10278. }
  10279. }
  10280. }
  10281. }
  10282. } else {
  10283. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10284. ;
  10285. } else if (req.ranges.size() == 1) {
  10286. auto offset_and_length =
  10287. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10288. auto offset = offset_and_length.first;
  10289. auto length = offset_and_length.second;
  10290. auto content_range = detail::make_content_range_header_field(
  10291. offset_and_length, res.body.size());
  10292. res.set_header("Content-Range", content_range);
  10293. assert(offset + length <= res.body.size());
  10294. res.body = res.body.substr(offset, length);
  10295. } else {
  10296. std::string data;
  10297. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10298. res.body.size(), data);
  10299. res.body.swap(data);
  10300. }
  10301. if (type != detail::EncodingType::None) {
  10302. output_pre_compression_log(req, res);
  10303. if (auto compressor = detail::make_compressor(type)) {
  10304. std::string compressed;
  10305. if (compressor->compress(res.body.data(), res.body.size(), true,
  10306. [&](const char *data, size_t data_len) {
  10307. compressed.append(data, data_len);
  10308. return true;
  10309. })) {
  10310. res.body.swap(compressed);
  10311. res.set_header("Content-Encoding", detail::encoding_name(type));
  10312. res.set_header("Vary", "Accept-Encoding");
  10313. }
  10314. }
  10315. }
  10316. auto length = std::to_string(res.body.size());
  10317. res.set_header("Content-Length", length);
  10318. }
  10319. }
  10320. inline bool Server::dispatch_request_for_content_reader(
  10321. Request &req, Response &res, ContentReader content_reader,
  10322. const HandlersForContentReader &handlers) const {
  10323. for (const auto &x : handlers) {
  10324. const auto &matcher = x.first;
  10325. const auto &handler = x.second;
  10326. if (matcher->match(req)) {
  10327. req.matched_route = matcher->pattern();
  10328. if (!pre_request_handler_ ||
  10329. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10330. handler(req, res, content_reader);
  10331. }
  10332. return true;
  10333. }
  10334. }
  10335. return false;
  10336. }
  10337. inline std::string
  10338. get_client_ip(const std::string &x_forwarded_for,
  10339. const std::vector<std::string> &trusted_proxies) {
  10340. // X-Forwarded-For is a comma-separated list per RFC 7239
  10341. std::vector<std::string> ip_list;
  10342. detail::split(x_forwarded_for.data(),
  10343. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10344. [&](const char *b, const char *e) {
  10345. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10346. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10347. });
  10348. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10349. // no segments. Signal "no client IP derived" with an empty string so the
  10350. // caller can fall back to the connection-level remote address.
  10351. if (ip_list.empty()) { return std::string(); }
  10352. for (size_t i = 0; i < ip_list.size(); ++i) {
  10353. auto ip = ip_list[i];
  10354. auto is_trusted_proxy =
  10355. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10356. [&](const std::string &proxy) { return ip == proxy; });
  10357. if (is_trusted_proxy) {
  10358. if (i == 0) {
  10359. // If the trusted proxy is the first IP, there's no preceding client IP
  10360. return ip;
  10361. } else {
  10362. // Return the IP immediately before the trusted proxy
  10363. return ip_list[i - 1];
  10364. }
  10365. }
  10366. }
  10367. // If no trusted proxy is found, return the first IP in the list
  10368. return ip_list.front();
  10369. }
  10370. inline bool
  10371. Server::process_request(Stream &strm, const std::string &remote_addr,
  10372. int remote_port, const std::string &local_addr,
  10373. int local_port, bool close_connection,
  10374. bool &connection_closed,
  10375. const std::function<void(Request &)> &setup_request,
  10376. bool *websocket_upgraded) {
  10377. std::array<char, 2048> buf{};
  10378. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10379. // Connection has been closed on client
  10380. if (!line_reader.getline()) { return false; }
  10381. Request req;
  10382. req.start_time_ = std::chrono::steady_clock::now();
  10383. req.remote_addr = remote_addr;
  10384. req.remote_port = remote_port;
  10385. req.local_addr = local_addr;
  10386. req.local_port = local_port;
  10387. Response res;
  10388. res.version = "HTTP/1.1";
  10389. res.headers = default_headers_;
  10390. // Request line and headers
  10391. if (!parse_request_line(line_reader.ptr(), req)) {
  10392. res.status = StatusCode::BadRequest_400;
  10393. output_error_log(Error::InvalidRequestLine, &req);
  10394. return write_response(strm, close_connection, req, res);
  10395. }
  10396. // Request headers
  10397. if (!detail::read_headers(strm, req.headers)) {
  10398. res.status = StatusCode::BadRequest_400;
  10399. output_error_log(Error::InvalidHeaders, &req);
  10400. return write_response(strm, close_connection, req, res);
  10401. }
  10402. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10403. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10404. // tolerated for compatibility with existing clients.
  10405. if (req.get_header_value_u64("Content-Length") > 0 &&
  10406. req.has_header("Transfer-Encoding")) {
  10407. connection_closed = true;
  10408. res.status = StatusCode::BadRequest_400;
  10409. return write_response(strm, close_connection, req, res);
  10410. }
  10411. // Check if the request URI doesn't exceed the limit
  10412. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10413. connection_closed = true;
  10414. res.status = StatusCode::UriTooLong_414;
  10415. output_error_log(Error::ExceedUriMaxLength, &req);
  10416. return write_response(strm, close_connection, req, res);
  10417. }
  10418. if (req.get_header_value("Connection") == "close") {
  10419. connection_closed = true;
  10420. }
  10421. if (req.version == "HTTP/1.0" &&
  10422. req.get_header_value("Connection") != "Keep-Alive") {
  10423. connection_closed = true;
  10424. }
  10425. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10426. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10427. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10428. req.remote_addr = derived.empty() ? remote_addr : derived;
  10429. } else {
  10430. req.remote_addr = remote_addr;
  10431. }
  10432. req.remote_port = remote_port;
  10433. req.local_addr = local_addr;
  10434. req.local_port = local_port;
  10435. if (req.has_header("Accept")) {
  10436. const auto &accept_header = req.get_header_value("Accept");
  10437. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10438. connection_closed = true;
  10439. res.status = StatusCode::BadRequest_400;
  10440. output_error_log(Error::HTTPParsing, &req);
  10441. return write_response(strm, close_connection, req, res);
  10442. }
  10443. }
  10444. if (req.has_header("Range")) {
  10445. const auto &range_header_value = req.get_header_value("Range");
  10446. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10447. connection_closed = true;
  10448. res.status = StatusCode::RangeNotSatisfiable_416;
  10449. output_error_log(Error::InvalidRangeHeader, &req);
  10450. return write_response(strm, close_connection, req, res);
  10451. }
  10452. }
  10453. if (setup_request) { setup_request(req); }
  10454. if (req.get_header_value("Expect") == "100-continue") {
  10455. int status = StatusCode::Continue_100;
  10456. if (expect_100_continue_handler_) {
  10457. status = expect_100_continue_handler_(req, res);
  10458. }
  10459. switch (status) {
  10460. case StatusCode::Continue_100:
  10461. case StatusCode::ExpectationFailed_417:
  10462. detail::write_response_line(strm, status);
  10463. strm.write("\r\n");
  10464. break;
  10465. default:
  10466. connection_closed = true;
  10467. return write_response(strm, true, req, res);
  10468. }
  10469. }
  10470. // Setup `is_connection_closed` method
  10471. auto sock = strm.socket();
  10472. req.is_connection_closed = [sock]() {
  10473. return !detail::is_socket_alive(sock);
  10474. };
  10475. // WebSocket upgrade
  10476. // Check pre_routing_handler_ before upgrading so that authentication
  10477. // and other middleware can reject the request with an HTTP response
  10478. // (e.g., 401) before the protocol switches.
  10479. if (detail::is_websocket_upgrade(req)) {
  10480. if (pre_routing_handler_ &&
  10481. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10482. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10483. return write_response(strm, close_connection, req, res);
  10484. }
  10485. // Find matching WebSocket handler
  10486. for (const auto &entry : websocket_handlers_) {
  10487. if (entry.matcher->match(req)) {
  10488. // Compute accept key
  10489. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10490. auto accept_key = detail::websocket_accept_key(client_key);
  10491. // Negotiate subprotocol
  10492. std::string selected_subprotocol;
  10493. if (entry.sub_protocol_selector) {
  10494. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10495. if (!protocol_header.empty()) {
  10496. std::vector<std::string> protocols;
  10497. std::istringstream iss(protocol_header);
  10498. std::string token;
  10499. while (std::getline(iss, token, ',')) {
  10500. // Trim whitespace
  10501. auto start = token.find_first_not_of(' ');
  10502. auto end = token.find_last_not_of(' ');
  10503. if (start != std::string::npos) {
  10504. protocols.push_back(token.substr(start, end - start + 1));
  10505. }
  10506. }
  10507. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10508. }
  10509. }
  10510. // Send 101 Switching Protocols
  10511. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10512. "Upgrade: websocket\r\n"
  10513. "Connection: Upgrade\r\n"
  10514. "Sec-WebSocket-Accept: " +
  10515. accept_key + "\r\n";
  10516. if (!selected_subprotocol.empty()) {
  10517. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10518. return false;
  10519. }
  10520. handshake_response +=
  10521. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10522. }
  10523. handshake_response += "\r\n";
  10524. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10525. 0) {
  10526. return false;
  10527. }
  10528. connection_closed = true;
  10529. if (websocket_upgraded) { *websocket_upgraded = true; }
  10530. {
  10531. // Use WebSocket-specific read timeout instead of HTTP timeout
  10532. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10533. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10534. websocket_max_missed_pongs_);
  10535. entry.handler(req, ws);
  10536. }
  10537. return true;
  10538. }
  10539. }
  10540. // No matching handler - fall through to 404
  10541. }
  10542. // Routing
  10543. auto routed = false;
  10544. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10545. routed = routing(req, res, strm);
  10546. #else
  10547. try {
  10548. routed = routing(req, res, strm);
  10549. } catch (std::exception &) {
  10550. if (exception_handler_) {
  10551. auto ep = std::current_exception();
  10552. exception_handler_(req, res, ep);
  10553. routed = true;
  10554. } else {
  10555. res.status = StatusCode::InternalServerError_500;
  10556. }
  10557. } catch (...) {
  10558. if (exception_handler_) {
  10559. auto ep = std::current_exception();
  10560. exception_handler_(req, res, ep);
  10561. routed = true;
  10562. } else {
  10563. res.status = StatusCode::InternalServerError_500;
  10564. }
  10565. }
  10566. #endif
  10567. auto ret = false;
  10568. if (routed) {
  10569. if (res.status == -1) {
  10570. res.status = req.ranges.empty() ? StatusCode::OK_200
  10571. : StatusCode::PartialContent_206;
  10572. }
  10573. // Serve file content by using a content provider
  10574. auto file_open_error = false;
  10575. if (!res.file_content_path_.empty()) {
  10576. const auto &path = res.file_content_path_;
  10577. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10578. if (!mm->is_open()) {
  10579. res.body.clear();
  10580. res.content_length_ = 0;
  10581. res.content_provider_ = nullptr;
  10582. res.status = StatusCode::NotFound_404;
  10583. output_error_log(Error::OpenFile, &req);
  10584. file_open_error = true;
  10585. } else {
  10586. auto content_type = res.file_content_content_type_;
  10587. if (content_type.empty()) {
  10588. content_type = detail::find_content_type(
  10589. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10590. }
  10591. res.set_content_provider(
  10592. mm->size(), content_type,
  10593. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10594. sink.write(mm->data() + offset, length);
  10595. return true;
  10596. });
  10597. }
  10598. }
  10599. if (file_open_error) {
  10600. ret = write_response(strm, close_connection, req, res);
  10601. } else if (detail::range_error(req, res)) {
  10602. res.body.clear();
  10603. res.content_length_ = 0;
  10604. res.content_provider_ = nullptr;
  10605. res.status = StatusCode::RangeNotSatisfiable_416;
  10606. ret = write_response(strm, close_connection, req, res);
  10607. } else {
  10608. ret = write_response_with_content(strm, close_connection, req, res);
  10609. }
  10610. } else {
  10611. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10612. ret = write_response(strm, close_connection, req, res);
  10613. }
  10614. // Drain any unconsumed framed body to prevent request smuggling on
  10615. // keep-alive. Without framing there is no body to drain — reading would
  10616. // consume the next request (issue #2450).
  10617. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10618. int dummy_status;
  10619. if (!detail::read_content(
  10620. strm, req, payload_max_length_, dummy_status, nullptr,
  10621. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10622. connection_closed = true;
  10623. }
  10624. }
  10625. return ret;
  10626. }
  10627. inline bool Server::is_valid() const { return true; }
  10628. inline bool Server::process_and_close_socket(socket_t sock) {
  10629. std::string remote_addr;
  10630. int remote_port = 0;
  10631. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10632. std::string local_addr;
  10633. int local_port = 0;
  10634. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10635. bool websocket_upgraded = false;
  10636. auto ret = detail::process_server_socket(
  10637. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10638. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10639. write_timeout_usec_,
  10640. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10641. return process_request(strm, remote_addr, remote_port, local_addr,
  10642. local_port, close_connection, connection_closed,
  10643. nullptr, &websocket_upgraded);
  10644. });
  10645. detail::shutdown_socket(sock);
  10646. detail::close_socket(sock);
  10647. return ret;
  10648. }
  10649. inline void Server::output_log(const Request &req, const Response &res) const {
  10650. if (logger_) {
  10651. std::lock_guard<std::mutex> guard(logger_mutex_);
  10652. logger_(req, res);
  10653. }
  10654. }
  10655. inline void Server::output_pre_compression_log(const Request &req,
  10656. const Response &res) const {
  10657. if (pre_compression_logger_) {
  10658. std::lock_guard<std::mutex> guard(logger_mutex_);
  10659. pre_compression_logger_(req, res);
  10660. }
  10661. }
  10662. inline void Server::output_error_log(const Error &err,
  10663. const Request *req) const {
  10664. if (error_logger_) {
  10665. std::lock_guard<std::mutex> guard(logger_mutex_);
  10666. error_logger_(err, req);
  10667. }
  10668. }
  10669. /*
  10670. * Group 5: ClientImpl and Client (Universal) implementation
  10671. */
  10672. // HTTP client implementation
  10673. inline ClientImpl::ClientImpl(const std::string &host)
  10674. : ClientImpl(host, 80, std::string(), std::string()) {}
  10675. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10676. : ClientImpl(host, port, std::string(), std::string()) {}
  10677. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10678. const std::string &client_cert_path,
  10679. const std::string &client_key_path)
  10680. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10681. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10682. inline ClientImpl::~ClientImpl() {
  10683. // Wait until all the requests in flight are handled.
  10684. size_t retry_count = 10;
  10685. while (retry_count-- > 0) {
  10686. {
  10687. std::lock_guard<std::mutex> guard(socket_mutex_);
  10688. if (socket_requests_in_flight_ == 0) { break; }
  10689. }
  10690. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10691. }
  10692. std::lock_guard<std::mutex> guard(socket_mutex_);
  10693. shutdown_socket(socket_);
  10694. close_socket(socket_);
  10695. }
  10696. inline bool ClientImpl::is_valid() const { return true; }
  10697. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10698. client_cert_path_ = rhs.client_cert_path_;
  10699. client_key_path_ = rhs.client_key_path_;
  10700. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10701. read_timeout_sec_ = rhs.read_timeout_sec_;
  10702. read_timeout_usec_ = rhs.read_timeout_usec_;
  10703. write_timeout_sec_ = rhs.write_timeout_sec_;
  10704. write_timeout_usec_ = rhs.write_timeout_usec_;
  10705. max_timeout_msec_ = rhs.max_timeout_msec_;
  10706. basic_auth_username_ = rhs.basic_auth_username_;
  10707. basic_auth_password_ = rhs.basic_auth_password_;
  10708. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10709. keep_alive_ = rhs.keep_alive_;
  10710. follow_location_ = rhs.follow_location_;
  10711. path_encode_ = rhs.path_encode_;
  10712. address_family_ = rhs.address_family_;
  10713. tcp_nodelay_ = rhs.tcp_nodelay_;
  10714. ipv6_v6only_ = rhs.ipv6_v6only_;
  10715. socket_options_ = rhs.socket_options_;
  10716. compress_ = rhs.compress_;
  10717. decompress_ = rhs.decompress_;
  10718. payload_max_length_ = rhs.payload_max_length_;
  10719. has_payload_max_length_ = rhs.has_payload_max_length_;
  10720. interface_ = rhs.interface_;
  10721. proxy_host_ = rhs.proxy_host_;
  10722. proxy_port_ = rhs.proxy_port_;
  10723. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10724. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10725. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10726. no_proxy_entries_ = rhs.no_proxy_entries_;
  10727. logger_ = rhs.logger_;
  10728. error_logger_ = rhs.error_logger_;
  10729. #ifdef CPPHTTPLIB_SSL_ENABLED
  10730. digest_auth_username_ = rhs.digest_auth_username_;
  10731. digest_auth_password_ = rhs.digest_auth_password_;
  10732. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10733. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10734. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10735. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10736. server_certificate_verification_ = rhs.server_certificate_verification_;
  10737. server_hostname_verification_ = rhs.server_hostname_verification_;
  10738. system_ca_mode_ = rhs.system_ca_mode_;
  10739. #endif
  10740. }
  10741. inline bool
  10742. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10743. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10744. if (no_proxy_entries_.empty()) { return true; }
  10745. // host_ is const so its normalized form is invariant; cache it. The
  10746. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10747. if (host == host_) {
  10748. if (!host_normalized_valid_) {
  10749. host_normalized_ = detail::normalize_target(host_);
  10750. host_normalized_valid_ = true;
  10751. }
  10752. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10753. }
  10754. auto target = detail::normalize_target(host);
  10755. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10756. }
  10757. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10758. if (is_proxy_enabled_for_host(host_)) {
  10759. return detail::create_client_socket(
  10760. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10761. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10762. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10763. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10764. }
  10765. // Check is custom IP specified for host_
  10766. std::string ip;
  10767. auto it = addr_map_.find(host_);
  10768. if (it != addr_map_.end()) { ip = it->second; }
  10769. return detail::create_client_socket(
  10770. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10771. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10772. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10773. write_timeout_usec_, interface_, error);
  10774. }
  10775. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10776. Error &error) {
  10777. auto sock = create_client_socket(error);
  10778. if (sock == INVALID_SOCKET) { return false; }
  10779. socket.sock = sock;
  10780. return true;
  10781. }
  10782. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10783. return create_and_connect_socket(socket, error);
  10784. }
  10785. inline bool ClientImpl::setup_proxy_connection(
  10786. Socket & /*socket*/,
  10787. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10788. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10789. return true;
  10790. }
  10791. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10792. bool /*shutdown_gracefully*/) {
  10793. // If there are any requests in flight from threads other than us, then it's
  10794. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10795. assert(socket_requests_in_flight_ == 0 ||
  10796. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10797. }
  10798. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10799. if (socket.sock == INVALID_SOCKET) { return; }
  10800. detail::shutdown_socket(socket.sock);
  10801. }
  10802. inline void ClientImpl::close_socket(Socket &socket) {
  10803. // If there are requests in flight in another thread, usually closing
  10804. // the socket will be fine and they will simply receive an error when
  10805. // using the closed socket, but it is still a bug since rarely the OS
  10806. // may reassign the socket id to be used for a new socket, and then
  10807. // suddenly they will be operating on a live socket that is different
  10808. // than the one they intended!
  10809. assert(socket_requests_in_flight_ == 0 ||
  10810. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10811. // It is also a bug if this happens while SSL is still active
  10812. #ifdef CPPHTTPLIB_SSL_ENABLED
  10813. assert(socket.ssl == nullptr);
  10814. #endif
  10815. if (socket.sock == INVALID_SOCKET) { return; }
  10816. detail::close_socket(socket.sock);
  10817. socket.sock = INVALID_SOCKET;
  10818. }
  10819. inline void ClientImpl::disconnect(bool gracefully) {
  10820. shutdown_ssl(socket_, gracefully);
  10821. shutdown_socket(socket_);
  10822. close_socket(socket_);
  10823. }
  10824. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10825. Response &res,
  10826. bool skip_100_continue) const {
  10827. std::array<char, 2048> buf{};
  10828. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10829. if (!line_reader.getline()) { return false; }
  10830. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10831. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10832. #else
  10833. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10834. #endif
  10835. std::cmatch m;
  10836. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10837. return req.method == "CONNECT";
  10838. }
  10839. res.version = std::string(m[1]);
  10840. res.status = std::stoi(std::string(m[2]));
  10841. res.reason = std::string(m[3]);
  10842. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10843. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10844. if (!line_reader.getline()) { return false; } // CRLF
  10845. if (!line_reader.getline()) { return false; } // next response line
  10846. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10847. res.version = std::string(m[1]);
  10848. res.status = std::stoi(std::string(m[2]));
  10849. res.reason = std::string(m[3]);
  10850. }
  10851. return true;
  10852. }
  10853. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10854. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10855. auto ret = send_(req, res, error);
  10856. if (error == Error::SSLPeerCouldBeClosed_) {
  10857. assert(!ret);
  10858. ret = send_(req, res, error);
  10859. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10860. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10861. }
  10862. return ret;
  10863. }
  10864. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10865. {
  10866. std::lock_guard<std::mutex> guard(socket_mutex_);
  10867. // Set this to false immediately - if it ever gets set to true by the end
  10868. // of the request, we know another thread instructed us to close the
  10869. // socket.
  10870. socket_should_be_closed_when_request_is_done_ = false;
  10871. auto is_alive = false;
  10872. if (socket_.is_open()) {
  10873. is_alive = detail::is_socket_alive(socket_.sock);
  10874. #ifdef CPPHTTPLIB_SSL_ENABLED
  10875. if (is_alive && is_ssl()) {
  10876. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10877. is_alive = false;
  10878. }
  10879. }
  10880. #endif
  10881. if (!is_alive) {
  10882. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10883. disconnect(/*gracefully=*/false);
  10884. }
  10885. }
  10886. if (!is_alive) {
  10887. if (!ensure_socket_connection(socket_, error)) {
  10888. output_error_log(error, &req);
  10889. return false;
  10890. }
  10891. {
  10892. auto success = true;
  10893. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10894. error)) {
  10895. if (!success) { output_error_log(error, &req); }
  10896. return success;
  10897. }
  10898. }
  10899. }
  10900. // Mark the current socket as being in use so that it cannot be closed by
  10901. // anyone else while this request is ongoing, even though we will be
  10902. // releasing the mutex.
  10903. if (socket_requests_in_flight_ > 1) {
  10904. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10905. }
  10906. socket_requests_in_flight_ += 1;
  10907. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10908. }
  10909. for (const auto &header : default_headers_) {
  10910. if (req.headers.find(header.first) == req.headers.end()) {
  10911. req.headers.insert(header);
  10912. }
  10913. }
  10914. auto ret = false;
  10915. auto close_connection = !keep_alive_;
  10916. auto se = detail::scope_exit([&]() {
  10917. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10918. std::lock_guard<std::mutex> guard(socket_mutex_);
  10919. socket_requests_in_flight_ -= 1;
  10920. if (socket_requests_in_flight_ <= 0) {
  10921. assert(socket_requests_in_flight_ == 0);
  10922. socket_requests_are_from_thread_ = std::thread::id();
  10923. }
  10924. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10925. !ret) {
  10926. disconnect(/*gracefully=*/true);
  10927. }
  10928. });
  10929. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10930. return handle_request(strm, req, res, close_connection, error);
  10931. });
  10932. if (!ret) {
  10933. if (error == Error::Success) {
  10934. error = Error::Unknown;
  10935. output_error_log(error, &req);
  10936. }
  10937. }
  10938. return ret;
  10939. }
  10940. inline Result ClientImpl::send(const Request &req) {
  10941. auto req2 = req;
  10942. return send_(std::move(req2));
  10943. }
  10944. inline Result ClientImpl::send_(Request &&req) {
  10945. auto res = detail::make_unique<Response>();
  10946. auto error = Error::Success;
  10947. auto ret = send(req, *res, error);
  10948. #ifdef CPPHTTPLIB_SSL_ENABLED
  10949. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10950. last_ssl_error_, last_backend_error_};
  10951. #else
  10952. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10953. #endif
  10954. }
  10955. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10956. const std::string &ct) {
  10957. (void)for_stream;
  10958. for (const auto &header : default_headers_) {
  10959. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10960. }
  10961. if (!r.has_header("Host")) {
  10962. if (address_family_ == AF_UNIX) {
  10963. r.headers.emplace("Host", "localhost");
  10964. } else {
  10965. r.headers.emplace(
  10966. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10967. }
  10968. }
  10969. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10970. if (!r.content_receiver) {
  10971. if (!r.has_header("Accept-Encoding")) {
  10972. std::string accept_encoding;
  10973. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10974. accept_encoding = "br";
  10975. #endif
  10976. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10977. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10978. accept_encoding += "gzip, deflate";
  10979. #endif
  10980. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10981. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10982. accept_encoding += "zstd";
  10983. #endif
  10984. r.set_header("Accept-Encoding", accept_encoding);
  10985. }
  10986. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10987. if (!r.has_header("User-Agent")) {
  10988. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  10989. r.set_header("User-Agent", agent);
  10990. }
  10991. #endif
  10992. }
  10993. if (!r.body.empty()) {
  10994. if (!ct.empty() && !r.has_header("Content-Type")) {
  10995. r.headers.emplace("Content-Type", ct);
  10996. }
  10997. if (!r.has_header("Content-Length")) {
  10998. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  10999. }
  11000. }
  11001. }
  11002. inline ClientImpl::StreamHandle
  11003. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11004. const Params &params, const Headers &headers,
  11005. const std::string &body,
  11006. const std::string &content_type) {
  11007. StreamHandle handle;
  11008. handle.response = detail::make_unique<Response>();
  11009. handle.error = Error::Success;
  11010. auto query_path = params.empty() ? path : append_query_params(path, params);
  11011. handle.connection_ = detail::make_unique<ClientConnection>();
  11012. {
  11013. std::lock_guard<std::mutex> guard(socket_mutex_);
  11014. auto is_alive = false;
  11015. if (socket_.is_open()) {
  11016. is_alive = detail::is_socket_alive(socket_.sock);
  11017. #ifdef CPPHTTPLIB_SSL_ENABLED
  11018. if (is_alive && is_ssl()) {
  11019. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11020. is_alive = false;
  11021. }
  11022. }
  11023. #endif
  11024. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11025. }
  11026. if (!is_alive) {
  11027. if (!ensure_socket_connection(socket_, handle.error)) {
  11028. handle.response.reset();
  11029. return handle;
  11030. }
  11031. {
  11032. auto success = true;
  11033. auto start_time = std::chrono::steady_clock::now();
  11034. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11035. success, handle.error)) {
  11036. if (!success) { handle.response.reset(); }
  11037. return handle;
  11038. }
  11039. }
  11040. }
  11041. transfer_socket_ownership_to_handle(handle);
  11042. }
  11043. #ifdef CPPHTTPLIB_SSL_ENABLED
  11044. if (is_ssl() && handle.connection_->session) {
  11045. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11046. handle.connection_->sock, handle.connection_->session,
  11047. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11048. write_timeout_usec_);
  11049. } else {
  11050. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11051. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11052. write_timeout_sec_, write_timeout_usec_);
  11053. }
  11054. #else
  11055. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11056. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11057. write_timeout_sec_, write_timeout_usec_);
  11058. #endif
  11059. handle.stream_ = handle.socket_stream_.get();
  11060. Request req;
  11061. req.method = method;
  11062. req.path = query_path;
  11063. req.headers = headers;
  11064. req.body = body;
  11065. prepare_default_headers(req, true, content_type);
  11066. auto &strm = *handle.stream_;
  11067. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11068. handle.error = Error::Write;
  11069. handle.response.reset();
  11070. return handle;
  11071. }
  11072. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11073. handle.error)) {
  11074. handle.response.reset();
  11075. return handle;
  11076. }
  11077. if (!body.empty()) {
  11078. if (strm.write(body.data(), body.size()) < 0) {
  11079. handle.error = Error::Write;
  11080. handle.response.reset();
  11081. return handle;
  11082. }
  11083. }
  11084. if (!read_response_line(strm, req, *handle.response) ||
  11085. !detail::read_headers(strm, handle.response->headers)) {
  11086. handle.error = Error::Read;
  11087. handle.response.reset();
  11088. return handle;
  11089. }
  11090. handle.body_reader_.stream = handle.stream_;
  11091. handle.body_reader_.payload_max_length = payload_max_length_;
  11092. if (handle.response->has_header("Content-Length")) {
  11093. bool is_invalid = false;
  11094. auto content_length = detail::get_header_value_u64(
  11095. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11096. if (is_invalid) {
  11097. handle.error = Error::Read;
  11098. handle.response.reset();
  11099. return handle;
  11100. }
  11101. handle.body_reader_.has_content_length = true;
  11102. handle.body_reader_.content_length = content_length;
  11103. }
  11104. auto transfer_encoding =
  11105. handle.response->get_header_value("Transfer-Encoding");
  11106. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  11107. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11108. if (!content_encoding.empty()) {
  11109. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11110. }
  11111. return handle;
  11112. }
  11113. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11114. if (!is_valid() || !response) { return -1; }
  11115. if (decompressor_) { return read_with_decompression(buf, len); }
  11116. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11117. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11118. trailers_parsed_ = true;
  11119. if (body_reader_.chunked_decoder) {
  11120. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11121. response->trailers, response->headers)) {
  11122. return n;
  11123. }
  11124. } else {
  11125. detail::ChunkedDecoder dec(*stream_);
  11126. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11127. return n;
  11128. }
  11129. }
  11130. }
  11131. return n;
  11132. }
  11133. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11134. size_t len) {
  11135. if (decompress_offset_ < decompress_buffer_.size()) {
  11136. auto available = decompress_buffer_.size() - decompress_offset_;
  11137. auto to_copy = (std::min)(len, available);
  11138. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11139. decompress_offset_ += to_copy;
  11140. decompressed_bytes_read_ += to_copy;
  11141. return static_cast<ssize_t>(to_copy);
  11142. }
  11143. decompress_buffer_.clear();
  11144. decompress_offset_ = 0;
  11145. constexpr size_t kDecompressionBufferSize = 8192;
  11146. char compressed_buf[kDecompressionBufferSize];
  11147. while (true) {
  11148. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11149. sizeof(compressed_buf));
  11150. if (n <= 0) { return n; }
  11151. bool decompress_ok = decompressor_->decompress(
  11152. compressed_buf, static_cast<size_t>(n),
  11153. [this](const char *data, size_t data_len) {
  11154. decompress_buffer_.append(data, data_len);
  11155. auto limit = body_reader_.payload_max_length;
  11156. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11157. return false;
  11158. }
  11159. return true;
  11160. });
  11161. if (!decompress_ok) {
  11162. body_reader_.last_error = Error::Read;
  11163. return -1;
  11164. }
  11165. if (!decompress_buffer_.empty()) { break; }
  11166. }
  11167. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11168. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11169. decompress_offset_ = to_copy;
  11170. decompressed_bytes_read_ += to_copy;
  11171. return static_cast<ssize_t>(to_copy);
  11172. }
  11173. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11174. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11175. return;
  11176. }
  11177. trailers_parsed_ = true;
  11178. const auto bufsiz = 128;
  11179. char line_buf[bufsiz];
  11180. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11181. if (!line_reader.getline()) { return; }
  11182. if (!detail::parse_trailers(line_reader, response->trailers,
  11183. response->headers)) {
  11184. return;
  11185. }
  11186. }
  11187. namespace detail {
  11188. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11189. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11190. size_t &out_chunk_offset,
  11191. size_t &out_chunk_total) {
  11192. if (finished) { return 0; }
  11193. if (chunk_remaining == 0) {
  11194. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11195. if (!lr.getline()) { return -1; }
  11196. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11197. const char *p = lr.ptr();
  11198. int v = 0;
  11199. if (!is_hex(*p, v)) { return -1; }
  11200. size_t chunk_len = 0;
  11201. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11202. for (; is_hex(*p, v); ++p) {
  11203. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11204. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11205. }
  11206. while (is_space_or_tab(*p)) {
  11207. ++p;
  11208. }
  11209. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11210. if (chunk_len == 0) {
  11211. chunk_remaining = 0;
  11212. finished = true;
  11213. out_chunk_offset = 0;
  11214. out_chunk_total = 0;
  11215. return 0;
  11216. }
  11217. chunk_remaining = chunk_len;
  11218. last_chunk_total = chunk_remaining;
  11219. last_chunk_offset = 0;
  11220. }
  11221. auto to_read = (std::min)(chunk_remaining, len);
  11222. auto n = strm.read(buf, to_read);
  11223. if (n <= 0) { return -1; }
  11224. auto offset_before = last_chunk_offset;
  11225. last_chunk_offset += static_cast<size_t>(n);
  11226. chunk_remaining -= static_cast<size_t>(n);
  11227. out_chunk_offset = offset_before;
  11228. out_chunk_total = last_chunk_total;
  11229. if (chunk_remaining == 0) {
  11230. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11231. if (!lr.getline()) { return -1; }
  11232. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11233. }
  11234. return n;
  11235. }
  11236. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11237. const Headers &src_headers) {
  11238. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11239. if (!lr.getline()) { return false; }
  11240. return parse_trailers(lr, dest, src_headers);
  11241. }
  11242. } // namespace detail
  11243. inline void
  11244. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11245. handle.connection_->sock = socket_.sock;
  11246. #ifdef CPPHTTPLIB_SSL_ENABLED
  11247. handle.connection_->session = socket_.ssl;
  11248. socket_.ssl = nullptr;
  11249. #endif
  11250. socket_.sock = INVALID_SOCKET;
  11251. }
  11252. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11253. Response &res, bool close_connection,
  11254. Error &error) {
  11255. if (req.path.empty()) {
  11256. error = Error::Connection;
  11257. output_error_log(error, &req);
  11258. return false;
  11259. }
  11260. auto req_save = req;
  11261. bool ret;
  11262. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11263. auto req2 = req;
  11264. req2.path = "http://" +
  11265. detail::make_host_and_port_string(host_, port_, false) +
  11266. req.path;
  11267. ret = process_request(strm, req2, res, close_connection, error);
  11268. req = std::move(req2);
  11269. req.path = req_save.path;
  11270. } else {
  11271. ret = process_request(strm, req, res, close_connection, error);
  11272. }
  11273. if (!ret) { return false; }
  11274. if (res.get_header_value("Connection") == "close" ||
  11275. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11276. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11277. // for this to be safe.
  11278. // This is safe to call because handle_request is only called by send_
  11279. // which locks the request mutex during the process. It would be a bug
  11280. // to call it from a different thread since it's a thread-safety issue
  11281. // to do these things to the socket if another thread is using the socket.
  11282. std::lock_guard<std::mutex> guard(socket_mutex_);
  11283. disconnect(/*gracefully=*/true);
  11284. }
  11285. if (300 < res.status && res.status < 400 && follow_location_) {
  11286. req = std::move(req_save);
  11287. ret = redirect(req, res, error);
  11288. }
  11289. #ifdef CPPHTTPLIB_SSL_ENABLED
  11290. if ((res.status == StatusCode::Unauthorized_401 ||
  11291. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11292. req.authorization_count_ < 5) {
  11293. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11294. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11295. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11296. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11297. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11298. return ret;
  11299. }
  11300. const auto &username =
  11301. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11302. const auto &password =
  11303. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11304. if (!username.empty() && !password.empty()) {
  11305. std::map<std::string, std::string> auth;
  11306. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11307. Request new_req = req;
  11308. new_req.authorization_count_ += 1;
  11309. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11310. : "Authorization");
  11311. new_req.headers.insert(detail::make_digest_authentication_header(
  11312. req, auth, new_req.authorization_count_, detail::random_string(10),
  11313. username, password, is_proxy));
  11314. Response new_res;
  11315. ret = send(new_req, new_res, error);
  11316. if (ret) { res = std::move(new_res); }
  11317. }
  11318. }
  11319. }
  11320. #endif
  11321. return ret;
  11322. }
  11323. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11324. if (req.redirect_count_ == 0) {
  11325. error = Error::ExceedRedirectCount;
  11326. output_error_log(error, &req);
  11327. return false;
  11328. }
  11329. auto location = res.get_header_value("location");
  11330. if (location.empty()) { return false; }
  11331. detail::UrlComponents uc;
  11332. if (!detail::parse_url(location, uc)) { return false; }
  11333. // Only follow http/https redirects
  11334. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11335. return false;
  11336. }
  11337. auto scheme = is_ssl() ? "https" : "http";
  11338. auto next_scheme = std::move(uc.scheme);
  11339. auto next_host = std::move(uc.host);
  11340. auto port_str = std::move(uc.port);
  11341. auto next_path = std::move(uc.path);
  11342. auto next_query = std::move(uc.query);
  11343. auto next_port = port_;
  11344. if (!port_str.empty()) {
  11345. if (!detail::parse_port(port_str, next_port)) { return false; }
  11346. } else if (!next_scheme.empty()) {
  11347. next_port = next_scheme == "https" ? 443 : 80;
  11348. }
  11349. if (next_scheme.empty()) { next_scheme = scheme; }
  11350. if (next_host.empty()) { next_host = host_; }
  11351. if (next_path.empty()) { next_path = "/"; }
  11352. auto path = decode_path_component(next_path) + next_query;
  11353. // Same host redirect - use current client
  11354. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11355. return detail::redirect(*this, req, res, path, location, error);
  11356. }
  11357. // Cross-host/scheme redirect - create new client with robust setup
  11358. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11359. path, location, error);
  11360. }
  11361. // New method for robust redirect client creation
  11362. inline bool ClientImpl::create_redirect_client(
  11363. const std::string &scheme, const std::string &host, int port, Request &req,
  11364. Response &res, const std::string &path, const std::string &location,
  11365. Error &error) {
  11366. // Determine if we need SSL
  11367. auto need_ssl = (scheme == "https");
  11368. // Clean up request headers that are host/client specific
  11369. // Remove headers that should not be carried over to new host
  11370. auto headers_to_remove =
  11371. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  11372. for (const auto &header_name : headers_to_remove) {
  11373. auto it = req.headers.find(header_name);
  11374. while (it != req.headers.end()) {
  11375. it = req.headers.erase(it);
  11376. it = req.headers.find(header_name);
  11377. }
  11378. }
  11379. // Create appropriate client type and handle redirect
  11380. if (need_ssl) {
  11381. #ifdef CPPHTTPLIB_SSL_ENABLED
  11382. // Create SSL client for HTTPS redirect
  11383. SSLClient redirect_client(host, port);
  11384. // Setup basic client configuration first
  11385. setup_redirect_client(redirect_client);
  11386. redirect_client.enable_server_certificate_verification(
  11387. server_certificate_verification_);
  11388. redirect_client.enable_server_hostname_verification(
  11389. server_hostname_verification_);
  11390. redirect_client.system_ca_mode_ = system_ca_mode_;
  11391. // Transfer CA certificate to redirect client
  11392. if (!ca_cert_pem_.empty()) {
  11393. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11394. ca_cert_pem_.size());
  11395. }
  11396. if (!ca_cert_file_path_.empty()) {
  11397. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11398. }
  11399. // Client certificates are set through constructor for SSLClient
  11400. // NOTE: SSLClient constructor already takes client_cert_path and
  11401. // client_key_path so we need to create it properly if client certs are
  11402. // needed
  11403. // Execute the redirect
  11404. return detail::redirect(redirect_client, req, res, path, location, error);
  11405. #else
  11406. // SSL not supported - set appropriate error
  11407. error = Error::SSLConnection;
  11408. output_error_log(error, &req);
  11409. return false;
  11410. #endif
  11411. } else {
  11412. // HTTP redirect
  11413. ClientImpl redirect_client(host, port);
  11414. // Setup client with robust configuration
  11415. setup_redirect_client(redirect_client);
  11416. // Execute the redirect
  11417. return detail::redirect(redirect_client, req, res, path, location, error);
  11418. }
  11419. }
  11420. // New method for robust client setup (based on basic_manual_redirect.cpp
  11421. // logic)
  11422. template <typename ClientType>
  11423. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11424. // Copy basic settings first
  11425. client.set_connection_timeout(connection_timeout_sec_);
  11426. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11427. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11428. client.set_keep_alive(keep_alive_);
  11429. client.set_follow_location(
  11430. true); // Enable redirects to handle multi-step redirects
  11431. client.set_path_encode(path_encode_);
  11432. client.set_compress(compress_);
  11433. client.set_decompress(decompress_);
  11434. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11435. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11436. // 15.4, credentials must not be forwarded when redirecting to a different
  11437. // host. This function is only called for cross-host redirects; same-host
  11438. // redirects are handled directly in ClientImpl::redirect().
  11439. // Copy the proxy configuration unconditionally; the per-target bypass is
  11440. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11441. // still use the proxy.
  11442. client.no_proxy_entries_ = no_proxy_entries_;
  11443. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11444. client.set_proxy(proxy_host_, proxy_port_);
  11445. if (!proxy_basic_auth_username_.empty()) {
  11446. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11447. proxy_basic_auth_password_);
  11448. }
  11449. if (!proxy_bearer_token_auth_token_.empty()) {
  11450. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11451. }
  11452. #ifdef CPPHTTPLIB_SSL_ENABLED
  11453. if (!proxy_digest_auth_username_.empty()) {
  11454. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11455. proxy_digest_auth_password_);
  11456. }
  11457. #endif
  11458. }
  11459. // Copy network and socket settings
  11460. client.set_address_family(address_family_);
  11461. client.set_tcp_nodelay(tcp_nodelay_);
  11462. client.set_ipv6_v6only(ipv6_v6only_);
  11463. if (socket_options_) { client.set_socket_options(socket_options_); }
  11464. if (!interface_.empty()) { client.set_interface(interface_); }
  11465. // Copy logging and headers
  11466. if (logger_) { client.set_logger(logger_); }
  11467. if (error_logger_) { client.set_error_logger(error_logger_); }
  11468. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11469. // Each new client should generate its own headers based on its target host
  11470. }
  11471. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11472. const Request &req,
  11473. Error &error) const {
  11474. auto is_shutting_down = []() { return false; };
  11475. if (req.is_chunked_content_provider_) {
  11476. auto compressor = compress_ ? detail::create_compressor().first
  11477. : std::unique_ptr<detail::compressor>();
  11478. if (!compressor) {
  11479. compressor = detail::make_unique<detail::nocompressor>();
  11480. }
  11481. return detail::write_content_chunked(strm, req.content_provider_,
  11482. is_shutting_down, *compressor, error);
  11483. } else {
  11484. return detail::write_content_with_progress(
  11485. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11486. req.upload_progress, error);
  11487. }
  11488. }
  11489. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11490. bool close_connection, Error &error,
  11491. bool skip_body) {
  11492. // Prepare additional headers
  11493. if (close_connection) {
  11494. if (!req.has_header("Connection")) {
  11495. req.set_header("Connection", "close");
  11496. }
  11497. }
  11498. std::string ct_for_defaults;
  11499. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11500. ct_for_defaults = "text/plain";
  11501. }
  11502. prepare_default_headers(req, false, ct_for_defaults);
  11503. if (req.body.empty()) {
  11504. if (req.content_provider_) {
  11505. if (!req.is_chunked_content_provider_) {
  11506. if (!req.has_header("Content-Length")) {
  11507. auto length = std::to_string(req.content_length_);
  11508. req.set_header("Content-Length", length);
  11509. }
  11510. }
  11511. } else {
  11512. if (req.method == "POST" || req.method == "PUT" ||
  11513. req.method == "PATCH") {
  11514. req.set_header("Content-Length", "0");
  11515. }
  11516. }
  11517. }
  11518. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11519. if (!req.has_header("Authorization")) {
  11520. req.headers.insert(make_basic_authentication_header(
  11521. basic_auth_username_, basic_auth_password_, false));
  11522. }
  11523. }
  11524. if (!bearer_token_auth_token_.empty()) {
  11525. if (!req.has_header("Authorization")) {
  11526. req.headers.insert(make_bearer_token_authentication_header(
  11527. bearer_token_auth_token_, false));
  11528. }
  11529. }
  11530. // Proxy-Authorization is only sent when the proxy is actually used for
  11531. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11532. // credentials directly to the destination server.
  11533. if (is_proxy_enabled_for_host(host_)) {
  11534. if (!proxy_basic_auth_username_.empty() &&
  11535. !proxy_basic_auth_password_.empty() &&
  11536. !req.has_header("Proxy-Authorization")) {
  11537. req.headers.insert(make_basic_authentication_header(
  11538. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11539. }
  11540. if (!proxy_bearer_token_auth_token_.empty() &&
  11541. !req.has_header("Proxy-Authorization")) {
  11542. req.headers.insert(make_bearer_token_authentication_header(
  11543. proxy_bearer_token_auth_token_, true));
  11544. }
  11545. }
  11546. // Request line and headers
  11547. {
  11548. detail::BufferStream bstrm;
  11549. // Extract path and query from req.path
  11550. std::string path_part, query_part;
  11551. auto query_pos = req.path.find('?');
  11552. if (query_pos != std::string::npos) {
  11553. path_part = req.path.substr(0, query_pos);
  11554. query_part = req.path.substr(query_pos + 1);
  11555. } else {
  11556. path_part = req.path;
  11557. query_part = "";
  11558. }
  11559. // Encode path part. If the original `req.path` already contained a
  11560. // query component, preserve its raw query string (including parameter
  11561. // order) instead of reparsing and reassembling it which may reorder
  11562. // parameters due to container ordering (e.g. `Params` uses
  11563. // `std::multimap`). When there is no query in `req.path`, fall back to
  11564. // building a query from `req.params` so existing callers that pass
  11565. // `Params` continue to work.
  11566. auto path_with_query =
  11567. path_encode_ ? detail::encode_path(path_part) : path_part;
  11568. if (!query_part.empty()) {
  11569. // Normalize the query string (decode then re-encode) while preserving
  11570. // the original parameter order. When path encoding is disabled the
  11571. // caller has supplied an already-encoded target and expects the exact
  11572. // bytes to be sent on the wire, so skip normalization for the query
  11573. // too. Normalizing here would decode-then-re-encode the query and
  11574. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11575. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11576. if (path_encode_) {
  11577. auto normalized = detail::normalize_query_string(query_part);
  11578. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11579. } else {
  11580. path_with_query += '?' + query_part;
  11581. }
  11582. // Still populate req.params for handlers/users who read them.
  11583. detail::parse_query_text(query_part, req.params);
  11584. } else {
  11585. // No query in path; parse any query_part (empty) and append params
  11586. // from `req.params` when present (preserves prior behavior for
  11587. // callers who provide Params separately).
  11588. detail::parse_query_text(query_part, req.params);
  11589. if (!req.params.empty()) {
  11590. path_with_query = append_query_params(path_with_query, req.params);
  11591. }
  11592. }
  11593. // Write request line and headers
  11594. detail::write_request_line(bstrm, req.method, path_with_query);
  11595. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11596. error)) {
  11597. output_error_log(error, &req);
  11598. return false;
  11599. }
  11600. // Flush buffer
  11601. auto &data = bstrm.get_buffer();
  11602. if (!detail::write_data(strm, data.data(), data.size())) {
  11603. error = Error::Write;
  11604. output_error_log(error, &req);
  11605. return false;
  11606. }
  11607. }
  11608. // After sending request line and headers, wait briefly for an early server
  11609. // response (e.g. 4xx) and avoid sending a potentially large request body
  11610. // unnecessarily. This workaround is only enabled on Windows because Unix
  11611. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11612. // buffering can accept large writes even when the peer already responded.
  11613. // Check the stream first (which covers SSL via `is_readable()`), then
  11614. // fall back to select on the socket. Only perform the wait for very large
  11615. // request bodies to avoid interfering with normal small requests and
  11616. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11617. // response. Skip this check when using Expect: 100-continue, as the protocol
  11618. // handles early responses properly.
  11619. #if defined(_WIN32)
  11620. if (!skip_body &&
  11621. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11622. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11623. auto start = std::chrono::high_resolution_clock::now();
  11624. for (;;) {
  11625. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11626. // from SSL internals. If the underlying socket is readable, assume an
  11627. // early response may be present.
  11628. auto sock = strm.socket();
  11629. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11630. return false;
  11631. }
  11632. // Fallback to stream-level check for non-socket streams or when the
  11633. // socket isn't reporting readable. Avoid using `is_readable()` for
  11634. // SSL, since `SSL_pending()` may report buffered records that do not
  11635. // indicate a complete application-level response yet.
  11636. if (!is_ssl() && strm.is_readable()) { return false; }
  11637. auto now = std::chrono::high_resolution_clock::now();
  11638. auto elapsed =
  11639. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11640. .count();
  11641. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11642. break;
  11643. }
  11644. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11645. }
  11646. }
  11647. #endif
  11648. // Body
  11649. if (skip_body) { return true; }
  11650. return write_request_body(strm, req, error);
  11651. }
  11652. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11653. Error &error) {
  11654. if (req.body.empty()) {
  11655. return write_content_with_provider(strm, req, error);
  11656. }
  11657. if (req.upload_progress) {
  11658. auto body_size = req.body.size();
  11659. size_t written = 0;
  11660. auto data = req.body.data();
  11661. while (written < body_size) {
  11662. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11663. if (!detail::write_data(strm, data + written, to_write)) {
  11664. error = Error::Write;
  11665. output_error_log(error, &req);
  11666. return false;
  11667. }
  11668. written += to_write;
  11669. if (!req.upload_progress(written, body_size)) {
  11670. error = Error::Canceled;
  11671. output_error_log(error, &req);
  11672. return false;
  11673. }
  11674. }
  11675. } else {
  11676. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11677. error = Error::Write;
  11678. output_error_log(error, &req);
  11679. return false;
  11680. }
  11681. }
  11682. return true;
  11683. }
  11684. inline std::unique_ptr<Response>
  11685. ClientImpl::send_with_content_provider_and_receiver(
  11686. Request &req, const char *body, size_t content_length,
  11687. ContentProvider content_provider,
  11688. ContentProviderWithoutLength content_provider_without_length,
  11689. const std::string &content_type, ContentReceiver content_receiver,
  11690. Error &error) {
  11691. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11692. auto enc = compress_
  11693. ? detail::create_compressor()
  11694. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11695. nullptr, nullptr);
  11696. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11697. if (enc.first && !content_provider_without_length) {
  11698. auto &compressor = enc.first;
  11699. if (content_provider) {
  11700. auto ok = true;
  11701. size_t offset = 0;
  11702. DataSink data_sink;
  11703. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11704. if (ok) {
  11705. auto last = offset + data_len == content_length;
  11706. auto ret = compressor->compress(
  11707. data, data_len, last,
  11708. [&](const char *compressed_data, size_t compressed_data_len) {
  11709. req.body.append(compressed_data, compressed_data_len);
  11710. return true;
  11711. });
  11712. if (ret) {
  11713. offset += data_len;
  11714. } else {
  11715. ok = false;
  11716. }
  11717. }
  11718. return ok;
  11719. };
  11720. while (ok && offset < content_length) {
  11721. if (!content_provider(offset, content_length - offset, data_sink)) {
  11722. error = Error::Canceled;
  11723. output_error_log(error, &req);
  11724. return nullptr;
  11725. }
  11726. }
  11727. } else {
  11728. if (!compressor->compress(body, content_length, true,
  11729. [&](const char *data, size_t data_len) {
  11730. req.body.append(data, data_len);
  11731. return true;
  11732. })) {
  11733. error = Error::Compression;
  11734. output_error_log(error, &req);
  11735. return nullptr;
  11736. }
  11737. }
  11738. } else {
  11739. if (content_provider) {
  11740. req.content_length_ = content_length;
  11741. req.content_provider_ = std::move(content_provider);
  11742. req.is_chunked_content_provider_ = false;
  11743. } else if (content_provider_without_length) {
  11744. req.content_length_ = 0;
  11745. req.content_provider_ = detail::ContentProviderAdapter(
  11746. std::move(content_provider_without_length));
  11747. req.is_chunked_content_provider_ = true;
  11748. req.set_header("Transfer-Encoding", "chunked");
  11749. } else {
  11750. req.body.assign(body, content_length);
  11751. }
  11752. }
  11753. if (content_receiver) {
  11754. req.content_receiver =
  11755. [content_receiver](const char *data, size_t data_length,
  11756. size_t /*offset*/, size_t /*total_length*/) {
  11757. return content_receiver(data, data_length);
  11758. };
  11759. }
  11760. auto res = detail::make_unique<Response>();
  11761. return send(req, *res, error) ? std::move(res) : nullptr;
  11762. }
  11763. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11764. const std::string &method, const std::string &path, const Headers &headers,
  11765. const char *body, size_t content_length, ContentProvider content_provider,
  11766. ContentProviderWithoutLength content_provider_without_length,
  11767. const std::string &content_type, ContentReceiver content_receiver,
  11768. UploadProgress progress) {
  11769. Request req;
  11770. req.method = method;
  11771. req.headers = headers;
  11772. req.path = path;
  11773. req.upload_progress = std::move(progress);
  11774. if (max_timeout_msec_ > 0) {
  11775. req.start_time_ = std::chrono::steady_clock::now();
  11776. }
  11777. auto error = Error::Success;
  11778. auto res = send_with_content_provider_and_receiver(
  11779. req, body, content_length, std::move(content_provider),
  11780. std::move(content_provider_without_length), content_type,
  11781. std::move(content_receiver), error);
  11782. #ifdef CPPHTTPLIB_SSL_ENABLED
  11783. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11784. last_backend_error_};
  11785. #else
  11786. return Result{std::move(res), error, std::move(req.headers)};
  11787. #endif
  11788. }
  11789. inline void ClientImpl::output_log(const Request &req,
  11790. const Response &res) const {
  11791. if (logger_) {
  11792. std::lock_guard<std::mutex> guard(logger_mutex_);
  11793. logger_(req, res);
  11794. }
  11795. }
  11796. inline void ClientImpl::output_error_log(const Error &err,
  11797. const Request *req) const {
  11798. if (error_logger_) {
  11799. std::lock_guard<std::mutex> guard(logger_mutex_);
  11800. error_logger_(err, req);
  11801. }
  11802. }
  11803. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11804. Response &res, bool close_connection,
  11805. Error &error) {
  11806. // Auto-add Expect: 100-continue for large bodies
  11807. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11808. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11809. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11810. req.set_header("Expect", "100-continue");
  11811. }
  11812. }
  11813. // Check for Expect: 100-continue
  11814. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11815. // Send request (skip body if using Expect: 100-continue)
  11816. auto write_request_success =
  11817. write_request(strm, req, close_connection, error, expect_100_continue);
  11818. #ifdef CPPHTTPLIB_SSL_ENABLED
  11819. if (is_ssl() && !expect_100_continue) {
  11820. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11821. if (!is_proxy_enabled) {
  11822. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11823. error = Error::SSLPeerCouldBeClosed_;
  11824. output_error_log(error, &req);
  11825. return false;
  11826. }
  11827. }
  11828. }
  11829. #endif
  11830. // Handle Expect: 100-continue.
  11831. //
  11832. // Wait for an interim/early response by attempting to read the status line
  11833. // under a short timeout, instead of trusting raw socket readability. Over
  11834. // TLS, post-handshake records (e.g. session tickets) make the socket
  11835. // readable without any HTTP response being available; relying on
  11836. // `select_read` there caused the body to be withheld forever and the
  11837. // request to fail with `Read` (#2458). If no status line arrives within the
  11838. // timeout, send the body anyway (matching curl's behavior).
  11839. auto status_line_read = false;
  11840. if (expect_100_continue && write_request_success) {
  11841. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11842. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11843. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11844. strm.set_read_timeout(sec, usec);
  11845. status_line_read = read_response_line(strm, req, res, false);
  11846. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11847. }
  11848. if (!status_line_read) {
  11849. // No interim response within the timeout: send the body and handle the
  11850. // response as usual.
  11851. if (!write_request_body(strm, req, error)) { return false; }
  11852. expect_100_continue = false; // Switch to normal response handling
  11853. }
  11854. }
  11855. // Receive response and headers
  11856. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11857. if ((!status_line_read &&
  11858. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11859. !detail::read_headers(strm, res.headers)) {
  11860. if (write_request_success) { error = Error::Read; }
  11861. output_error_log(error, &req);
  11862. return false;
  11863. }
  11864. if (!write_request_success) { return false; }
  11865. // Handle Expect: 100-continue response
  11866. if (expect_100_continue) {
  11867. if (res.status == StatusCode::Continue_100) {
  11868. // Server accepted, send the body
  11869. if (!write_request_body(strm, req, error)) { return false; }
  11870. // Read the actual response
  11871. res.headers.clear();
  11872. res.body.clear();
  11873. if (!read_response_line(strm, req, res) ||
  11874. !detail::read_headers(strm, res.headers)) {
  11875. error = Error::Read;
  11876. output_error_log(error, &req);
  11877. return false;
  11878. }
  11879. }
  11880. // If not 100 Continue, server returned an error; proceed with that response
  11881. }
  11882. // Body
  11883. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11884. req.method != "CONNECT") {
  11885. auto redirect = 300 < res.status && res.status < 400 &&
  11886. res.status != StatusCode::NotModified_304 &&
  11887. follow_location_;
  11888. if (req.response_handler && !redirect) {
  11889. if (!req.response_handler(res)) {
  11890. error = Error::Canceled;
  11891. output_error_log(error, &req);
  11892. return false;
  11893. }
  11894. }
  11895. auto out =
  11896. req.content_receiver
  11897. ? static_cast<ContentReceiverWithProgress>(
  11898. [&](const char *buf, size_t n, size_t off, size_t len) {
  11899. if (redirect) { return true; }
  11900. auto ret = req.content_receiver(buf, n, off, len);
  11901. if (!ret) {
  11902. error = Error::Canceled;
  11903. output_error_log(error, &req);
  11904. }
  11905. return ret;
  11906. })
  11907. : static_cast<ContentReceiverWithProgress>(
  11908. [&](const char *buf, size_t n, size_t /*off*/,
  11909. size_t /*len*/) {
  11910. assert(res.body.size() + n <= res.body.max_size());
  11911. if (payload_max_length_ > 0 &&
  11912. (res.body.size() >= payload_max_length_ ||
  11913. n > payload_max_length_ - res.body.size())) {
  11914. return false;
  11915. }
  11916. res.body.append(buf, n);
  11917. return true;
  11918. });
  11919. auto progress = [&](size_t current, size_t total) {
  11920. if (!req.download_progress || redirect) { return true; }
  11921. auto ret = req.download_progress(current, total);
  11922. if (!ret) {
  11923. error = Error::Canceled;
  11924. output_error_log(error, &req);
  11925. }
  11926. return ret;
  11927. };
  11928. if (res.has_header("Content-Length")) {
  11929. if (!req.content_receiver) {
  11930. auto len = res.get_header_value_u64("Content-Length");
  11931. if (len > res.body.max_size()) {
  11932. error = Error::Read;
  11933. output_error_log(error, &req);
  11934. return false;
  11935. }
  11936. // Cap the reservation by payload_max_length_ to avoid OOM when a
  11937. // hostile or malformed server sends an enormous Content-Length.
  11938. // The actual body read below is bounded by payload_max_length_,
  11939. // so reserving more than that is never useful.
  11940. auto reserve_len = static_cast<size_t>(len);
  11941. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  11942. reserve_len = payload_max_length_;
  11943. }
  11944. res.body.reserve(reserve_len);
  11945. }
  11946. }
  11947. if (res.status != StatusCode::NotModified_304) {
  11948. int dummy_status;
  11949. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11950. ? (std::numeric_limits<size_t>::max)()
  11951. : payload_max_length_;
  11952. if (!detail::read_content(strm, res, max_length, dummy_status,
  11953. std::move(progress), std::move(out),
  11954. decompress_)) {
  11955. if (error != Error::Canceled) { error = Error::Read; }
  11956. output_error_log(error, &req);
  11957. return false;
  11958. }
  11959. }
  11960. }
  11961. // Log
  11962. output_log(req, res);
  11963. return true;
  11964. }
  11965. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11966. const std::string &boundary, const UploadFormDataItems &items,
  11967. const FormDataProviderItems &provider_items) const {
  11968. size_t cur_item = 0;
  11969. size_t cur_start = 0;
  11970. // cur_item and cur_start are copied to within the std::function and
  11971. // maintain state between successive calls
  11972. return [&, cur_item, cur_start](size_t offset,
  11973. DataSink &sink) mutable -> bool {
  11974. if (!offset && !items.empty()) {
  11975. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  11976. return true;
  11977. } else if (cur_item < provider_items.size()) {
  11978. if (!cur_start) {
  11979. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  11980. provider_items[cur_item], boundary);
  11981. offset += begin.size();
  11982. cur_start = offset;
  11983. sink.os << begin;
  11984. }
  11985. DataSink cur_sink;
  11986. auto has_data = true;
  11987. cur_sink.write = sink.write;
  11988. cur_sink.done = [&]() { has_data = false; };
  11989. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  11990. return false;
  11991. }
  11992. if (!has_data) {
  11993. sink.os << detail::serialize_multipart_formdata_item_end();
  11994. cur_item++;
  11995. cur_start = 0;
  11996. }
  11997. return true;
  11998. } else {
  11999. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12000. sink.done();
  12001. return true;
  12002. }
  12003. };
  12004. }
  12005. inline bool ClientImpl::process_socket(
  12006. const Socket &socket,
  12007. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12008. std::function<bool(Stream &strm)> callback) {
  12009. return detail::process_client_socket(
  12010. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12011. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12012. }
  12013. inline bool ClientImpl::is_ssl() const { return false; }
  12014. inline Result ClientImpl::Get(const std::string &path,
  12015. DownloadProgress progress) {
  12016. return Get(path, Headers(), std::move(progress));
  12017. }
  12018. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12019. const Headers &headers,
  12020. DownloadProgress progress) {
  12021. if (params.empty()) { return Get(path, headers); }
  12022. std::string path_with_query = append_query_params(path, params);
  12023. return Get(path_with_query, headers, std::move(progress));
  12024. }
  12025. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12026. DownloadProgress progress) {
  12027. Request req;
  12028. req.method = "GET";
  12029. req.path = path;
  12030. req.headers = headers;
  12031. req.download_progress = std::move(progress);
  12032. if (max_timeout_msec_ > 0) {
  12033. req.start_time_ = std::chrono::steady_clock::now();
  12034. }
  12035. return send_(std::move(req));
  12036. }
  12037. inline Result ClientImpl::Get(const std::string &path,
  12038. ContentReceiver content_receiver,
  12039. DownloadProgress progress) {
  12040. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12041. std::move(progress));
  12042. }
  12043. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12044. ContentReceiver content_receiver,
  12045. DownloadProgress progress) {
  12046. return Get(path, headers, nullptr, std::move(content_receiver),
  12047. std::move(progress));
  12048. }
  12049. inline Result ClientImpl::Get(const std::string &path,
  12050. ResponseHandler response_handler,
  12051. ContentReceiver content_receiver,
  12052. DownloadProgress progress) {
  12053. return Get(path, Headers(), std::move(response_handler),
  12054. std::move(content_receiver), std::move(progress));
  12055. }
  12056. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12057. ResponseHandler response_handler,
  12058. ContentReceiver content_receiver,
  12059. DownloadProgress progress) {
  12060. Request req;
  12061. req.method = "GET";
  12062. req.path = path;
  12063. req.headers = headers;
  12064. req.response_handler = std::move(response_handler);
  12065. req.content_receiver =
  12066. [content_receiver](const char *data, size_t data_length,
  12067. size_t /*offset*/, size_t /*total_length*/) {
  12068. return content_receiver(data, data_length);
  12069. };
  12070. req.download_progress = std::move(progress);
  12071. if (max_timeout_msec_ > 0) {
  12072. req.start_time_ = std::chrono::steady_clock::now();
  12073. }
  12074. return send_(std::move(req));
  12075. }
  12076. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12077. const Headers &headers,
  12078. ContentReceiver content_receiver,
  12079. DownloadProgress progress) {
  12080. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12081. std::move(progress));
  12082. }
  12083. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12084. const Headers &headers,
  12085. ResponseHandler response_handler,
  12086. ContentReceiver content_receiver,
  12087. DownloadProgress progress) {
  12088. if (params.empty()) {
  12089. return Get(path, headers, std::move(response_handler),
  12090. std::move(content_receiver), std::move(progress));
  12091. }
  12092. std::string path_with_query = append_query_params(path, params);
  12093. return Get(path_with_query, headers, std::move(response_handler),
  12094. std::move(content_receiver), std::move(progress));
  12095. }
  12096. inline Result ClientImpl::Head(const std::string &path) {
  12097. return Head(path, Headers());
  12098. }
  12099. inline Result ClientImpl::Head(const std::string &path,
  12100. const Headers &headers) {
  12101. Request req;
  12102. req.method = "HEAD";
  12103. req.headers = headers;
  12104. req.path = path;
  12105. if (max_timeout_msec_ > 0) {
  12106. req.start_time_ = std::chrono::steady_clock::now();
  12107. }
  12108. return send_(std::move(req));
  12109. }
  12110. inline Result ClientImpl::Post(const std::string &path) {
  12111. return Post(path, std::string(), std::string());
  12112. }
  12113. inline Result ClientImpl::Post(const std::string &path,
  12114. const Headers &headers) {
  12115. return Post(path, headers, nullptr, 0, std::string());
  12116. }
  12117. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12118. size_t content_length,
  12119. const std::string &content_type,
  12120. UploadProgress progress) {
  12121. return Post(path, Headers(), body, content_length, content_type, progress);
  12122. }
  12123. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12124. const std::string &content_type,
  12125. UploadProgress progress) {
  12126. return Post(path, Headers(), body, content_type, progress);
  12127. }
  12128. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12129. return Post(path, Headers(), params);
  12130. }
  12131. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12132. ContentProvider content_provider,
  12133. const std::string &content_type,
  12134. UploadProgress progress) {
  12135. return Post(path, Headers(), content_length, std::move(content_provider),
  12136. content_type, progress);
  12137. }
  12138. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12139. ContentProvider content_provider,
  12140. const std::string &content_type,
  12141. ContentReceiver content_receiver,
  12142. UploadProgress progress) {
  12143. return Post(path, Headers(), content_length, std::move(content_provider),
  12144. content_type, std::move(content_receiver), progress);
  12145. }
  12146. inline Result ClientImpl::Post(const std::string &path,
  12147. ContentProviderWithoutLength content_provider,
  12148. const std::string &content_type,
  12149. UploadProgress progress) {
  12150. return Post(path, Headers(), std::move(content_provider), content_type,
  12151. progress);
  12152. }
  12153. inline Result ClientImpl::Post(const std::string &path,
  12154. ContentProviderWithoutLength content_provider,
  12155. const std::string &content_type,
  12156. ContentReceiver content_receiver,
  12157. UploadProgress progress) {
  12158. return Post(path, Headers(), std::move(content_provider), content_type,
  12159. std::move(content_receiver), progress);
  12160. }
  12161. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12162. const Params &params) {
  12163. auto query = detail::params_to_query_str(params);
  12164. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12165. }
  12166. inline Result ClientImpl::Post(const std::string &path,
  12167. const UploadFormDataItems &items,
  12168. UploadProgress progress) {
  12169. return Post(path, Headers(), items, progress);
  12170. }
  12171. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12172. const UploadFormDataItems &items,
  12173. UploadProgress progress) {
  12174. const auto &boundary = detail::make_multipart_data_boundary();
  12175. const auto &content_type =
  12176. detail::serialize_multipart_formdata_get_content_type(boundary);
  12177. auto content_length = detail::get_multipart_content_length(items, boundary);
  12178. return Post(path, headers, content_length,
  12179. detail::make_multipart_content_provider(items, boundary),
  12180. content_type, progress);
  12181. }
  12182. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12183. const UploadFormDataItems &items,
  12184. const std::string &boundary,
  12185. UploadProgress progress) {
  12186. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12187. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12188. }
  12189. const auto &content_type =
  12190. detail::serialize_multipart_formdata_get_content_type(boundary);
  12191. auto content_length = detail::get_multipart_content_length(items, boundary);
  12192. return Post(path, headers, content_length,
  12193. detail::make_multipart_content_provider(items, boundary),
  12194. content_type, progress);
  12195. }
  12196. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12197. const char *body, size_t content_length,
  12198. const std::string &content_type,
  12199. UploadProgress progress) {
  12200. return send_with_content_provider_and_receiver(
  12201. "POST", path, headers, body, content_length, nullptr, nullptr,
  12202. content_type, nullptr, progress);
  12203. }
  12204. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12205. const std::string &body,
  12206. const std::string &content_type,
  12207. UploadProgress progress) {
  12208. return send_with_content_provider_and_receiver(
  12209. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12210. content_type, nullptr, progress);
  12211. }
  12212. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12213. size_t content_length,
  12214. ContentProvider content_provider,
  12215. const std::string &content_type,
  12216. UploadProgress progress) {
  12217. return send_with_content_provider_and_receiver(
  12218. "POST", path, headers, nullptr, content_length,
  12219. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12220. }
  12221. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12222. size_t content_length,
  12223. ContentProvider content_provider,
  12224. const std::string &content_type,
  12225. ContentReceiver content_receiver,
  12226. DownloadProgress progress) {
  12227. return send_with_content_provider_and_receiver(
  12228. "POST", path, headers, nullptr, content_length,
  12229. std::move(content_provider), nullptr, content_type,
  12230. std::move(content_receiver), std::move(progress));
  12231. }
  12232. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12233. ContentProviderWithoutLength content_provider,
  12234. const std::string &content_type,
  12235. UploadProgress progress) {
  12236. return send_with_content_provider_and_receiver(
  12237. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12238. content_type, nullptr, progress);
  12239. }
  12240. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12241. ContentProviderWithoutLength content_provider,
  12242. const std::string &content_type,
  12243. ContentReceiver content_receiver,
  12244. DownloadProgress progress) {
  12245. return send_with_content_provider_and_receiver(
  12246. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12247. content_type, std::move(content_receiver), std::move(progress));
  12248. }
  12249. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12250. const UploadFormDataItems &items,
  12251. const FormDataProviderItems &provider_items,
  12252. UploadProgress progress) {
  12253. const auto &boundary = detail::make_multipart_data_boundary();
  12254. const auto &content_type =
  12255. detail::serialize_multipart_formdata_get_content_type(boundary);
  12256. return send_with_content_provider_and_receiver(
  12257. "POST", path, headers, nullptr, 0, nullptr,
  12258. get_multipart_content_provider(boundary, items, provider_items),
  12259. content_type, nullptr, progress);
  12260. }
  12261. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12262. const std::string &body,
  12263. const std::string &content_type,
  12264. ContentReceiver content_receiver,
  12265. DownloadProgress progress) {
  12266. Request req;
  12267. req.method = "POST";
  12268. req.path = path;
  12269. req.headers = headers;
  12270. req.body = body;
  12271. req.content_receiver =
  12272. [content_receiver](const char *data, size_t data_length,
  12273. size_t /*offset*/, size_t /*total_length*/) {
  12274. return content_receiver(data, data_length);
  12275. };
  12276. req.download_progress = std::move(progress);
  12277. if (max_timeout_msec_ > 0) {
  12278. req.start_time_ = std::chrono::steady_clock::now();
  12279. }
  12280. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12281. return send_(std::move(req));
  12282. }
  12283. inline Result ClientImpl::Put(const std::string &path) {
  12284. return Put(path, std::string(), std::string());
  12285. }
  12286. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12287. return Put(path, headers, nullptr, 0, std::string());
  12288. }
  12289. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12290. size_t content_length,
  12291. const std::string &content_type,
  12292. UploadProgress progress) {
  12293. return Put(path, Headers(), body, content_length, content_type, progress);
  12294. }
  12295. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12296. const std::string &content_type,
  12297. UploadProgress progress) {
  12298. return Put(path, Headers(), body, content_type, progress);
  12299. }
  12300. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12301. return Put(path, Headers(), params);
  12302. }
  12303. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12304. ContentProvider content_provider,
  12305. const std::string &content_type,
  12306. UploadProgress progress) {
  12307. return Put(path, Headers(), content_length, std::move(content_provider),
  12308. content_type, progress);
  12309. }
  12310. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12311. ContentProvider content_provider,
  12312. const std::string &content_type,
  12313. ContentReceiver content_receiver,
  12314. UploadProgress progress) {
  12315. return Put(path, Headers(), content_length, std::move(content_provider),
  12316. content_type, std::move(content_receiver), progress);
  12317. }
  12318. inline Result ClientImpl::Put(const std::string &path,
  12319. ContentProviderWithoutLength content_provider,
  12320. const std::string &content_type,
  12321. UploadProgress progress) {
  12322. return Put(path, Headers(), std::move(content_provider), content_type,
  12323. progress);
  12324. }
  12325. inline Result ClientImpl::Put(const std::string &path,
  12326. ContentProviderWithoutLength content_provider,
  12327. const std::string &content_type,
  12328. ContentReceiver content_receiver,
  12329. UploadProgress progress) {
  12330. return Put(path, Headers(), std::move(content_provider), content_type,
  12331. std::move(content_receiver), progress);
  12332. }
  12333. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12334. const Params &params) {
  12335. auto query = detail::params_to_query_str(params);
  12336. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12337. }
  12338. inline Result ClientImpl::Put(const std::string &path,
  12339. const UploadFormDataItems &items,
  12340. UploadProgress progress) {
  12341. return Put(path, Headers(), items, progress);
  12342. }
  12343. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12344. const UploadFormDataItems &items,
  12345. UploadProgress progress) {
  12346. const auto &boundary = detail::make_multipart_data_boundary();
  12347. const auto &content_type =
  12348. detail::serialize_multipart_formdata_get_content_type(boundary);
  12349. auto content_length = detail::get_multipart_content_length(items, boundary);
  12350. return Put(path, headers, content_length,
  12351. detail::make_multipart_content_provider(items, boundary),
  12352. content_type, progress);
  12353. }
  12354. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12355. const UploadFormDataItems &items,
  12356. const std::string &boundary,
  12357. UploadProgress progress) {
  12358. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12359. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12360. }
  12361. const auto &content_type =
  12362. detail::serialize_multipart_formdata_get_content_type(boundary);
  12363. auto content_length = detail::get_multipart_content_length(items, boundary);
  12364. return Put(path, headers, content_length,
  12365. detail::make_multipart_content_provider(items, boundary),
  12366. content_type, progress);
  12367. }
  12368. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12369. const char *body, size_t content_length,
  12370. const std::string &content_type,
  12371. UploadProgress progress) {
  12372. return send_with_content_provider_and_receiver(
  12373. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12374. content_type, nullptr, progress);
  12375. }
  12376. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12377. const std::string &body,
  12378. const std::string &content_type,
  12379. UploadProgress progress) {
  12380. return send_with_content_provider_and_receiver(
  12381. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12382. content_type, nullptr, progress);
  12383. }
  12384. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12385. size_t content_length,
  12386. ContentProvider content_provider,
  12387. const std::string &content_type,
  12388. UploadProgress progress) {
  12389. return send_with_content_provider_and_receiver(
  12390. "PUT", path, headers, nullptr, content_length,
  12391. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12392. }
  12393. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12394. size_t content_length,
  12395. ContentProvider content_provider,
  12396. const std::string &content_type,
  12397. ContentReceiver content_receiver,
  12398. UploadProgress progress) {
  12399. return send_with_content_provider_and_receiver(
  12400. "PUT", path, headers, nullptr, content_length,
  12401. std::move(content_provider), nullptr, content_type,
  12402. std::move(content_receiver), progress);
  12403. }
  12404. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12405. ContentProviderWithoutLength content_provider,
  12406. const std::string &content_type,
  12407. UploadProgress progress) {
  12408. return send_with_content_provider_and_receiver(
  12409. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12410. content_type, nullptr, progress);
  12411. }
  12412. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12413. ContentProviderWithoutLength content_provider,
  12414. const std::string &content_type,
  12415. ContentReceiver content_receiver,
  12416. UploadProgress progress) {
  12417. return send_with_content_provider_and_receiver(
  12418. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12419. content_type, std::move(content_receiver), progress);
  12420. }
  12421. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12422. const UploadFormDataItems &items,
  12423. const FormDataProviderItems &provider_items,
  12424. UploadProgress progress) {
  12425. const auto &boundary = detail::make_multipart_data_boundary();
  12426. const auto &content_type =
  12427. detail::serialize_multipart_formdata_get_content_type(boundary);
  12428. return send_with_content_provider_and_receiver(
  12429. "PUT", path, headers, nullptr, 0, nullptr,
  12430. get_multipart_content_provider(boundary, items, provider_items),
  12431. content_type, nullptr, progress);
  12432. }
  12433. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12434. const std::string &body,
  12435. const std::string &content_type,
  12436. ContentReceiver content_receiver,
  12437. DownloadProgress progress) {
  12438. Request req;
  12439. req.method = "PUT";
  12440. req.path = path;
  12441. req.headers = headers;
  12442. req.body = body;
  12443. req.content_receiver =
  12444. [content_receiver](const char *data, size_t data_length,
  12445. size_t /*offset*/, size_t /*total_length*/) {
  12446. return content_receiver(data, data_length);
  12447. };
  12448. req.download_progress = std::move(progress);
  12449. if (max_timeout_msec_ > 0) {
  12450. req.start_time_ = std::chrono::steady_clock::now();
  12451. }
  12452. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12453. return send_(std::move(req));
  12454. }
  12455. inline Result ClientImpl::Patch(const std::string &path) {
  12456. return Patch(path, std::string(), std::string());
  12457. }
  12458. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12459. UploadProgress progress) {
  12460. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12461. }
  12462. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12463. size_t content_length,
  12464. const std::string &content_type,
  12465. UploadProgress progress) {
  12466. return Patch(path, Headers(), body, content_length, content_type, progress);
  12467. }
  12468. inline Result ClientImpl::Patch(const std::string &path,
  12469. const std::string &body,
  12470. const std::string &content_type,
  12471. UploadProgress progress) {
  12472. return Patch(path, Headers(), body, content_type, progress);
  12473. }
  12474. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12475. return Patch(path, Headers(), params);
  12476. }
  12477. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12478. ContentProvider content_provider,
  12479. const std::string &content_type,
  12480. UploadProgress progress) {
  12481. return Patch(path, Headers(), content_length, std::move(content_provider),
  12482. content_type, progress);
  12483. }
  12484. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12485. ContentProvider content_provider,
  12486. const std::string &content_type,
  12487. ContentReceiver content_receiver,
  12488. UploadProgress progress) {
  12489. return Patch(path, Headers(), content_length, std::move(content_provider),
  12490. content_type, std::move(content_receiver), progress);
  12491. }
  12492. inline Result ClientImpl::Patch(const std::string &path,
  12493. ContentProviderWithoutLength content_provider,
  12494. const std::string &content_type,
  12495. UploadProgress progress) {
  12496. return Patch(path, Headers(), std::move(content_provider), content_type,
  12497. progress);
  12498. }
  12499. inline Result ClientImpl::Patch(const std::string &path,
  12500. ContentProviderWithoutLength content_provider,
  12501. const std::string &content_type,
  12502. ContentReceiver content_receiver,
  12503. UploadProgress progress) {
  12504. return Patch(path, Headers(), std::move(content_provider), content_type,
  12505. std::move(content_receiver), progress);
  12506. }
  12507. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12508. const Params &params) {
  12509. auto query = detail::params_to_query_str(params);
  12510. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12511. }
  12512. inline Result ClientImpl::Patch(const std::string &path,
  12513. const UploadFormDataItems &items,
  12514. UploadProgress progress) {
  12515. return Patch(path, Headers(), items, progress);
  12516. }
  12517. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12518. const UploadFormDataItems &items,
  12519. UploadProgress progress) {
  12520. const auto &boundary = detail::make_multipart_data_boundary();
  12521. const auto &content_type =
  12522. detail::serialize_multipart_formdata_get_content_type(boundary);
  12523. auto content_length = detail::get_multipart_content_length(items, boundary);
  12524. return Patch(path, headers, content_length,
  12525. detail::make_multipart_content_provider(items, boundary),
  12526. content_type, progress);
  12527. }
  12528. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12529. const UploadFormDataItems &items,
  12530. const std::string &boundary,
  12531. UploadProgress progress) {
  12532. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12533. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12534. }
  12535. const auto &content_type =
  12536. detail::serialize_multipart_formdata_get_content_type(boundary);
  12537. auto content_length = detail::get_multipart_content_length(items, boundary);
  12538. return Patch(path, headers, content_length,
  12539. detail::make_multipart_content_provider(items, boundary),
  12540. content_type, progress);
  12541. }
  12542. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12543. const char *body, size_t content_length,
  12544. const std::string &content_type,
  12545. UploadProgress progress) {
  12546. return send_with_content_provider_and_receiver(
  12547. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12548. content_type, nullptr, progress);
  12549. }
  12550. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12551. const std::string &body,
  12552. const std::string &content_type,
  12553. UploadProgress progress) {
  12554. return send_with_content_provider_and_receiver(
  12555. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12556. content_type, nullptr, progress);
  12557. }
  12558. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12559. size_t content_length,
  12560. ContentProvider content_provider,
  12561. const std::string &content_type,
  12562. UploadProgress progress) {
  12563. return send_with_content_provider_and_receiver(
  12564. "PATCH", path, headers, nullptr, content_length,
  12565. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12566. }
  12567. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12568. size_t content_length,
  12569. ContentProvider content_provider,
  12570. const std::string &content_type,
  12571. ContentReceiver content_receiver,
  12572. UploadProgress progress) {
  12573. return send_with_content_provider_and_receiver(
  12574. "PATCH", path, headers, nullptr, content_length,
  12575. std::move(content_provider), nullptr, content_type,
  12576. std::move(content_receiver), progress);
  12577. }
  12578. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12579. ContentProviderWithoutLength content_provider,
  12580. const std::string &content_type,
  12581. UploadProgress progress) {
  12582. return send_with_content_provider_and_receiver(
  12583. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12584. content_type, nullptr, progress);
  12585. }
  12586. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12587. ContentProviderWithoutLength content_provider,
  12588. const std::string &content_type,
  12589. ContentReceiver content_receiver,
  12590. UploadProgress progress) {
  12591. return send_with_content_provider_and_receiver(
  12592. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12593. content_type, std::move(content_receiver), progress);
  12594. }
  12595. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12596. const UploadFormDataItems &items,
  12597. const FormDataProviderItems &provider_items,
  12598. UploadProgress progress) {
  12599. const auto &boundary = detail::make_multipart_data_boundary();
  12600. const auto &content_type =
  12601. detail::serialize_multipart_formdata_get_content_type(boundary);
  12602. return send_with_content_provider_and_receiver(
  12603. "PATCH", path, headers, nullptr, 0, nullptr,
  12604. get_multipart_content_provider(boundary, items, provider_items),
  12605. content_type, nullptr, progress);
  12606. }
  12607. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12608. const std::string &body,
  12609. const std::string &content_type,
  12610. ContentReceiver content_receiver,
  12611. DownloadProgress progress) {
  12612. Request req;
  12613. req.method = "PATCH";
  12614. req.path = path;
  12615. req.headers = headers;
  12616. req.body = body;
  12617. req.content_receiver =
  12618. [content_receiver](const char *data, size_t data_length,
  12619. size_t /*offset*/, size_t /*total_length*/) {
  12620. return content_receiver(data, data_length);
  12621. };
  12622. req.download_progress = std::move(progress);
  12623. if (max_timeout_msec_ > 0) {
  12624. req.start_time_ = std::chrono::steady_clock::now();
  12625. }
  12626. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12627. return send_(std::move(req));
  12628. }
  12629. inline Result ClientImpl::Delete(const std::string &path,
  12630. DownloadProgress progress) {
  12631. return Delete(path, Headers(), std::string(), std::string(), progress);
  12632. }
  12633. inline Result ClientImpl::Delete(const std::string &path,
  12634. const Headers &headers,
  12635. DownloadProgress progress) {
  12636. return Delete(path, headers, std::string(), std::string(), progress);
  12637. }
  12638. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12639. size_t content_length,
  12640. const std::string &content_type,
  12641. DownloadProgress progress) {
  12642. return Delete(path, Headers(), body, content_length, content_type, progress);
  12643. }
  12644. inline Result ClientImpl::Delete(const std::string &path,
  12645. const std::string &body,
  12646. const std::string &content_type,
  12647. DownloadProgress progress) {
  12648. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12649. progress);
  12650. }
  12651. inline Result ClientImpl::Delete(const std::string &path,
  12652. const Headers &headers,
  12653. const std::string &body,
  12654. const std::string &content_type,
  12655. DownloadProgress progress) {
  12656. return Delete(path, headers, body.data(), body.size(), content_type,
  12657. progress);
  12658. }
  12659. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12660. DownloadProgress progress) {
  12661. return Delete(path, Headers(), params, progress);
  12662. }
  12663. inline Result ClientImpl::Delete(const std::string &path,
  12664. const Headers &headers, const Params &params,
  12665. DownloadProgress progress) {
  12666. auto query = detail::params_to_query_str(params);
  12667. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12668. progress);
  12669. }
  12670. inline Result ClientImpl::Delete(const std::string &path,
  12671. const Headers &headers, const char *body,
  12672. size_t content_length,
  12673. const std::string &content_type,
  12674. DownloadProgress progress) {
  12675. Request req;
  12676. req.method = "DELETE";
  12677. req.headers = headers;
  12678. req.path = path;
  12679. req.download_progress = std::move(progress);
  12680. if (max_timeout_msec_ > 0) {
  12681. req.start_time_ = std::chrono::steady_clock::now();
  12682. }
  12683. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12684. req.body.assign(body, content_length);
  12685. return send_(std::move(req));
  12686. }
  12687. inline Result ClientImpl::Options(const std::string &path) {
  12688. return Options(path, Headers());
  12689. }
  12690. inline Result ClientImpl::Options(const std::string &path,
  12691. const Headers &headers) {
  12692. Request req;
  12693. req.method = "OPTIONS";
  12694. req.headers = headers;
  12695. req.path = path;
  12696. if (max_timeout_msec_ > 0) {
  12697. req.start_time_ = std::chrono::steady_clock::now();
  12698. }
  12699. return send_(std::move(req));
  12700. }
  12701. inline void ClientImpl::stop() {
  12702. std::lock_guard<std::mutex> guard(socket_mutex_);
  12703. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12704. // do is to shutdown_socket, so that threads using this socket suddenly
  12705. // discover they can't read/write any more and error out. Everything else
  12706. // (closing the socket, shutting ssl down) is unsafe because these actions
  12707. // are not thread-safe.
  12708. if (socket_requests_in_flight_ > 0) {
  12709. shutdown_socket(socket_);
  12710. // Aside from that, we set a flag for the socket to be closed when we're
  12711. // done.
  12712. socket_should_be_closed_when_request_is_done_ = true;
  12713. return;
  12714. }
  12715. disconnect(/*gracefully=*/true);
  12716. }
  12717. inline std::string ClientImpl::host() const { return host_; }
  12718. inline int ClientImpl::port() const { return port_; }
  12719. inline size_t ClientImpl::is_socket_open() const {
  12720. std::lock_guard<std::mutex> guard(socket_mutex_);
  12721. return socket_.is_open();
  12722. }
  12723. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12724. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12725. connection_timeout_sec_ = sec;
  12726. connection_timeout_usec_ = usec;
  12727. }
  12728. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12729. read_timeout_sec_ = sec;
  12730. read_timeout_usec_ = usec;
  12731. }
  12732. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12733. write_timeout_sec_ = sec;
  12734. write_timeout_usec_ = usec;
  12735. }
  12736. inline void ClientImpl::set_max_timeout(time_t msec) {
  12737. max_timeout_msec_ = msec;
  12738. }
  12739. inline void ClientImpl::set_basic_auth(const std::string &username,
  12740. const std::string &password) {
  12741. basic_auth_username_ = username;
  12742. basic_auth_password_ = password;
  12743. }
  12744. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12745. bearer_token_auth_token_ = token;
  12746. }
  12747. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12748. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12749. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12750. inline void
  12751. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12752. addr_map_ = std::move(addr_map);
  12753. }
  12754. inline void ClientImpl::set_default_headers(Headers headers) {
  12755. default_headers_ = std::move(headers);
  12756. }
  12757. inline void ClientImpl::set_header_writer(
  12758. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12759. header_writer_ = writer;
  12760. }
  12761. inline void ClientImpl::set_address_family(int family) {
  12762. address_family_ = family;
  12763. }
  12764. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12765. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12766. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12767. socket_options_ = std::move(socket_options);
  12768. }
  12769. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12770. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12771. inline void ClientImpl::set_payload_max_length(size_t length) {
  12772. payload_max_length_ = length;
  12773. has_payload_max_length_ = true;
  12774. }
  12775. inline void ClientImpl::set_interface(const std::string &intf) {
  12776. interface_ = intf;
  12777. }
  12778. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12779. proxy_host_ = host;
  12780. proxy_port_ = port;
  12781. std::lock_guard<std::mutex> guard(socket_mutex_);
  12782. disconnect(/*gracefully=*/true);
  12783. }
  12784. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12785. const std::string &password) {
  12786. proxy_basic_auth_username_ = username;
  12787. proxy_basic_auth_password_ = password;
  12788. }
  12789. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12790. proxy_bearer_token_auth_token_ = token;
  12791. }
  12792. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12793. std::vector<detail::NoProxyEntry> parsed;
  12794. parsed.reserve(patterns.size());
  12795. for (const auto &p : patterns) {
  12796. auto trimmed = detail::trim_copy(p);
  12797. if (trimmed.empty()) { continue; }
  12798. detail::NoProxyEntry entry;
  12799. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12800. parsed.push_back(std::move(entry));
  12801. }
  12802. }
  12803. no_proxy_entries_ = std::move(parsed);
  12804. std::lock_guard<std::mutex> guard(socket_mutex_);
  12805. disconnect(/*gracefully=*/true);
  12806. }
  12807. #ifdef CPPHTTPLIB_SSL_ENABLED
  12808. inline void ClientImpl::set_digest_auth(const std::string &username,
  12809. const std::string &password) {
  12810. digest_auth_username_ = username;
  12811. digest_auth_password_ = password;
  12812. }
  12813. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12814. const std::string &ca_cert_dir_path) {
  12815. ca_cert_file_path_ = ca_cert_file_path;
  12816. ca_cert_dir_path_ = ca_cert_dir_path;
  12817. }
  12818. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12819. const std::string &password) {
  12820. proxy_digest_auth_username_ = username;
  12821. proxy_digest_auth_password_ = password;
  12822. }
  12823. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12824. server_certificate_verification_ = enabled;
  12825. }
  12826. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12827. server_hostname_verification_ = enabled;
  12828. }
  12829. inline void ClientImpl::enable_system_ca(bool enabled) {
  12830. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12831. }
  12832. #endif
  12833. inline void ClientImpl::set_logger(Logger logger) {
  12834. logger_ = std::move(logger);
  12835. }
  12836. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12837. error_logger_ = std::move(error_logger);
  12838. }
  12839. /*
  12840. * SSL/TLS Common Implementation
  12841. */
  12842. inline ClientConnection::~ClientConnection() {
  12843. #ifdef CPPHTTPLIB_SSL_ENABLED
  12844. if (session) {
  12845. tls::shutdown(session, true);
  12846. tls::free_session(session);
  12847. session = nullptr;
  12848. }
  12849. #endif
  12850. if (sock != INVALID_SOCKET) {
  12851. detail::close_socket(sock);
  12852. sock = INVALID_SOCKET;
  12853. }
  12854. }
  12855. // Universal client implementation
  12856. inline Client::Client(const std::string &scheme_host_port)
  12857. : Client(scheme_host_port, std::string(), std::string()) {}
  12858. inline Client::Client(const std::string &scheme_host_port,
  12859. const std::string &client_cert_path,
  12860. const std::string &client_key_path) {
  12861. detail::UrlComponents uc;
  12862. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12863. auto &scheme = uc.scheme;
  12864. #ifdef CPPHTTPLIB_SSL_ENABLED
  12865. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12866. #else
  12867. if (!scheme.empty() && scheme != "http") {
  12868. #endif
  12869. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12870. std::string msg = "'" + scheme + "' scheme is not supported.";
  12871. throw std::invalid_argument(msg);
  12872. #endif
  12873. return;
  12874. }
  12875. auto is_ssl = scheme == "https";
  12876. auto host = std::move(uc.host);
  12877. auto port = is_ssl ? 443 : 80;
  12878. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12879. if (is_ssl) {
  12880. #ifdef CPPHTTPLIB_SSL_ENABLED
  12881. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12882. client_key_path);
  12883. is_ssl_ = is_ssl;
  12884. #endif
  12885. } else {
  12886. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12887. client_key_path);
  12888. }
  12889. } else {
  12890. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12891. // if port param below changes.
  12892. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12893. client_cert_path, client_key_path);
  12894. }
  12895. }
  12896. inline Client::Client(const std::string &host, int port)
  12897. : Client(host, port, std::string(), std::string()) {}
  12898. inline Client::Client(const std::string &host, int port,
  12899. const std::string &client_cert_path,
  12900. const std::string &client_key_path)
  12901. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12902. client_key_path)) {}
  12903. inline Client::~Client() = default;
  12904. inline bool Client::is_valid() const {
  12905. return cli_ != nullptr && cli_->is_valid();
  12906. }
  12907. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12908. return cli_->Get(path, std::move(progress));
  12909. }
  12910. inline Result Client::Get(const std::string &path, const Headers &headers,
  12911. DownloadProgress progress) {
  12912. return cli_->Get(path, headers, std::move(progress));
  12913. }
  12914. inline Result Client::Get(const std::string &path,
  12915. ContentReceiver content_receiver,
  12916. DownloadProgress progress) {
  12917. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12918. }
  12919. inline Result Client::Get(const std::string &path, const Headers &headers,
  12920. ContentReceiver content_receiver,
  12921. DownloadProgress progress) {
  12922. return cli_->Get(path, headers, std::move(content_receiver),
  12923. std::move(progress));
  12924. }
  12925. inline Result Client::Get(const std::string &path,
  12926. ResponseHandler response_handler,
  12927. ContentReceiver content_receiver,
  12928. DownloadProgress progress) {
  12929. return cli_->Get(path, std::move(response_handler),
  12930. std::move(content_receiver), std::move(progress));
  12931. }
  12932. inline Result Client::Get(const std::string &path, const Headers &headers,
  12933. ResponseHandler response_handler,
  12934. ContentReceiver content_receiver,
  12935. DownloadProgress progress) {
  12936. return cli_->Get(path, headers, std::move(response_handler),
  12937. std::move(content_receiver), std::move(progress));
  12938. }
  12939. inline Result Client::Get(const std::string &path, const Params &params,
  12940. const Headers &headers, DownloadProgress progress) {
  12941. return cli_->Get(path, params, headers, std::move(progress));
  12942. }
  12943. inline Result Client::Get(const std::string &path, const Params &params,
  12944. const Headers &headers,
  12945. ContentReceiver content_receiver,
  12946. DownloadProgress progress) {
  12947. return cli_->Get(path, params, headers, std::move(content_receiver),
  12948. std::move(progress));
  12949. }
  12950. inline Result Client::Get(const std::string &path, const Params &params,
  12951. const Headers &headers,
  12952. ResponseHandler response_handler,
  12953. ContentReceiver content_receiver,
  12954. DownloadProgress progress) {
  12955. return cli_->Get(path, params, headers, std::move(response_handler),
  12956. std::move(content_receiver), std::move(progress));
  12957. }
  12958. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12959. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12960. return cli_->Head(path, headers);
  12961. }
  12962. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12963. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12964. return cli_->Post(path, headers);
  12965. }
  12966. inline Result Client::Post(const std::string &path, const char *body,
  12967. size_t content_length,
  12968. const std::string &content_type,
  12969. UploadProgress progress) {
  12970. return cli_->Post(path, body, content_length, content_type, progress);
  12971. }
  12972. inline Result Client::Post(const std::string &path, const Headers &headers,
  12973. const char *body, size_t content_length,
  12974. const std::string &content_type,
  12975. UploadProgress progress) {
  12976. return cli_->Post(path, headers, body, content_length, content_type,
  12977. progress);
  12978. }
  12979. inline Result Client::Post(const std::string &path, const std::string &body,
  12980. const std::string &content_type,
  12981. UploadProgress progress) {
  12982. return cli_->Post(path, body, content_type, progress);
  12983. }
  12984. inline Result Client::Post(const std::string &path, const Headers &headers,
  12985. const std::string &body,
  12986. const std::string &content_type,
  12987. UploadProgress progress) {
  12988. return cli_->Post(path, headers, body, content_type, progress);
  12989. }
  12990. inline Result Client::Post(const std::string &path, size_t content_length,
  12991. ContentProvider content_provider,
  12992. const std::string &content_type,
  12993. UploadProgress progress) {
  12994. return cli_->Post(path, content_length, std::move(content_provider),
  12995. content_type, progress);
  12996. }
  12997. inline Result Client::Post(const std::string &path, size_t content_length,
  12998. ContentProvider content_provider,
  12999. const std::string &content_type,
  13000. ContentReceiver content_receiver,
  13001. UploadProgress progress) {
  13002. return cli_->Post(path, content_length, std::move(content_provider),
  13003. content_type, std::move(content_receiver), progress);
  13004. }
  13005. inline Result Client::Post(const std::string &path,
  13006. ContentProviderWithoutLength content_provider,
  13007. const std::string &content_type,
  13008. UploadProgress progress) {
  13009. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13010. }
  13011. inline Result Client::Post(const std::string &path,
  13012. ContentProviderWithoutLength content_provider,
  13013. const std::string &content_type,
  13014. ContentReceiver content_receiver,
  13015. UploadProgress progress) {
  13016. return cli_->Post(path, std::move(content_provider), content_type,
  13017. std::move(content_receiver), progress);
  13018. }
  13019. inline Result Client::Post(const std::string &path, const Headers &headers,
  13020. size_t content_length,
  13021. ContentProvider content_provider,
  13022. const std::string &content_type,
  13023. UploadProgress progress) {
  13024. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13025. content_type, progress);
  13026. }
  13027. inline Result Client::Post(const std::string &path, const Headers &headers,
  13028. size_t content_length,
  13029. ContentProvider content_provider,
  13030. const std::string &content_type,
  13031. ContentReceiver content_receiver,
  13032. DownloadProgress progress) {
  13033. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13034. content_type, std::move(content_receiver), progress);
  13035. }
  13036. inline Result Client::Post(const std::string &path, const Headers &headers,
  13037. ContentProviderWithoutLength content_provider,
  13038. const std::string &content_type,
  13039. UploadProgress progress) {
  13040. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13041. progress);
  13042. }
  13043. inline Result Client::Post(const std::string &path, const Headers &headers,
  13044. ContentProviderWithoutLength content_provider,
  13045. const std::string &content_type,
  13046. ContentReceiver content_receiver,
  13047. DownloadProgress progress) {
  13048. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13049. std::move(content_receiver), progress);
  13050. }
  13051. inline Result Client::Post(const std::string &path, const Params &params) {
  13052. return cli_->Post(path, params);
  13053. }
  13054. inline Result Client::Post(const std::string &path, const Headers &headers,
  13055. const Params &params) {
  13056. return cli_->Post(path, headers, params);
  13057. }
  13058. inline Result Client::Post(const std::string &path,
  13059. const UploadFormDataItems &items,
  13060. UploadProgress progress) {
  13061. return cli_->Post(path, items, progress);
  13062. }
  13063. inline Result Client::Post(const std::string &path, const Headers &headers,
  13064. const UploadFormDataItems &items,
  13065. UploadProgress progress) {
  13066. return cli_->Post(path, headers, items, progress);
  13067. }
  13068. inline Result Client::Post(const std::string &path, const Headers &headers,
  13069. const UploadFormDataItems &items,
  13070. const std::string &boundary,
  13071. UploadProgress progress) {
  13072. return cli_->Post(path, headers, items, boundary, progress);
  13073. }
  13074. inline Result Client::Post(const std::string &path, const Headers &headers,
  13075. const UploadFormDataItems &items,
  13076. const FormDataProviderItems &provider_items,
  13077. UploadProgress progress) {
  13078. return cli_->Post(path, headers, items, provider_items, progress);
  13079. }
  13080. inline Result Client::Post(const std::string &path, const Headers &headers,
  13081. const std::string &body,
  13082. const std::string &content_type,
  13083. ContentReceiver content_receiver,
  13084. DownloadProgress progress) {
  13085. return cli_->Post(path, headers, body, content_type,
  13086. std::move(content_receiver), progress);
  13087. }
  13088. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13089. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13090. return cli_->Put(path, headers);
  13091. }
  13092. inline Result Client::Put(const std::string &path, const char *body,
  13093. size_t content_length,
  13094. const std::string &content_type,
  13095. UploadProgress progress) {
  13096. return cli_->Put(path, body, content_length, content_type, progress);
  13097. }
  13098. inline Result Client::Put(const std::string &path, const Headers &headers,
  13099. const char *body, size_t content_length,
  13100. const std::string &content_type,
  13101. UploadProgress progress) {
  13102. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13103. }
  13104. inline Result Client::Put(const std::string &path, const std::string &body,
  13105. const std::string &content_type,
  13106. UploadProgress progress) {
  13107. return cli_->Put(path, body, content_type, progress);
  13108. }
  13109. inline Result Client::Put(const std::string &path, const Headers &headers,
  13110. const std::string &body,
  13111. const std::string &content_type,
  13112. UploadProgress progress) {
  13113. return cli_->Put(path, headers, body, content_type, progress);
  13114. }
  13115. inline Result Client::Put(const std::string &path, size_t content_length,
  13116. ContentProvider content_provider,
  13117. const std::string &content_type,
  13118. UploadProgress progress) {
  13119. return cli_->Put(path, content_length, std::move(content_provider),
  13120. content_type, progress);
  13121. }
  13122. inline Result Client::Put(const std::string &path, size_t content_length,
  13123. ContentProvider content_provider,
  13124. const std::string &content_type,
  13125. ContentReceiver content_receiver,
  13126. UploadProgress progress) {
  13127. return cli_->Put(path, content_length, std::move(content_provider),
  13128. content_type, std::move(content_receiver), progress);
  13129. }
  13130. inline Result Client::Put(const std::string &path,
  13131. ContentProviderWithoutLength content_provider,
  13132. const std::string &content_type,
  13133. UploadProgress progress) {
  13134. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13135. }
  13136. inline Result Client::Put(const std::string &path,
  13137. ContentProviderWithoutLength content_provider,
  13138. const std::string &content_type,
  13139. ContentReceiver content_receiver,
  13140. UploadProgress progress) {
  13141. return cli_->Put(path, std::move(content_provider), content_type,
  13142. std::move(content_receiver), progress);
  13143. }
  13144. inline Result Client::Put(const std::string &path, const Headers &headers,
  13145. size_t content_length,
  13146. ContentProvider content_provider,
  13147. const std::string &content_type,
  13148. UploadProgress progress) {
  13149. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13150. content_type, progress);
  13151. }
  13152. inline Result Client::Put(const std::string &path, const Headers &headers,
  13153. size_t content_length,
  13154. ContentProvider content_provider,
  13155. const std::string &content_type,
  13156. ContentReceiver content_receiver,
  13157. UploadProgress progress) {
  13158. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13159. content_type, std::move(content_receiver), progress);
  13160. }
  13161. inline Result Client::Put(const std::string &path, const Headers &headers,
  13162. ContentProviderWithoutLength content_provider,
  13163. const std::string &content_type,
  13164. UploadProgress progress) {
  13165. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13166. progress);
  13167. }
  13168. inline Result Client::Put(const std::string &path, const Headers &headers,
  13169. ContentProviderWithoutLength content_provider,
  13170. const std::string &content_type,
  13171. ContentReceiver content_receiver,
  13172. UploadProgress progress) {
  13173. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13174. std::move(content_receiver), progress);
  13175. }
  13176. inline Result Client::Put(const std::string &path, const Params &params) {
  13177. return cli_->Put(path, params);
  13178. }
  13179. inline Result Client::Put(const std::string &path, const Headers &headers,
  13180. const Params &params) {
  13181. return cli_->Put(path, headers, params);
  13182. }
  13183. inline Result Client::Put(const std::string &path,
  13184. const UploadFormDataItems &items,
  13185. UploadProgress progress) {
  13186. return cli_->Put(path, items, progress);
  13187. }
  13188. inline Result Client::Put(const std::string &path, const Headers &headers,
  13189. const UploadFormDataItems &items,
  13190. UploadProgress progress) {
  13191. return cli_->Put(path, headers, items, progress);
  13192. }
  13193. inline Result Client::Put(const std::string &path, const Headers &headers,
  13194. const UploadFormDataItems &items,
  13195. const std::string &boundary,
  13196. UploadProgress progress) {
  13197. return cli_->Put(path, headers, items, boundary, progress);
  13198. }
  13199. inline Result Client::Put(const std::string &path, const Headers &headers,
  13200. const UploadFormDataItems &items,
  13201. const FormDataProviderItems &provider_items,
  13202. UploadProgress progress) {
  13203. return cli_->Put(path, headers, items, provider_items, progress);
  13204. }
  13205. inline Result Client::Put(const std::string &path, const Headers &headers,
  13206. const std::string &body,
  13207. const std::string &content_type,
  13208. ContentReceiver content_receiver,
  13209. DownloadProgress progress) {
  13210. return cli_->Put(path, headers, body, content_type, content_receiver,
  13211. progress);
  13212. }
  13213. inline Result Client::Patch(const std::string &path) {
  13214. return cli_->Patch(path);
  13215. }
  13216. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13217. return cli_->Patch(path, headers);
  13218. }
  13219. inline Result Client::Patch(const std::string &path, const char *body,
  13220. size_t content_length,
  13221. const std::string &content_type,
  13222. UploadProgress progress) {
  13223. return cli_->Patch(path, body, content_length, content_type, progress);
  13224. }
  13225. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13226. const char *body, size_t content_length,
  13227. const std::string &content_type,
  13228. UploadProgress progress) {
  13229. return cli_->Patch(path, headers, body, content_length, content_type,
  13230. progress);
  13231. }
  13232. inline Result Client::Patch(const std::string &path, const std::string &body,
  13233. const std::string &content_type,
  13234. UploadProgress progress) {
  13235. return cli_->Patch(path, body, content_type, progress);
  13236. }
  13237. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13238. const std::string &body,
  13239. const std::string &content_type,
  13240. UploadProgress progress) {
  13241. return cli_->Patch(path, headers, body, content_type, progress);
  13242. }
  13243. inline Result Client::Patch(const std::string &path, size_t content_length,
  13244. ContentProvider content_provider,
  13245. const std::string &content_type,
  13246. UploadProgress progress) {
  13247. return cli_->Patch(path, content_length, std::move(content_provider),
  13248. content_type, progress);
  13249. }
  13250. inline Result Client::Patch(const std::string &path, size_t content_length,
  13251. ContentProvider content_provider,
  13252. const std::string &content_type,
  13253. ContentReceiver content_receiver,
  13254. UploadProgress progress) {
  13255. return cli_->Patch(path, content_length, std::move(content_provider),
  13256. content_type, std::move(content_receiver), progress);
  13257. }
  13258. inline Result Client::Patch(const std::string &path,
  13259. ContentProviderWithoutLength content_provider,
  13260. const std::string &content_type,
  13261. UploadProgress progress) {
  13262. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13263. }
  13264. inline Result Client::Patch(const std::string &path,
  13265. ContentProviderWithoutLength content_provider,
  13266. const std::string &content_type,
  13267. ContentReceiver content_receiver,
  13268. UploadProgress progress) {
  13269. return cli_->Patch(path, std::move(content_provider), content_type,
  13270. std::move(content_receiver), progress);
  13271. }
  13272. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13273. size_t content_length,
  13274. ContentProvider content_provider,
  13275. const std::string &content_type,
  13276. UploadProgress progress) {
  13277. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13278. content_type, progress);
  13279. }
  13280. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13281. size_t content_length,
  13282. ContentProvider content_provider,
  13283. const std::string &content_type,
  13284. ContentReceiver content_receiver,
  13285. UploadProgress progress) {
  13286. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13287. content_type, std::move(content_receiver), progress);
  13288. }
  13289. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13290. ContentProviderWithoutLength content_provider,
  13291. const std::string &content_type,
  13292. UploadProgress progress) {
  13293. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13294. progress);
  13295. }
  13296. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13297. ContentProviderWithoutLength content_provider,
  13298. const std::string &content_type,
  13299. ContentReceiver content_receiver,
  13300. UploadProgress progress) {
  13301. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13302. std::move(content_receiver), progress);
  13303. }
  13304. inline Result Client::Patch(const std::string &path, const Params &params) {
  13305. return cli_->Patch(path, params);
  13306. }
  13307. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13308. const Params &params) {
  13309. return cli_->Patch(path, headers, params);
  13310. }
  13311. inline Result Client::Patch(const std::string &path,
  13312. const UploadFormDataItems &items,
  13313. UploadProgress progress) {
  13314. return cli_->Patch(path, items, progress);
  13315. }
  13316. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13317. const UploadFormDataItems &items,
  13318. UploadProgress progress) {
  13319. return cli_->Patch(path, headers, items, progress);
  13320. }
  13321. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13322. const UploadFormDataItems &items,
  13323. const std::string &boundary,
  13324. UploadProgress progress) {
  13325. return cli_->Patch(path, headers, items, boundary, progress);
  13326. }
  13327. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13328. const UploadFormDataItems &items,
  13329. const FormDataProviderItems &provider_items,
  13330. UploadProgress progress) {
  13331. return cli_->Patch(path, headers, items, provider_items, progress);
  13332. }
  13333. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13334. const std::string &body,
  13335. const std::string &content_type,
  13336. ContentReceiver content_receiver,
  13337. DownloadProgress progress) {
  13338. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13339. progress);
  13340. }
  13341. inline Result Client::Delete(const std::string &path,
  13342. DownloadProgress progress) {
  13343. return cli_->Delete(path, progress);
  13344. }
  13345. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13346. DownloadProgress progress) {
  13347. return cli_->Delete(path, headers, progress);
  13348. }
  13349. inline Result Client::Delete(const std::string &path, const char *body,
  13350. size_t content_length,
  13351. const std::string &content_type,
  13352. DownloadProgress progress) {
  13353. return cli_->Delete(path, body, content_length, content_type, progress);
  13354. }
  13355. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13356. const char *body, size_t content_length,
  13357. const std::string &content_type,
  13358. DownloadProgress progress) {
  13359. return cli_->Delete(path, headers, body, content_length, content_type,
  13360. progress);
  13361. }
  13362. inline Result Client::Delete(const std::string &path, const std::string &body,
  13363. const std::string &content_type,
  13364. DownloadProgress progress) {
  13365. return cli_->Delete(path, body, content_type, progress);
  13366. }
  13367. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13368. const std::string &body,
  13369. const std::string &content_type,
  13370. DownloadProgress progress) {
  13371. return cli_->Delete(path, headers, body, content_type, progress);
  13372. }
  13373. inline Result Client::Delete(const std::string &path, const Params &params,
  13374. DownloadProgress progress) {
  13375. return cli_->Delete(path, params, progress);
  13376. }
  13377. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13378. const Params &params, DownloadProgress progress) {
  13379. return cli_->Delete(path, headers, params, progress);
  13380. }
  13381. inline Result Client::Options(const std::string &path) {
  13382. return cli_->Options(path);
  13383. }
  13384. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13385. return cli_->Options(path, headers);
  13386. }
  13387. inline ClientImpl::StreamHandle
  13388. Client::open_stream(const std::string &method, const std::string &path,
  13389. const Params &params, const Headers &headers,
  13390. const std::string &body, const std::string &content_type) {
  13391. return cli_->open_stream(method, path, params, headers, body, content_type);
  13392. }
  13393. inline bool Client::send(Request &req, Response &res, Error &error) {
  13394. return cli_->send(req, res, error);
  13395. }
  13396. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13397. inline void Client::stop() { cli_->stop(); }
  13398. inline std::string Client::host() const { return cli_->host(); }
  13399. inline int Client::port() const { return cli_->port(); }
  13400. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13401. inline socket_t Client::socket() const { return cli_->socket(); }
  13402. inline void
  13403. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13404. cli_->set_hostname_addr_map(std::move(addr_map));
  13405. }
  13406. inline void Client::set_default_headers(Headers headers) {
  13407. cli_->set_default_headers(std::move(headers));
  13408. }
  13409. inline void Client::set_header_writer(
  13410. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13411. cli_->set_header_writer(writer);
  13412. }
  13413. inline void Client::set_address_family(int family) {
  13414. cli_->set_address_family(family);
  13415. }
  13416. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13417. inline void Client::set_socket_options(SocketOptions socket_options) {
  13418. cli_->set_socket_options(std::move(socket_options));
  13419. }
  13420. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13421. cli_->set_connection_timeout(sec, usec);
  13422. }
  13423. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13424. cli_->set_read_timeout(sec, usec);
  13425. }
  13426. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13427. cli_->set_write_timeout(sec, usec);
  13428. }
  13429. inline void Client::set_basic_auth(const std::string &username,
  13430. const std::string &password) {
  13431. cli_->set_basic_auth(username, password);
  13432. }
  13433. inline void Client::set_bearer_token_auth(const std::string &token) {
  13434. cli_->set_bearer_token_auth(token);
  13435. }
  13436. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13437. inline void Client::set_follow_location(bool on) {
  13438. cli_->set_follow_location(on);
  13439. }
  13440. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13441. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13442. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13443. inline void Client::set_payload_max_length(size_t length) {
  13444. cli_->set_payload_max_length(length);
  13445. }
  13446. inline void Client::set_interface(const std::string &intf) {
  13447. cli_->set_interface(intf);
  13448. }
  13449. inline void Client::set_proxy(const std::string &host, int port) {
  13450. cli_->set_proxy(host, port);
  13451. }
  13452. inline void Client::set_proxy_basic_auth(const std::string &username,
  13453. const std::string &password) {
  13454. cli_->set_proxy_basic_auth(username, password);
  13455. }
  13456. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13457. cli_->set_proxy_bearer_token_auth(token);
  13458. }
  13459. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13460. cli_->set_no_proxy(patterns);
  13461. }
  13462. inline void Client::set_logger(Logger logger) {
  13463. cli_->set_logger(std::move(logger));
  13464. }
  13465. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13466. cli_->set_error_logger(std::move(error_logger));
  13467. }
  13468. /*
  13469. * Group 6: SSL Server and Client implementation
  13470. */
  13471. #ifdef CPPHTTPLIB_SSL_ENABLED
  13472. // SSL HTTP server implementation
  13473. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13474. const char *client_ca_cert_file_path,
  13475. const char *client_ca_cert_dir_path,
  13476. const char *private_key_password) {
  13477. using namespace tls;
  13478. ctx_ = create_server_context();
  13479. if (!ctx_) { return; }
  13480. // Load server certificate and private key
  13481. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13482. private_key_password)) {
  13483. last_ssl_error_ = static_cast<int>(get_error());
  13484. free_context(ctx_);
  13485. ctx_ = nullptr;
  13486. return;
  13487. }
  13488. // Load client CA certificates for client authentication
  13489. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13490. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13491. client_ca_cert_dir_path)) {
  13492. last_ssl_error_ = static_cast<int>(get_error());
  13493. free_context(ctx_);
  13494. ctx_ = nullptr;
  13495. return;
  13496. }
  13497. // Enable client certificate verification
  13498. set_verify_client(ctx_, true);
  13499. }
  13500. }
  13501. inline SSLServer::SSLServer(const PemMemory &pem) {
  13502. using namespace tls;
  13503. ctx_ = create_server_context();
  13504. if (ctx_) {
  13505. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13506. pem.private_key_password)) {
  13507. last_ssl_error_ = static_cast<int>(get_error());
  13508. free_context(ctx_);
  13509. ctx_ = nullptr;
  13510. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13511. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13512. last_ssl_error_ = static_cast<int>(get_error());
  13513. free_context(ctx_);
  13514. ctx_ = nullptr;
  13515. } else {
  13516. set_verify_client(ctx_, true);
  13517. }
  13518. }
  13519. }
  13520. }
  13521. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13522. using namespace tls;
  13523. ctx_ = create_server_context();
  13524. if (ctx_) {
  13525. if (!setup_callback(ctx_)) {
  13526. free_context(ctx_);
  13527. ctx_ = nullptr;
  13528. }
  13529. }
  13530. }
  13531. inline SSLServer::~SSLServer() {
  13532. if (ctx_) { tls::free_context(ctx_); }
  13533. }
  13534. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13535. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13536. using namespace tls;
  13537. // Create TLS session with mutex protection
  13538. session_t session = nullptr;
  13539. {
  13540. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13541. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13542. }
  13543. if (!session) {
  13544. last_ssl_error_ = static_cast<int>(get_error());
  13545. detail::shutdown_socket(sock);
  13546. detail::close_socket(sock);
  13547. return false;
  13548. }
  13549. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13550. bool handshake_done = false;
  13551. bool ret = false;
  13552. bool websocket_upgraded = false;
  13553. auto cleanup = detail::scope_exit([&] {
  13554. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13555. free_session(session);
  13556. detail::shutdown_socket(sock);
  13557. detail::close_socket(sock);
  13558. });
  13559. // Perform TLS accept handshake with timeout
  13560. TlsError tls_err;
  13561. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13562. &tls_err)) {
  13563. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13564. // Map TlsError to legacy ssl_error for backward compatibility
  13565. if (tls_err.code == ErrorCode::WantRead) {
  13566. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13567. } else if (tls_err.code == ErrorCode::WantWrite) {
  13568. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13569. } else {
  13570. last_ssl_error_ = SSL_ERROR_SSL;
  13571. }
  13572. #else
  13573. last_ssl_error_ = static_cast<int>(get_error());
  13574. #endif
  13575. return false;
  13576. }
  13577. handshake_done = true;
  13578. std::string remote_addr;
  13579. int remote_port = 0;
  13580. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13581. std::string local_addr;
  13582. int local_port = 0;
  13583. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13584. ret = detail::process_server_socket_ssl(
  13585. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13586. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13587. write_timeout_usec_,
  13588. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13589. return process_request(
  13590. strm, remote_addr, remote_port, local_addr, local_port,
  13591. close_connection, connection_closed,
  13592. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13593. });
  13594. return ret;
  13595. }
  13596. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13597. const char *key_pem,
  13598. const char *client_ca_pem,
  13599. const char *password) {
  13600. if (!ctx_) { return false; }
  13601. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13602. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13603. return false;
  13604. }
  13605. if (client_ca_pem) {
  13606. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13607. }
  13608. return true;
  13609. }
  13610. // SSL HTTP client implementation
  13611. inline SSLClient::~SSLClient() {
  13612. if (ctx_) { tls::free_context(ctx_); }
  13613. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13614. // base function rather than the derived function once we get to the
  13615. // base class destructor, and won't free the SSL (causing a leak).
  13616. shutdown_ssl_impl(socket_, true);
  13617. }
  13618. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13619. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13620. shutdown_ssl_impl(socket, shutdown_gracefully);
  13621. }
  13622. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13623. bool shutdown_gracefully) {
  13624. if (socket.sock == INVALID_SOCKET) {
  13625. assert(socket.ssl == nullptr);
  13626. return;
  13627. }
  13628. if (socket.ssl) {
  13629. tls::shutdown(socket.ssl, shutdown_gracefully);
  13630. {
  13631. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13632. tls::free_session(socket.ssl);
  13633. }
  13634. socket.ssl = nullptr;
  13635. }
  13636. assert(socket.ssl == nullptr);
  13637. }
  13638. inline bool SSLClient::process_socket(
  13639. const Socket &socket,
  13640. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13641. std::function<bool(Stream &strm)> callback) {
  13642. assert(socket.ssl);
  13643. return detail::process_client_socket_ssl(
  13644. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13645. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13646. std::move(callback));
  13647. }
  13648. inline bool SSLClient::is_ssl() const { return true; }
  13649. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13650. if (!is_valid()) {
  13651. error = Error::SSLConnection;
  13652. return false;
  13653. }
  13654. return ClientImpl::create_and_connect_socket(socket, error);
  13655. }
  13656. inline bool SSLClient::setup_proxy_connection(
  13657. Socket &socket,
  13658. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13659. Response &res, bool &success, Error &error) {
  13660. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13661. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13662. return false;
  13663. }
  13664. if (!initialize_ssl(socket, error)) {
  13665. success = false;
  13666. return false;
  13667. }
  13668. return true;
  13669. }
  13670. // Assumes that socket_mutex_ is locked and that there are no requests in
  13671. // flight
  13672. inline bool SSLClient::connect_with_proxy(
  13673. Socket &socket,
  13674. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13675. Response &res, bool &success, Error &error) {
  13676. success = true;
  13677. Response proxy_res;
  13678. if (!detail::process_client_socket(
  13679. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13680. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13681. start_time, [&](Stream &strm) {
  13682. Request req2;
  13683. req2.method = "CONNECT";
  13684. req2.path =
  13685. detail::make_host_and_port_string_always_port(host_, port_);
  13686. if (max_timeout_msec_ > 0) {
  13687. req2.start_time_ = std::chrono::steady_clock::now();
  13688. }
  13689. return process_request(strm, req2, proxy_res, false, error);
  13690. })) {
  13691. // Thread-safe to close everything because we are assuming there are no
  13692. // requests in flight
  13693. shutdown_ssl(socket, true);
  13694. shutdown_socket(socket);
  13695. close_socket(socket);
  13696. success = false;
  13697. return false;
  13698. }
  13699. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13700. if (!proxy_digest_auth_username_.empty() &&
  13701. !proxy_digest_auth_password_.empty()) {
  13702. std::map<std::string, std::string> auth;
  13703. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13704. // Close the current socket and create a new one for the authenticated
  13705. // request
  13706. shutdown_ssl(socket, true);
  13707. shutdown_socket(socket);
  13708. close_socket(socket);
  13709. // Create a new socket for the authenticated CONNECT request
  13710. if (!ensure_socket_connection(socket, error)) {
  13711. success = false;
  13712. output_error_log(error, nullptr);
  13713. return false;
  13714. }
  13715. proxy_res = Response();
  13716. if (!detail::process_client_socket(
  13717. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13718. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13719. start_time, [&](Stream &strm) {
  13720. Request req3;
  13721. req3.method = "CONNECT";
  13722. req3.path = detail::make_host_and_port_string_always_port(
  13723. host_, port_);
  13724. req3.headers.insert(detail::make_digest_authentication_header(
  13725. req3, auth, 1, detail::random_string(10),
  13726. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13727. true));
  13728. if (max_timeout_msec_ > 0) {
  13729. req3.start_time_ = std::chrono::steady_clock::now();
  13730. }
  13731. return process_request(strm, req3, proxy_res, false, error);
  13732. })) {
  13733. // Thread-safe to close everything because we are assuming there are
  13734. // no requests in flight
  13735. shutdown_ssl(socket, true);
  13736. shutdown_socket(socket);
  13737. close_socket(socket);
  13738. success = false;
  13739. return false;
  13740. }
  13741. }
  13742. }
  13743. }
  13744. // If status code is not 200, proxy request is failed.
  13745. // Set error to ProxyConnection and return proxy response
  13746. // as the response of the request
  13747. if (proxy_res.status != StatusCode::OK_200) {
  13748. error = Error::ProxyConnection;
  13749. output_error_log(error, nullptr);
  13750. res = std::move(proxy_res);
  13751. // Thread-safe to close everything because we are assuming there are
  13752. // no requests in flight
  13753. shutdown_ssl(socket, true);
  13754. shutdown_socket(socket);
  13755. close_socket(socket);
  13756. return false;
  13757. }
  13758. return true;
  13759. }
  13760. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13761. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13762. if (is_proxy_enabled_for_host(host_)) { return true; }
  13763. if (!initialize_ssl(socket, error)) {
  13764. shutdown_socket(socket);
  13765. close_socket(socket);
  13766. return false;
  13767. }
  13768. return true;
  13769. }
  13770. // SSL HTTP client implementation
  13771. inline SSLClient::SSLClient(const std::string &host)
  13772. : SSLClient(host, 443, std::string(), std::string()) {}
  13773. inline SSLClient::SSLClient(const std::string &host, int port)
  13774. : SSLClient(host, port, std::string(), std::string()) {}
  13775. inline void SSLClient::init_ctx() {
  13776. ctx_ = tls::create_client_context();
  13777. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13778. }
  13779. inline void SSLClient::reset_ctx_on_error() {
  13780. last_backend_error_ = tls::get_error();
  13781. tls::free_context(ctx_);
  13782. ctx_ = nullptr;
  13783. }
  13784. inline SSLClient::SSLClient(const std::string &host, int port,
  13785. const std::string &client_cert_path,
  13786. const std::string &client_key_path,
  13787. const std::string &private_key_password)
  13788. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13789. init_ctx();
  13790. if (!ctx_) { return; }
  13791. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13792. const char *password =
  13793. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13794. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13795. client_key_path.c_str(), password)) {
  13796. reset_ctx_on_error();
  13797. }
  13798. }
  13799. }
  13800. inline SSLClient::SSLClient(const std::string &host, int port,
  13801. const PemMemory &pem)
  13802. : ClientImpl(host, port) {
  13803. init_ctx();
  13804. if (!ctx_) { return; }
  13805. if (pem.cert_pem && pem.key_pem) {
  13806. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13807. pem.private_key_password)) {
  13808. reset_ctx_on_error();
  13809. }
  13810. }
  13811. }
  13812. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13813. if (ca_cert_store && ctx_) {
  13814. // set_ca_store takes ownership of ca_cert_store
  13815. tls::set_ca_store(ctx_, ca_cert_store);
  13816. ca_cert_store_set_ = true;
  13817. } else if (ca_cert_store) {
  13818. tls::free_ca_store(ca_cert_store);
  13819. }
  13820. }
  13821. inline void
  13822. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13823. if (!ctx_) { return; }
  13824. tls::set_verify_callback(ctx_, verifier);
  13825. }
  13826. inline void SSLClient::set_session_verifier(
  13827. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13828. session_verifier_ = std::move(verifier);
  13829. }
  13830. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13831. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13832. enable_windows_cert_verification_ = enabled;
  13833. }
  13834. #endif
  13835. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13836. std::size_t size) {
  13837. if (ctx_ && ca_cert && size > 0) {
  13838. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13839. tls::load_ca_pem(ctx_, ca_cert, size);
  13840. }
  13841. }
  13842. inline bool SSLClient::load_certs() {
  13843. auto ret = true;
  13844. std::call_once(initialize_cert_, [&]() {
  13845. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13846. ret = detail::load_client_ca_config(
  13847. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13848. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13849. last_backend_error_);
  13850. });
  13851. return ret;
  13852. }
  13853. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13854. using namespace tls;
  13855. // Load CA certificates if server verification is enabled
  13856. if (server_certificate_verification_) {
  13857. if (!load_certs()) {
  13858. error = Error::SSLLoadingCerts;
  13859. output_error_log(error, nullptr);
  13860. return false;
  13861. }
  13862. }
  13863. bool is_ip = detail::is_ip_address(host_);
  13864. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13865. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13866. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13867. // Chain verification happens during the handshake even for IP hosts; the
  13868. // certificate identity is verified post-handshake via verify_hostname().
  13869. set_verify_client(ctx_, server_certificate_verification_);
  13870. #endif
  13871. // Create TLS session
  13872. session_t session = nullptr;
  13873. {
  13874. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13875. session = create_session(ctx_, socket.sock);
  13876. }
  13877. if (!session) {
  13878. error = Error::SSLConnection;
  13879. last_backend_error_ = get_error();
  13880. return false;
  13881. }
  13882. // Use scope_exit to ensure session is freed on error paths
  13883. bool success = false;
  13884. auto session_guard = detail::scope_exit([&] {
  13885. if (!success) { free_session(session); }
  13886. });
  13887. // Set SNI extension (skip for IP addresses per RFC 6066).
  13888. // On MbedTLS, set_sni also enables hostname verification internally.
  13889. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13890. if (!is_ip) {
  13891. if (!set_sni(session, host_.c_str())) {
  13892. error = Error::SSLConnection;
  13893. last_backend_error_ = get_error();
  13894. return false;
  13895. }
  13896. }
  13897. // Perform non-blocking TLS handshake with timeout
  13898. TlsError tls_err;
  13899. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13900. connection_timeout_usec_, &tls_err)) {
  13901. last_ssl_error_ = static_cast<int>(tls_err.code);
  13902. last_backend_error_ = tls_err.backend_code;
  13903. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13904. error = Error::SSLServerVerification;
  13905. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13906. error = Error::SSLServerHostnameVerification;
  13907. } else {
  13908. error = Error::SSLConnection;
  13909. }
  13910. output_error_log(error, nullptr);
  13911. return false;
  13912. }
  13913. // Post-handshake session verifier callback
  13914. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13915. if (session_verifier_) { verification_status = session_verifier_(session); }
  13916. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13917. last_backend_error_ = get_error();
  13918. error = Error::SSLServerVerification;
  13919. output_error_log(error, nullptr);
  13920. return false;
  13921. }
  13922. // Default server certificate verification
  13923. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13924. server_certificate_verification_) {
  13925. verify_result_ = tls::get_verify_result(session);
  13926. if (verify_result_ != 0) {
  13927. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13928. error = Error::SSLServerVerification;
  13929. output_error_log(error, nullptr);
  13930. return false;
  13931. }
  13932. auto server_cert = get_peer_cert(session);
  13933. if (!server_cert) {
  13934. last_backend_error_ = get_error();
  13935. error = Error::SSLServerVerification;
  13936. output_error_log(error, nullptr);
  13937. return false;
  13938. }
  13939. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13940. // Hostname verification (post-handshake for all cases).
  13941. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13942. // On MbedTLS, set_sni already enabled hostname verification during
  13943. // handshake for non-IP hosts, but this check is still needed for IP
  13944. // addresses where SNI is not set.
  13945. if (server_hostname_verification_) {
  13946. if (!verify_hostname(server_cert, host_.c_str())) {
  13947. last_backend_error_ = hostname_mismatch_code();
  13948. error = Error::SSLServerHostnameVerification;
  13949. output_error_log(error, nullptr);
  13950. return false;
  13951. }
  13952. }
  13953. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13954. // Additional Windows Schannel verification.
  13955. // This provides real-time certificate validation with Windows Update
  13956. // integration, working with both OpenSSL and MbedTLS backends.
  13957. // Skip when a custom CA cert is specified, as the Windows certificate
  13958. // store would not know about user-provided CA certificates. Also skip
  13959. // when system CA trust is explicitly disabled.
  13960. if (enable_windows_cert_verification_ &&
  13961. system_ca_mode_ != SystemCAMode::Disabled &&
  13962. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  13963. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  13964. std::vector<unsigned char> der;
  13965. if (get_cert_der(server_cert, der)) {
  13966. uint64_t wincrypt_error = 0;
  13967. if (!detail::verify_cert_with_windows_schannel(
  13968. der, host_, server_hostname_verification_, wincrypt_error)) {
  13969. last_backend_error_ = wincrypt_error;
  13970. error = Error::SSLServerVerification;
  13971. output_error_log(error, nullptr);
  13972. return false;
  13973. }
  13974. }
  13975. }
  13976. #endif
  13977. }
  13978. success = true;
  13979. socket.ssl = session;
  13980. return true;
  13981. }
  13982. inline void Client::set_digest_auth(const std::string &username,
  13983. const std::string &password) {
  13984. cli_->set_digest_auth(username, password);
  13985. }
  13986. inline void Client::set_proxy_digest_auth(const std::string &username,
  13987. const std::string &password) {
  13988. cli_->set_proxy_digest_auth(username, password);
  13989. }
  13990. inline void Client::enable_server_certificate_verification(bool enabled) {
  13991. cli_->enable_server_certificate_verification(enabled);
  13992. }
  13993. inline void Client::enable_server_hostname_verification(bool enabled) {
  13994. cli_->enable_server_hostname_verification(enabled);
  13995. }
  13996. inline void Client::enable_system_ca(bool enabled) {
  13997. cli_->enable_system_ca(enabled);
  13998. }
  13999. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14000. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14001. if (is_ssl_) {
  14002. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14003. enabled);
  14004. }
  14005. }
  14006. #endif
  14007. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14008. const std::string &ca_cert_dir_path) {
  14009. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14010. }
  14011. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14012. if (is_ssl_) {
  14013. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14014. } else if (ca_cert_store) {
  14015. tls::free_ca_store(ca_cert_store);
  14016. }
  14017. }
  14018. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14019. if (is_ssl_) {
  14020. // Use the PEM-based path so the CA data is retained for redirect transfer
  14021. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14022. }
  14023. }
  14024. inline void
  14025. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14026. if (is_ssl_) {
  14027. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14028. std::move(verifier));
  14029. }
  14030. }
  14031. inline void Client::set_session_verifier(
  14032. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14033. if (is_ssl_) {
  14034. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14035. }
  14036. }
  14037. inline tls::ctx_t Client::tls_context() const {
  14038. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14039. return nullptr;
  14040. }
  14041. #endif // CPPHTTPLIB_SSL_ENABLED
  14042. /*
  14043. * Group 7: TLS abstraction layer - Common API
  14044. */
  14045. #ifdef CPPHTTPLIB_SSL_ENABLED
  14046. namespace tls {
  14047. // Helper for PeerCert construction
  14048. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14049. return PeerCert(get_peer_cert(session));
  14050. }
  14051. namespace impl {
  14052. inline VerifyCallback &get_verify_callback() {
  14053. static thread_local VerifyCallback callback;
  14054. return callback;
  14055. }
  14056. inline VerifyCallback &get_mbedtls_verify_callback() {
  14057. static thread_local VerifyCallback callback;
  14058. return callback;
  14059. }
  14060. // Check if a string is an IPv4 address
  14061. inline bool is_ipv4_address(const std::string &str) {
  14062. int dots = 0;
  14063. for (char c : str) {
  14064. if (c == '.') {
  14065. dots++;
  14066. } else if (!isdigit(static_cast<unsigned char>(c))) {
  14067. return false;
  14068. }
  14069. }
  14070. return dots == 3;
  14071. }
  14072. // Parse IPv4 address string to bytes
  14073. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14074. const char *p = str.c_str();
  14075. for (int i = 0; i < 4; i++) {
  14076. if (i > 0) {
  14077. if (*p != '.') { return false; }
  14078. p++;
  14079. }
  14080. int val = 0;
  14081. int digits = 0;
  14082. while (*p >= '0' && *p <= '9') {
  14083. val = val * 10 + (*p - '0');
  14084. if (val > 255) { return false; }
  14085. p++;
  14086. digits++;
  14087. }
  14088. if (digits == 0) { return false; }
  14089. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14090. if (digits > 1 && *(p - digits) == '0') { return false; }
  14091. out[i] = static_cast<unsigned char>(val);
  14092. }
  14093. return *p == '\0';
  14094. }
  14095. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14096. // `out` must have room for at least 16 bytes. Returns the address length
  14097. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14098. // literal. Used to match a host against iPAddress SANs the same way the
  14099. // OpenSSL backend does via X509_check_ip.
  14100. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14101. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14102. struct in6_addr addr6 = {};
  14103. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14104. memcpy(out, &addr6, 16);
  14105. return 16;
  14106. }
  14107. return 0;
  14108. }
  14109. #ifdef _WIN32
  14110. // Enumerate Windows system certificates and call callback with DER data
  14111. template <typename Callback>
  14112. inline bool enumerate_windows_system_certs(Callback cb) {
  14113. bool loaded = false;
  14114. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14115. for (auto store_name : store_names) {
  14116. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14117. if (hStore) {
  14118. PCCERT_CONTEXT pContext = nullptr;
  14119. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14120. nullptr) {
  14121. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14122. loaded = true;
  14123. }
  14124. }
  14125. CertCloseStore(hStore, 0);
  14126. }
  14127. }
  14128. return loaded;
  14129. }
  14130. #endif
  14131. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14132. // Enumerate macOS Keychain certificates and call callback with DER data
  14133. template <typename Callback>
  14134. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14135. bool loaded = false;
  14136. const SecTrustSettingsDomain domains[] = {
  14137. kSecTrustSettingsDomainSystem,
  14138. kSecTrustSettingsDomainAdmin,
  14139. kSecTrustSettingsDomainUser,
  14140. };
  14141. for (auto domain : domains) {
  14142. CFArrayRef certs = nullptr;
  14143. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14144. if (status != errSecSuccess || !certs) {
  14145. if (certs) CFRelease(certs);
  14146. continue;
  14147. }
  14148. CFIndex count = CFArrayGetCount(certs);
  14149. for (CFIndex i = 0; i < count; i++) {
  14150. SecCertificateRef cert =
  14151. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14152. CFDataRef data = SecCertificateCopyData(cert);
  14153. if (data) {
  14154. if (cb(CFDataGetBytePtr(data),
  14155. static_cast<size_t>(CFDataGetLength(data)))) {
  14156. loaded = true;
  14157. }
  14158. CFRelease(data);
  14159. }
  14160. }
  14161. CFRelease(certs);
  14162. }
  14163. return loaded;
  14164. }
  14165. #endif
  14166. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14167. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14168. // Common CA certificate file paths on Linux/Unix
  14169. inline const char **system_ca_paths() {
  14170. static const char *paths[] = {
  14171. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14172. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14173. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14174. "/etc/pki/tls/cacert.pem", // OpenELEC
  14175. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14176. nullptr};
  14177. return paths;
  14178. }
  14179. // Common CA certificate directory paths on Linux/Unix
  14180. inline const char **system_ca_dirs() {
  14181. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14182. "/etc/pki/tls/certs", // RHEL/CentOS
  14183. "/usr/share/ca-certificates", // Other
  14184. nullptr};
  14185. return dirs;
  14186. }
  14187. #endif
  14188. } // namespace impl
  14189. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14190. const char *ca_dir) {
  14191. if (!ctx) { return false; }
  14192. bool success = true;
  14193. if (ca_file && *ca_file) {
  14194. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14195. }
  14196. if (ca_dir && *ca_dir) {
  14197. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14198. }
  14199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14200. // Set CA list for client certificate request (CertificateRequest message)
  14201. if (ca_file && *ca_file) {
  14202. auto list = SSL_load_client_CA_file(ca_file);
  14203. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14204. }
  14205. #endif
  14206. return success;
  14207. }
  14208. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14209. const char *password) {
  14210. return set_client_cert_pem(ctx, cert, key, password);
  14211. }
  14212. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14213. const char *key_path, const char *password) {
  14214. return set_client_cert_file(ctx, cert_path, key_path, password);
  14215. }
  14216. // PeerCert implementation
  14217. inline PeerCert::PeerCert() = default;
  14218. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14219. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14220. other.cert_ = nullptr;
  14221. }
  14222. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14223. if (this != &other) {
  14224. if (cert_) { free_cert(cert_); }
  14225. cert_ = other.cert_;
  14226. other.cert_ = nullptr;
  14227. }
  14228. return *this;
  14229. }
  14230. inline PeerCert::~PeerCert() {
  14231. if (cert_) { free_cert(cert_); }
  14232. }
  14233. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14234. inline std::string PeerCert::subject_cn() const {
  14235. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14236. }
  14237. inline std::string PeerCert::issuer_name() const {
  14238. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14239. }
  14240. inline bool PeerCert::check_hostname(const char *hostname) const {
  14241. return cert_ ? verify_hostname(cert_, hostname) : false;
  14242. }
  14243. inline std::vector<SanEntry> PeerCert::sans() const {
  14244. std::vector<SanEntry> result;
  14245. if (cert_) { get_cert_sans(cert_, result); }
  14246. return result;
  14247. }
  14248. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14249. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14250. }
  14251. inline std::string PeerCert::serial() const {
  14252. return cert_ ? get_cert_serial(cert_) : std::string();
  14253. }
  14254. // VerifyContext method implementations
  14255. inline std::string VerifyContext::subject_cn() const {
  14256. return cert ? get_cert_subject_cn(cert) : std::string();
  14257. }
  14258. inline std::string VerifyContext::issuer_name() const {
  14259. return cert ? get_cert_issuer_name(cert) : std::string();
  14260. }
  14261. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14262. return cert ? verify_hostname(cert, hostname) : false;
  14263. }
  14264. inline std::vector<SanEntry> VerifyContext::sans() const {
  14265. std::vector<SanEntry> result;
  14266. if (cert) { get_cert_sans(cert, result); }
  14267. return result;
  14268. }
  14269. inline bool VerifyContext::validity(time_t &not_before,
  14270. time_t &not_after) const {
  14271. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14272. }
  14273. inline std::string VerifyContext::serial() const {
  14274. return cert ? get_cert_serial(cert) : std::string();
  14275. }
  14276. // TlsError static method implementation
  14277. inline std::string TlsError::verify_error_to_string(long error_code) {
  14278. return verify_error_string(error_code);
  14279. }
  14280. } // namespace tls
  14281. // Request::peer_cert() implementation
  14282. inline tls::PeerCert Request::peer_cert() const {
  14283. return tls::get_peer_cert_from_session(ssl);
  14284. }
  14285. // Request::sni() implementation
  14286. inline std::string Request::sni() const {
  14287. if (!ssl) { return std::string(); }
  14288. const char *s = tls::get_sni(ssl);
  14289. return s ? std::string(s) : std::string();
  14290. }
  14291. #endif // CPPHTTPLIB_SSL_ENABLED
  14292. /*
  14293. * Group 8: TLS abstraction layer - OpenSSL backend
  14294. */
  14295. /*
  14296. * OpenSSL Backend Implementation
  14297. */
  14298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14299. namespace tls {
  14300. namespace impl {
  14301. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14302. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14303. switch (ssl_error) {
  14304. case SSL_ERROR_NONE: return ErrorCode::Success;
  14305. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14306. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14307. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14308. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14309. case SSL_ERROR_SSL:
  14310. default: return ErrorCode::Fatal;
  14311. }
  14312. }
  14313. // Helper: Create client CA list from PEM string
  14314. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14315. // Caller takes ownership of returned list
  14316. inline STACK_OF(X509_NAME) *
  14317. create_client_ca_list_from_pem(const char *ca_pem) {
  14318. if (!ca_pem) { return nullptr; }
  14319. auto ca_list = sk_X509_NAME_new_null();
  14320. if (!ca_list) { return nullptr; }
  14321. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14322. if (!bio) {
  14323. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14324. return nullptr;
  14325. }
  14326. X509 *cert = nullptr;
  14327. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14328. nullptr) {
  14329. const X509_NAME *name = X509_get_subject_name(cert);
  14330. if (name) {
  14331. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14332. }
  14333. X509_free(cert);
  14334. }
  14335. BIO_free(bio);
  14336. return ca_list;
  14337. }
  14338. // OpenSSL verify callback wrapper
  14339. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14340. auto &callback = get_verify_callback();
  14341. if (!callback) { return preverify_ok; }
  14342. // Get SSL object from X509_STORE_CTX
  14343. auto ssl = static_cast<SSL *>(
  14344. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14345. if (!ssl) { return preverify_ok; }
  14346. // Get current certificate and depth
  14347. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14348. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14349. int error = X509_STORE_CTX_get_error(ctx);
  14350. // Build context
  14351. VerifyContext verify_ctx;
  14352. verify_ctx.session = static_cast<session_t>(ssl);
  14353. verify_ctx.cert = static_cast<cert_t>(cert);
  14354. verify_ctx.depth = depth;
  14355. verify_ctx.preverify_ok = (preverify_ok != 0);
  14356. verify_ctx.error_code = error;
  14357. verify_ctx.error_string =
  14358. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14359. return callback(verify_ctx) ? 1 : 0;
  14360. }
  14361. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14362. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14363. // that must be released with release_store_objects
  14364. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14365. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14366. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14367. #endif
  14368. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14369. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14370. return X509_STORE_get1_objects(store);
  14371. #else
  14372. return X509_STORE_get0_objects(store);
  14373. #endif
  14374. }
  14375. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14376. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14377. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14378. #else
  14379. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14380. #endif
  14381. }
  14382. } // namespace impl
  14383. inline ctx_t create_client_context() {
  14384. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14385. if (ctx) {
  14386. // Disable auto-retry to properly handle non-blocking I/O
  14387. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14388. // Set minimum TLS version
  14389. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14390. }
  14391. return static_cast<ctx_t>(ctx);
  14392. }
  14393. inline void free_context(ctx_t ctx) {
  14394. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14395. }
  14396. inline bool set_min_version(ctx_t ctx, Version version) {
  14397. if (!ctx) return false;
  14398. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14399. static_cast<int>(version)) == 1;
  14400. }
  14401. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14402. if (!ctx || !pem || len == 0) return false;
  14403. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14404. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14405. if (!store) return false;
  14406. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14407. if (!bio) return false;
  14408. bool ok = true;
  14409. X509 *cert = nullptr;
  14410. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14411. nullptr) {
  14412. if (X509_STORE_add_cert(store, cert) != 1) {
  14413. // Ignore duplicate errors
  14414. auto err = ERR_peek_last_error();
  14415. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14416. ok = false;
  14417. }
  14418. }
  14419. X509_free(cert);
  14420. if (!ok) break;
  14421. }
  14422. BIO_free(bio);
  14423. // Clear any "no more certificates" errors
  14424. ERR_clear_error();
  14425. return ok;
  14426. }
  14427. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14428. if (!ctx || !file_path) return false;
  14429. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14430. nullptr) == 1;
  14431. }
  14432. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14433. if (!ctx || !dir_path) return false;
  14434. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14435. dir_path) == 1;
  14436. }
  14437. inline bool load_system_certs(ctx_t ctx) {
  14438. if (!ctx) return false;
  14439. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14440. #ifdef _WIN32
  14441. // Windows: Load from system certificate store (ROOT and CA)
  14442. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14443. if (!store) return false;
  14444. bool loaded_any = false;
  14445. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14446. for (auto store_name : store_names) {
  14447. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14448. if (!hStore) continue;
  14449. PCCERT_CONTEXT pContext = nullptr;
  14450. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14451. nullptr) {
  14452. const unsigned char *data = pContext->pbCertEncoded;
  14453. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14454. if (x509) {
  14455. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14456. X509_free(x509);
  14457. }
  14458. }
  14459. CertCloseStore(hStore, 0);
  14460. }
  14461. return loaded_any;
  14462. #elif defined(__APPLE__)
  14463. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14464. // macOS: Load from Keychain
  14465. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14466. if (!store) return false;
  14467. bool loaded_any = false;
  14468. const SecTrustSettingsDomain domains[] = {
  14469. kSecTrustSettingsDomainSystem,
  14470. kSecTrustSettingsDomainAdmin,
  14471. kSecTrustSettingsDomainUser,
  14472. };
  14473. for (auto domain : domains) {
  14474. CFArrayRef certs = nullptr;
  14475. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14476. !certs) {
  14477. if (certs) CFRelease(certs);
  14478. continue;
  14479. }
  14480. auto count = CFArrayGetCount(certs);
  14481. for (CFIndex i = 0; i < count; i++) {
  14482. auto cert = reinterpret_cast<SecCertificateRef>(
  14483. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14484. CFDataRef der = SecCertificateCopyData(cert);
  14485. if (der) {
  14486. const unsigned char *data = CFDataGetBytePtr(der);
  14487. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14488. if (x509) {
  14489. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14490. X509_free(x509);
  14491. }
  14492. CFRelease(der);
  14493. }
  14494. }
  14495. CFRelease(certs);
  14496. }
  14497. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14498. #else
  14499. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14500. #endif
  14501. #else
  14502. // Other Unix: use default verify paths
  14503. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14504. #endif
  14505. }
  14506. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14507. const char *password) {
  14508. if (!ctx || !cert || !key) return false;
  14509. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14510. // Load certificate
  14511. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14512. if (!cert_bio) return false;
  14513. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14514. BIO_free(cert_bio);
  14515. if (!x509) return false;
  14516. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14517. X509_free(x509);
  14518. if (!cert_ok) return false;
  14519. // Load private key
  14520. auto key_bio = BIO_new_mem_buf(key, -1);
  14521. if (!key_bio) return false;
  14522. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14523. password ? const_cast<char *>(password)
  14524. : nullptr);
  14525. BIO_free(key_bio);
  14526. if (!pkey) return false;
  14527. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14528. EVP_PKEY_free(pkey);
  14529. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14530. }
  14531. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14532. const char *key_path, const char *password) {
  14533. if (!ctx || !cert_path || !key_path) return false;
  14534. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14535. if (password && password[0] != '\0') {
  14536. SSL_CTX_set_default_passwd_cb_userdata(
  14537. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14538. }
  14539. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14540. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14541. }
  14542. inline ctx_t create_server_context() {
  14543. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14544. if (ctx) {
  14545. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14546. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14547. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14548. }
  14549. return static_cast<ctx_t>(ctx);
  14550. }
  14551. inline void set_verify_client(ctx_t ctx, bool require) {
  14552. if (!ctx) return;
  14553. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14554. require
  14555. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14556. : SSL_VERIFY_NONE,
  14557. nullptr);
  14558. }
  14559. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14560. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14561. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14562. SSL *ssl = SSL_new(ssl_ctx);
  14563. if (!ssl) return nullptr;
  14564. // Disable auto-retry for proper non-blocking I/O handling
  14565. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14566. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14567. if (!bio) {
  14568. SSL_free(ssl);
  14569. return nullptr;
  14570. }
  14571. SSL_set_bio(ssl, bio, bio);
  14572. return static_cast<session_t>(ssl);
  14573. }
  14574. inline void free_session(session_t session) {
  14575. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14576. }
  14577. inline bool set_sni(session_t session, const char *hostname) {
  14578. if (!session || !hostname) return false;
  14579. auto ssl = static_cast<SSL *>(session);
  14580. // Set SNI (Server Name Indication) only - does not enable verification
  14581. #if defined(OPENSSL_IS_BORINGSSL)
  14582. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14583. #else
  14584. // Direct call instead of macro to suppress -Wold-style-cast warning
  14585. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14586. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14587. #endif
  14588. }
  14589. inline bool set_hostname(session_t session, const char *hostname) {
  14590. if (!session || !hostname) return false;
  14591. auto ssl = static_cast<SSL *>(session);
  14592. // Enable hostname verification
  14593. auto param = SSL_get0_param(ssl);
  14594. if (!param) return false;
  14595. if (detail::is_ip_address(hostname)) {
  14596. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14597. // certificate's IP SANs instead of its DNS names
  14598. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14599. } else {
  14600. // Set SNI (Server Name Indication)
  14601. if (!set_sni(session, hostname)) { return false; }
  14602. X509_VERIFY_PARAM_set_hostflags(param,
  14603. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14604. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14605. }
  14606. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14607. return true;
  14608. }
  14609. inline TlsError connect(session_t session) {
  14610. if (!session) { return TlsError(); }
  14611. auto ssl = static_cast<SSL *>(session);
  14612. auto ret = SSL_connect(ssl);
  14613. TlsError err;
  14614. if (ret == 1) {
  14615. err.code = ErrorCode::Success;
  14616. } else {
  14617. auto ssl_err = SSL_get_error(ssl, ret);
  14618. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14619. err.backend_code = ERR_get_error();
  14620. }
  14621. return err;
  14622. }
  14623. inline TlsError accept(session_t session) {
  14624. if (!session) { return TlsError(); }
  14625. auto ssl = static_cast<SSL *>(session);
  14626. auto ret = SSL_accept(ssl);
  14627. TlsError err;
  14628. if (ret == 1) {
  14629. err.code = ErrorCode::Success;
  14630. } else {
  14631. auto ssl_err = SSL_get_error(ssl, ret);
  14632. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14633. err.backend_code = ERR_get_error();
  14634. }
  14635. return err;
  14636. }
  14637. inline bool connect_nonblocking(session_t session, socket_t sock,
  14638. time_t timeout_sec, time_t timeout_usec,
  14639. TlsError *err) {
  14640. if (!session) {
  14641. if (err) { err->code = ErrorCode::Fatal; }
  14642. return false;
  14643. }
  14644. auto ssl = static_cast<SSL *>(session);
  14645. auto bio = SSL_get_rbio(ssl);
  14646. // Set non-blocking mode for handshake
  14647. detail::set_nonblocking(sock, true);
  14648. if (bio) { BIO_set_nbio(bio, 1); }
  14649. auto cleanup = detail::scope_exit([&]() {
  14650. // Restore blocking mode after handshake
  14651. if (bio) { BIO_set_nbio(bio, 0); }
  14652. detail::set_nonblocking(sock, false);
  14653. });
  14654. auto res = 0;
  14655. while ((res = SSL_connect(ssl)) != 1) {
  14656. auto ssl_err = SSL_get_error(ssl, res);
  14657. switch (ssl_err) {
  14658. case SSL_ERROR_WANT_READ:
  14659. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14660. continue;
  14661. }
  14662. break;
  14663. case SSL_ERROR_WANT_WRITE:
  14664. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14665. continue;
  14666. }
  14667. break;
  14668. default: break;
  14669. }
  14670. if (err) {
  14671. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14672. err->backend_code = ERR_get_error();
  14673. }
  14674. return false;
  14675. }
  14676. if (err) { err->code = ErrorCode::Success; }
  14677. return true;
  14678. }
  14679. inline bool accept_nonblocking(session_t session, socket_t sock,
  14680. time_t timeout_sec, time_t timeout_usec,
  14681. TlsError *err) {
  14682. if (!session) {
  14683. if (err) { err->code = ErrorCode::Fatal; }
  14684. return false;
  14685. }
  14686. auto ssl = static_cast<SSL *>(session);
  14687. auto bio = SSL_get_rbio(ssl);
  14688. // Set non-blocking mode for handshake
  14689. detail::set_nonblocking(sock, true);
  14690. if (bio) { BIO_set_nbio(bio, 1); }
  14691. auto cleanup = detail::scope_exit([&]() {
  14692. // Restore blocking mode after handshake
  14693. if (bio) { BIO_set_nbio(bio, 0); }
  14694. detail::set_nonblocking(sock, false);
  14695. });
  14696. auto res = 0;
  14697. while ((res = SSL_accept(ssl)) != 1) {
  14698. auto ssl_err = SSL_get_error(ssl, res);
  14699. switch (ssl_err) {
  14700. case SSL_ERROR_WANT_READ:
  14701. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14702. continue;
  14703. }
  14704. break;
  14705. case SSL_ERROR_WANT_WRITE:
  14706. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14707. continue;
  14708. }
  14709. break;
  14710. default: break;
  14711. }
  14712. if (err) {
  14713. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14714. err->backend_code = ERR_get_error();
  14715. }
  14716. return false;
  14717. }
  14718. if (err) { err->code = ErrorCode::Success; }
  14719. return true;
  14720. }
  14721. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14722. if (!session || !buf) {
  14723. err.code = ErrorCode::Fatal;
  14724. return -1;
  14725. }
  14726. auto ssl = static_cast<SSL *>(session);
  14727. constexpr auto max_len =
  14728. static_cast<size_t>((std::numeric_limits<int>::max)());
  14729. if (len > max_len) { len = max_len; }
  14730. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14731. if (ret > 0) {
  14732. err.code = ErrorCode::Success;
  14733. return ret;
  14734. }
  14735. auto ssl_err = SSL_get_error(ssl, ret);
  14736. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14737. if (err.code == ErrorCode::PeerClosed) {
  14738. return 0;
  14739. } // Gracefully handle the peer closed state.
  14740. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14741. return -1;
  14742. }
  14743. inline ssize_t write(session_t session, const void *buf, size_t len,
  14744. TlsError &err) {
  14745. if (!session || !buf) {
  14746. err.code = ErrorCode::Fatal;
  14747. return -1;
  14748. }
  14749. auto ssl = static_cast<SSL *>(session);
  14750. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14751. if (ret > 0) {
  14752. err.code = ErrorCode::Success;
  14753. return ret;
  14754. }
  14755. auto ssl_err = SSL_get_error(ssl, ret);
  14756. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14757. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14758. return -1;
  14759. }
  14760. inline int pending(const_session_t session) {
  14761. if (!session) return 0;
  14762. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14763. }
  14764. inline void shutdown(session_t session, bool graceful) {
  14765. if (!session) return;
  14766. auto ssl = static_cast<SSL *>(session);
  14767. if (graceful) {
  14768. // First call sends close_notify
  14769. if (SSL_shutdown(ssl) == 0) {
  14770. // Second call waits for peer's close_notify
  14771. SSL_shutdown(ssl);
  14772. }
  14773. }
  14774. }
  14775. inline bool is_peer_closed(session_t session, socket_t sock) {
  14776. if (!session) return true;
  14777. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14778. detail::set_nonblocking(sock, true);
  14779. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14780. auto ssl = static_cast<SSL *>(session);
  14781. char buf;
  14782. auto ret = SSL_peek(ssl, &buf, 1);
  14783. if (ret > 0) return false;
  14784. auto err = SSL_get_error(ssl, ret);
  14785. return err == SSL_ERROR_ZERO_RETURN;
  14786. }
  14787. inline cert_t get_peer_cert(const_session_t session) {
  14788. if (!session) return nullptr;
  14789. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14790. static_cast<SSL *>(const_cast<void *>(session))));
  14791. }
  14792. inline void free_cert(cert_t cert) {
  14793. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14794. }
  14795. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14796. if (!cert || !hostname) return false;
  14797. auto x509 = static_cast<X509 *>(cert);
  14798. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14799. if (detail::is_ip_address(hostname)) {
  14800. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14801. }
  14802. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14803. }
  14804. inline uint64_t hostname_mismatch_code() {
  14805. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14806. }
  14807. inline long get_verify_result(const_session_t session) {
  14808. if (!session) return X509_V_ERR_UNSPECIFIED;
  14809. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14810. }
  14811. inline std::string get_cert_subject_cn(cert_t cert) {
  14812. if (!cert) return "";
  14813. auto x509 = static_cast<X509 *>(cert);
  14814. auto subject_name = X509_get_subject_name(x509);
  14815. if (!subject_name) return "";
  14816. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14817. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14818. if (idx < 0) return "";
  14819. auto entry = X509_NAME_get_entry(subject_name, idx);
  14820. if (!entry) return "";
  14821. auto data = X509_NAME_ENTRY_get_data(entry);
  14822. if (!data) return "";
  14823. return std::string(
  14824. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14825. static_cast<size_t>(ASN1_STRING_length(data)));
  14826. }
  14827. inline std::string get_cert_issuer_name(cert_t cert) {
  14828. if (!cert) return "";
  14829. auto x509 = static_cast<X509 *>(cert);
  14830. auto issuer_name = X509_get_issuer_name(x509);
  14831. if (!issuer_name) return "";
  14832. char buf[256];
  14833. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14834. return std::string(buf);
  14835. }
  14836. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14837. sans.clear();
  14838. if (!cert) return false;
  14839. auto x509 = static_cast<X509 *>(cert);
  14840. auto names = static_cast<GENERAL_NAMES *>(
  14841. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14842. if (!names) return true; // No SANs is valid
  14843. auto count = sk_GENERAL_NAME_num(names);
  14844. for (decltype(count) i = 0; i < count; i++) {
  14845. auto gen = sk_GENERAL_NAME_value(names, i);
  14846. if (!gen) continue;
  14847. SanEntry entry;
  14848. switch (gen->type) {
  14849. case GEN_DNS:
  14850. entry.type = SanType::DNS;
  14851. if (gen->d.dNSName) {
  14852. entry.value = std::string(
  14853. reinterpret_cast<const char *>(
  14854. ASN1_STRING_get0_data(gen->d.dNSName)),
  14855. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14856. }
  14857. break;
  14858. case GEN_IPADD:
  14859. entry.type = SanType::IP;
  14860. if (gen->d.iPAddress) {
  14861. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14862. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14863. if (len == 4) {
  14864. // IPv4
  14865. char buf[INET_ADDRSTRLEN];
  14866. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14867. entry.value = buf;
  14868. } else if (len == 16) {
  14869. // IPv6
  14870. char buf[INET6_ADDRSTRLEN];
  14871. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14872. entry.value = buf;
  14873. }
  14874. }
  14875. break;
  14876. case GEN_EMAIL:
  14877. entry.type = SanType::EMAIL;
  14878. if (gen->d.rfc822Name) {
  14879. entry.value = std::string(
  14880. reinterpret_cast<const char *>(
  14881. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14882. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14883. }
  14884. break;
  14885. case GEN_URI:
  14886. entry.type = SanType::URI;
  14887. if (gen->d.uniformResourceIdentifier) {
  14888. entry.value = std::string(
  14889. reinterpret_cast<const char *>(
  14890. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14891. static_cast<size_t>(
  14892. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14893. }
  14894. break;
  14895. default: entry.type = SanType::OTHER; break;
  14896. }
  14897. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14898. }
  14899. GENERAL_NAMES_free(names);
  14900. return true;
  14901. }
  14902. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14903. time_t &not_after) {
  14904. if (!cert) return false;
  14905. auto x509 = static_cast<X509 *>(cert);
  14906. auto nb = X509_get0_notBefore(x509);
  14907. auto na = X509_get0_notAfter(x509);
  14908. if (!nb || !na) return false;
  14909. ASN1_TIME *epoch = ASN1_TIME_new();
  14910. if (!epoch) return false;
  14911. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14912. if (!ASN1_TIME_set(epoch, 0)) return false;
  14913. int pday, psec;
  14914. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14915. not_before = 86400 * (time_t)pday + psec;
  14916. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14917. not_after = 86400 * (time_t)pday + psec;
  14918. return true;
  14919. }
  14920. inline std::string get_cert_serial(cert_t cert) {
  14921. if (!cert) return "";
  14922. auto x509 = static_cast<X509 *>(cert);
  14923. auto serial = X509_get_serialNumber(x509);
  14924. if (!serial) return "";
  14925. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14926. if (!bn) return "";
  14927. auto hex = BN_bn2hex(bn);
  14928. BN_free(bn);
  14929. if (!hex) return "";
  14930. std::string result(hex);
  14931. OPENSSL_free(hex);
  14932. return result;
  14933. }
  14934. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14935. if (!cert) return false;
  14936. auto x509 = static_cast<X509 *>(cert);
  14937. auto len = i2d_X509(x509, nullptr);
  14938. if (len < 0) return false;
  14939. der.resize(static_cast<size_t>(len));
  14940. auto p = der.data();
  14941. i2d_X509(x509, &p);
  14942. return true;
  14943. }
  14944. inline const char *get_sni(const_session_t session) {
  14945. if (!session) return nullptr;
  14946. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14947. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14948. }
  14949. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14950. inline uint64_t get_error() { return ERR_get_error(); }
  14951. inline std::string error_string(uint64_t code) {
  14952. char buf[256];
  14953. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14954. return std::string(buf);
  14955. }
  14956. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14957. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14958. if (!mem) { return nullptr; }
  14959. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14960. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14961. if (!inf) { return nullptr; }
  14962. auto store = X509_STORE_new();
  14963. if (store) {
  14964. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14965. auto itmp = sk_X509_INFO_value(inf, i);
  14966. if (!itmp) { continue; }
  14967. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14968. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14969. }
  14970. }
  14971. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14972. return static_cast<ca_store_t>(store);
  14973. }
  14974. inline void free_ca_store(ca_store_t store) {
  14975. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  14976. }
  14977. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14978. if (!ctx || !store) { return false; }
  14979. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14980. auto x509_store = static_cast<X509_STORE *>(store);
  14981. // Check if same store is already set
  14982. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  14983. // SSL_CTX_set_cert_store takes ownership and frees the old store
  14984. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  14985. return true;
  14986. }
  14987. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14988. certs.clear();
  14989. if (!ctx) { return 0; }
  14990. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14991. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14992. if (!store) { return 0; }
  14993. auto objs = impl::get_store_objects(store);
  14994. if (!objs) { return 0; }
  14995. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  14996. auto count = sk_X509_OBJECT_num(objs);
  14997. for (decltype(count) i = 0; i < count; i++) {
  14998. auto obj = sk_X509_OBJECT_value(objs, i);
  14999. if (!obj) { continue; }
  15000. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15001. auto x509 = X509_OBJECT_get0_X509(obj);
  15002. if (x509) {
  15003. // Increment reference count so caller can free it
  15004. X509_up_ref(x509);
  15005. certs.push_back(static_cast<cert_t>(x509));
  15006. }
  15007. }
  15008. }
  15009. return certs.size();
  15010. }
  15011. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15012. std::vector<std::string> names;
  15013. if (!ctx) { return names; }
  15014. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15015. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15016. if (!store) { return names; }
  15017. auto objs = impl::get_store_objects(store);
  15018. if (!objs) { return names; }
  15019. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15020. auto count = sk_X509_OBJECT_num(objs);
  15021. for (decltype(count) i = 0; i < count; i++) {
  15022. auto obj = sk_X509_OBJECT_value(objs, i);
  15023. if (!obj) { continue; }
  15024. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15025. auto x509 = X509_OBJECT_get0_X509(obj);
  15026. if (x509) {
  15027. auto subject = X509_get_subject_name(x509);
  15028. if (subject) {
  15029. char buf[512];
  15030. X509_NAME_oneline(subject, buf, sizeof(buf));
  15031. names.push_back(buf);
  15032. }
  15033. }
  15034. }
  15035. }
  15036. return names;
  15037. }
  15038. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15039. const char *key_pem, const char *password) {
  15040. if (!ctx || !cert_pem || !key_pem) { return false; }
  15041. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15042. // Load certificate from PEM
  15043. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15044. if (!cert_bio) { return false; }
  15045. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15046. BIO_free(cert_bio);
  15047. if (!cert) { return false; }
  15048. // Load private key from PEM
  15049. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15050. if (!key_bio) {
  15051. X509_free(cert);
  15052. return false;
  15053. }
  15054. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15055. password ? const_cast<char *>(password)
  15056. : nullptr);
  15057. BIO_free(key_bio);
  15058. if (!key) {
  15059. X509_free(cert);
  15060. return false;
  15061. }
  15062. // Update certificate and key
  15063. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15064. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15065. X509_free(cert);
  15066. EVP_PKEY_free(key);
  15067. return ret;
  15068. }
  15069. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15070. if (!ctx || !ca_pem) { return false; }
  15071. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15072. // Create new X509_STORE from PEM
  15073. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15074. if (!store) { return false; }
  15075. // SSL_CTX_set_cert_store takes ownership
  15076. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15077. // Set client CA list for client certificate request
  15078. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15079. if (ca_list) {
  15080. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15081. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15082. }
  15083. return true;
  15084. }
  15085. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15086. if (!ctx) { return false; }
  15087. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15088. impl::get_verify_callback() = std::move(callback);
  15089. if (impl::get_verify_callback()) {
  15090. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15091. } else {
  15092. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15093. }
  15094. return true;
  15095. }
  15096. inline long get_verify_error(const_session_t session) {
  15097. if (!session) { return -1; }
  15098. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15099. return SSL_get_verify_result(ssl);
  15100. }
  15101. inline std::string verify_error_string(long error_code) {
  15102. if (error_code == X509_V_OK) { return ""; }
  15103. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15104. return str ? str : "unknown error";
  15105. }
  15106. } // namespace tls
  15107. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15108. /*
  15109. * Group 9: TLS abstraction layer - Mbed TLS backend
  15110. */
  15111. /*
  15112. * Mbed TLS Backend Implementation
  15113. */
  15114. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15115. namespace tls {
  15116. namespace impl {
  15117. // Mbed TLS session wrapper
  15118. struct MbedTlsSession {
  15119. mbedtls_ssl_context ssl;
  15120. socket_t sock = INVALID_SOCKET;
  15121. std::string hostname; // For client: set via set_sni
  15122. std::string sni_hostname; // For server: received from client via SNI callback
  15123. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15124. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15125. MbedTlsSession(const MbedTlsSession &) = delete;
  15126. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15127. };
  15128. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15129. // queue)
  15130. inline int &mbedtls_last_error() {
  15131. static thread_local int err = 0;
  15132. return err;
  15133. }
  15134. // Helper to map Mbed TLS error to ErrorCode
  15135. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15136. if (ret == 0) { return ErrorCode::Success; }
  15137. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15138. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15139. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15140. return ErrorCode::PeerClosed;
  15141. }
  15142. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15143. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15144. out_errno = errno;
  15145. return ErrorCode::SyscallError;
  15146. }
  15147. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15148. return ErrorCode::CertVerifyFailed;
  15149. }
  15150. return ErrorCode::Fatal;
  15151. }
  15152. // BIO-like send callback for Mbed TLS
  15153. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15154. size_t len) {
  15155. auto sock = *static_cast<socket_t *>(ctx);
  15156. #ifdef _WIN32
  15157. auto ret =
  15158. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15159. if (ret == SOCKET_ERROR) {
  15160. int err = WSAGetLastError();
  15161. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15162. return MBEDTLS_ERR_NET_SEND_FAILED;
  15163. }
  15164. #else
  15165. auto ret = send(sock, buf, len, 0);
  15166. if (ret < 0) {
  15167. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15168. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15169. }
  15170. return MBEDTLS_ERR_NET_SEND_FAILED;
  15171. }
  15172. #endif
  15173. return static_cast<int>(ret);
  15174. }
  15175. // BIO-like recv callback for Mbed TLS
  15176. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15177. auto sock = *static_cast<socket_t *>(ctx);
  15178. #ifdef _WIN32
  15179. auto ret =
  15180. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15181. if (ret == SOCKET_ERROR) {
  15182. int err = WSAGetLastError();
  15183. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15184. return MBEDTLS_ERR_NET_RECV_FAILED;
  15185. }
  15186. #else
  15187. auto ret = recv(sock, buf, len, 0);
  15188. if (ret < 0) {
  15189. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15190. return MBEDTLS_ERR_SSL_WANT_READ;
  15191. }
  15192. return MBEDTLS_ERR_NET_RECV_FAILED;
  15193. }
  15194. #endif
  15195. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15196. return static_cast<int>(ret);
  15197. }
  15198. // MbedTlsContext constructor/destructor implementations
  15199. inline MbedTlsContext::MbedTlsContext() {
  15200. mbedtls_ssl_config_init(&conf);
  15201. mbedtls_entropy_init(&entropy);
  15202. mbedtls_ctr_drbg_init(&ctr_drbg);
  15203. mbedtls_x509_crt_init(&ca_chain);
  15204. mbedtls_x509_crt_init(&own_cert);
  15205. mbedtls_pk_init(&own_key);
  15206. }
  15207. inline MbedTlsContext::~MbedTlsContext() {
  15208. mbedtls_pk_free(&own_key);
  15209. mbedtls_x509_crt_free(&own_cert);
  15210. mbedtls_x509_crt_free(&ca_chain);
  15211. mbedtls_ctr_drbg_free(&ctr_drbg);
  15212. mbedtls_entropy_free(&entropy);
  15213. mbedtls_ssl_config_free(&conf);
  15214. }
  15215. // Thread-local storage for SNI captured during handshake
  15216. // This is needed because the SNI callback doesn't have a way to pass
  15217. // session-specific data before the session is fully set up
  15218. inline std::string &mbedpending_sni() {
  15219. static thread_local std::string sni;
  15220. return sni;
  15221. }
  15222. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15223. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15224. const unsigned char *name, size_t name_len) {
  15225. (void)p_ctx;
  15226. (void)ssl;
  15227. // Store SNI name in thread-local storage
  15228. // It will be retrieved and stored in the session after handshake
  15229. if (name && name_len > 0) {
  15230. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15231. } else {
  15232. mbedpending_sni().clear();
  15233. }
  15234. return 0; // Accept any SNI
  15235. }
  15236. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15237. int cert_depth, uint32_t *flags);
  15238. // MbedTLS verify callback wrapper
  15239. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15240. int cert_depth, uint32_t *flags) {
  15241. auto &callback = get_verify_callback();
  15242. if (!callback) { return 0; } // Continue with default verification
  15243. // data points to the MbedTlsSession
  15244. auto *session = static_cast<MbedTlsSession *>(data);
  15245. // Build context
  15246. VerifyContext verify_ctx;
  15247. verify_ctx.session = static_cast<session_t>(session);
  15248. verify_ctx.cert = static_cast<cert_t>(crt);
  15249. verify_ctx.depth = cert_depth;
  15250. verify_ctx.preverify_ok = (*flags == 0);
  15251. verify_ctx.error_code = static_cast<long>(*flags);
  15252. // Convert Mbed TLS flags to error string
  15253. static thread_local char error_buf[256];
  15254. if (*flags != 0) {
  15255. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15256. verify_ctx.error_string = error_buf;
  15257. } else {
  15258. verify_ctx.error_string = nullptr;
  15259. }
  15260. bool accepted = callback(verify_ctx);
  15261. if (accepted) {
  15262. *flags = 0; // Clear all error flags
  15263. return 0;
  15264. }
  15265. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15266. }
  15267. } // namespace impl
  15268. inline ctx_t create_client_context() {
  15269. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15270. if (!ctx) { return nullptr; }
  15271. ctx->is_server = false;
  15272. // Seed the random number generator
  15273. const char *pers = "httplib_client";
  15274. int ret = mbedtls_ctr_drbg_seed(
  15275. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15276. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15277. if (ret != 0) {
  15278. impl::mbedtls_last_error() = ret;
  15279. delete ctx;
  15280. return nullptr;
  15281. }
  15282. // Set up SSL config for client
  15283. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15284. MBEDTLS_SSL_TRANSPORT_STREAM,
  15285. MBEDTLS_SSL_PRESET_DEFAULT);
  15286. if (ret != 0) {
  15287. impl::mbedtls_last_error() = ret;
  15288. delete ctx;
  15289. return nullptr;
  15290. }
  15291. // Set random number generator
  15292. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15293. // Default: verify peer certificate
  15294. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15295. // Set minimum TLS version to 1.2
  15296. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15297. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15298. #else
  15299. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15300. MBEDTLS_SSL_MINOR_VERSION_3);
  15301. #endif
  15302. return static_cast<ctx_t>(ctx);
  15303. }
  15304. inline ctx_t create_server_context() {
  15305. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15306. if (!ctx) { return nullptr; }
  15307. ctx->is_server = true;
  15308. // Seed the random number generator
  15309. const char *pers = "httplib_server";
  15310. int ret = mbedtls_ctr_drbg_seed(
  15311. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15312. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15313. if (ret != 0) {
  15314. impl::mbedtls_last_error() = ret;
  15315. delete ctx;
  15316. return nullptr;
  15317. }
  15318. // Set up SSL config for server
  15319. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15320. MBEDTLS_SSL_TRANSPORT_STREAM,
  15321. MBEDTLS_SSL_PRESET_DEFAULT);
  15322. if (ret != 0) {
  15323. impl::mbedtls_last_error() = ret;
  15324. delete ctx;
  15325. return nullptr;
  15326. }
  15327. // Set random number generator
  15328. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15329. // Default: don't verify client
  15330. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15331. // Set minimum TLS version to 1.2
  15332. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15333. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15334. #else
  15335. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15336. MBEDTLS_SSL_MINOR_VERSION_3);
  15337. #endif
  15338. // Set SNI callback to capture client's SNI hostname
  15339. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15340. return static_cast<ctx_t>(ctx);
  15341. }
  15342. inline void free_context(ctx_t ctx) {
  15343. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15344. }
  15345. inline bool set_min_version(ctx_t ctx, Version version) {
  15346. if (!ctx) { return false; }
  15347. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15348. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15349. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15350. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15351. if (version >= Version::TLS1_3) {
  15352. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15353. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15354. #endif
  15355. }
  15356. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15357. #else
  15358. // Mbed TLS 2.x uses major/minor version numbers
  15359. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15360. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15361. if (version >= Version::TLS1_3) {
  15362. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15363. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15364. #else
  15365. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15366. #endif
  15367. }
  15368. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15369. #endif
  15370. return true;
  15371. }
  15372. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15373. if (!ctx || !pem) { return false; }
  15374. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15375. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15376. // Add null terminator if not present
  15377. std::string pem_str(pem, len);
  15378. int ret = mbedtls_x509_crt_parse(
  15379. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15380. pem_str.size() + 1);
  15381. if (ret != 0) {
  15382. impl::mbedtls_last_error() = ret;
  15383. return false;
  15384. }
  15385. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15386. return true;
  15387. }
  15388. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15389. if (!ctx || !file_path) { return false; }
  15390. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15391. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15392. if (ret != 0) {
  15393. impl::mbedtls_last_error() = ret;
  15394. return false;
  15395. }
  15396. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15397. return true;
  15398. }
  15399. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15400. if (!ctx || !dir_path) { return false; }
  15401. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15402. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15403. if (ret < 0) { // Returns number of certs on success, negative on error
  15404. impl::mbedtls_last_error() = ret;
  15405. return false;
  15406. }
  15407. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15408. return true;
  15409. }
  15410. inline bool load_system_certs(ctx_t ctx) {
  15411. if (!ctx) { return false; }
  15412. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15413. bool loaded = false;
  15414. #ifdef _WIN32
  15415. loaded = impl::enumerate_windows_system_certs(
  15416. [&](const unsigned char *data, size_t len) {
  15417. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15418. });
  15419. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15420. loaded = impl::enumerate_macos_keychain_certs(
  15421. [&](const unsigned char *data, size_t len) {
  15422. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15423. });
  15424. #else
  15425. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15426. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15427. loaded = true;
  15428. break;
  15429. }
  15430. }
  15431. if (!loaded) {
  15432. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15433. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15434. loaded = true;
  15435. break;
  15436. }
  15437. }
  15438. }
  15439. #endif
  15440. if (loaded) {
  15441. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15442. }
  15443. return loaded;
  15444. }
  15445. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15446. const char *password) {
  15447. if (!ctx || !cert || !key) { return false; }
  15448. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15449. // Parse certificate
  15450. std::string cert_str(cert);
  15451. int ret = mbedtls_x509_crt_parse(
  15452. &mctx->own_cert,
  15453. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15454. cert_str.size() + 1);
  15455. if (ret != 0) {
  15456. impl::mbedtls_last_error() = ret;
  15457. return false;
  15458. }
  15459. // Parse private key
  15460. std::string key_str(key);
  15461. const unsigned char *pwd =
  15462. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15463. size_t pwd_len = password ? strlen(password) : 0;
  15464. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15465. ret = mbedtls_pk_parse_key(
  15466. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15467. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15468. &mctx->ctr_drbg);
  15469. #else
  15470. ret = mbedtls_pk_parse_key(
  15471. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15472. key_str.size() + 1, pwd, pwd_len);
  15473. #endif
  15474. if (ret != 0) {
  15475. impl::mbedtls_last_error() = ret;
  15476. return false;
  15477. }
  15478. // Verify that the certificate and private key match
  15479. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15480. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15481. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15482. #else
  15483. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15484. #endif
  15485. if (ret != 0) {
  15486. impl::mbedtls_last_error() = ret;
  15487. return false;
  15488. }
  15489. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15490. if (ret != 0) {
  15491. impl::mbedtls_last_error() = ret;
  15492. return false;
  15493. }
  15494. return true;
  15495. }
  15496. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15497. const char *key_path, const char *password) {
  15498. if (!ctx || !cert_path || !key_path) { return false; }
  15499. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15500. // Parse certificate file
  15501. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15502. if (ret != 0) {
  15503. impl::mbedtls_last_error() = ret;
  15504. return false;
  15505. }
  15506. // Parse private key file
  15507. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15508. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15509. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15510. #else
  15511. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15512. #endif
  15513. if (ret != 0) {
  15514. impl::mbedtls_last_error() = ret;
  15515. return false;
  15516. }
  15517. // Verify that the certificate and private key match
  15518. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15519. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15520. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15521. #else
  15522. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15523. #endif
  15524. if (ret != 0) {
  15525. impl::mbedtls_last_error() = ret;
  15526. return false;
  15527. }
  15528. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15529. if (ret != 0) {
  15530. impl::mbedtls_last_error() = ret;
  15531. return false;
  15532. }
  15533. return true;
  15534. }
  15535. inline void set_verify_client(ctx_t ctx, bool require) {
  15536. if (!ctx) { return; }
  15537. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15538. mctx->verify_client = require;
  15539. if (require) {
  15540. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15541. } else {
  15542. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15543. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15544. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15545. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15546. : MBEDTLS_SSL_VERIFY_NONE);
  15547. }
  15548. }
  15549. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15550. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15551. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15552. auto session = new (std::nothrow) impl::MbedTlsSession();
  15553. if (!session) { return nullptr; }
  15554. session->sock = sock;
  15555. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15556. if (ret != 0) {
  15557. impl::mbedtls_last_error() = ret;
  15558. delete session;
  15559. return nullptr;
  15560. }
  15561. // Explicitly opt out of in-handshake hostname verification by default;
  15562. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15563. // fails outright when no hostname was set. set_sni() installs the real
  15564. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15565. // caller verifies the certificate identity post-handshake via
  15566. // verify_hostname().
  15567. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15568. // Set BIO callbacks
  15569. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15570. impl::mbedtls_net_recv_cb, nullptr);
  15571. // Set per-session verify callback with session pointer if callback is
  15572. // registered
  15573. if (mctx->has_verify_callback) {
  15574. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15575. session);
  15576. }
  15577. return static_cast<session_t>(session);
  15578. }
  15579. inline void free_session(session_t session) {
  15580. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15581. }
  15582. inline bool set_sni(session_t session, const char *hostname) {
  15583. if (!session || !hostname) { return false; }
  15584. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15585. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15586. if (ret != 0) {
  15587. impl::mbedtls_last_error() = ret;
  15588. return false;
  15589. }
  15590. msession->hostname = hostname;
  15591. return true;
  15592. }
  15593. inline bool set_hostname(session_t session, const char *hostname) {
  15594. // In Mbed TLS, set_hostname also sets up hostname verification
  15595. return set_sni(session, hostname);
  15596. }
  15597. inline TlsError connect(session_t session) {
  15598. TlsError err;
  15599. if (!session) {
  15600. err.code = ErrorCode::Fatal;
  15601. return err;
  15602. }
  15603. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15604. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15605. if (ret == 0) {
  15606. err.code = ErrorCode::Success;
  15607. } else {
  15608. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15609. err.backend_code = static_cast<uint64_t>(-ret);
  15610. impl::mbedtls_last_error() = ret;
  15611. }
  15612. return err;
  15613. }
  15614. inline TlsError accept(session_t session) {
  15615. // Same as connect for Mbed TLS - handshake works for both client and server
  15616. auto result = connect(session);
  15617. // After successful handshake, capture SNI from thread-local storage
  15618. if (result.code == ErrorCode::Success && session) {
  15619. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15620. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15621. impl::mbedpending_sni().clear();
  15622. }
  15623. return result;
  15624. }
  15625. inline bool connect_nonblocking(session_t session, socket_t sock,
  15626. time_t timeout_sec, time_t timeout_usec,
  15627. TlsError *err) {
  15628. if (!session) {
  15629. if (err) { err->code = ErrorCode::Fatal; }
  15630. return false;
  15631. }
  15632. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15633. // Set socket to non-blocking mode
  15634. detail::set_nonblocking(sock, true);
  15635. auto cleanup =
  15636. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15637. int ret;
  15638. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15639. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15640. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15641. continue;
  15642. }
  15643. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15644. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15645. continue;
  15646. }
  15647. }
  15648. // TlsError or timeout
  15649. if (err) {
  15650. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15651. err->backend_code = static_cast<uint64_t>(-ret);
  15652. }
  15653. impl::mbedtls_last_error() = ret;
  15654. return false;
  15655. }
  15656. if (err) { err->code = ErrorCode::Success; }
  15657. return true;
  15658. }
  15659. inline bool accept_nonblocking(session_t session, socket_t sock,
  15660. time_t timeout_sec, time_t timeout_usec,
  15661. TlsError *err) {
  15662. // Same implementation as connect for Mbed TLS
  15663. bool result =
  15664. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15665. // After successful handshake, capture SNI from thread-local storage
  15666. if (result && session) {
  15667. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15668. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15669. impl::mbedpending_sni().clear();
  15670. }
  15671. return result;
  15672. }
  15673. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15674. if (!session || !buf) {
  15675. err.code = ErrorCode::Fatal;
  15676. return -1;
  15677. }
  15678. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15679. int ret =
  15680. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15681. if (ret > 0) {
  15682. err.code = ErrorCode::Success;
  15683. return static_cast<ssize_t>(ret);
  15684. }
  15685. if (ret == 0) {
  15686. err.code = ErrorCode::PeerClosed;
  15687. return 0;
  15688. }
  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. // mbedTLS signals a clean close_notify via a negative error code rather
  15693. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15694. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15695. return -1;
  15696. }
  15697. inline ssize_t write(session_t session, const void *buf, size_t len,
  15698. TlsError &err) {
  15699. if (!session || !buf) {
  15700. err.code = ErrorCode::Fatal;
  15701. return -1;
  15702. }
  15703. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15704. int ret = mbedtls_ssl_write(&msession->ssl,
  15705. static_cast<const unsigned char *>(buf), len);
  15706. if (ret > 0) {
  15707. err.code = ErrorCode::Success;
  15708. return static_cast<ssize_t>(ret);
  15709. }
  15710. if (ret == 0) {
  15711. err.code = ErrorCode::PeerClosed;
  15712. return 0;
  15713. }
  15714. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15715. err.backend_code = static_cast<uint64_t>(-ret);
  15716. impl::mbedtls_last_error() = ret;
  15717. return -1;
  15718. }
  15719. inline int pending(const_session_t session) {
  15720. if (!session) { return 0; }
  15721. auto msession =
  15722. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15723. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15724. }
  15725. inline void shutdown(session_t session, bool graceful) {
  15726. if (!session) { return; }
  15727. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15728. if (graceful) {
  15729. // Try to send close_notify, but don't block forever
  15730. int ret;
  15731. int attempts = 0;
  15732. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15733. attempts < 3) {
  15734. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15735. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15736. break;
  15737. }
  15738. attempts++;
  15739. }
  15740. }
  15741. }
  15742. inline bool is_peer_closed(session_t session, socket_t sock) {
  15743. if (!session || sock == INVALID_SOCKET) { return true; }
  15744. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15745. // Check if there's already decrypted data available in the TLS buffer
  15746. // If so, the connection is definitely alive
  15747. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15748. // Set socket to non-blocking to avoid blocking on read
  15749. detail::set_nonblocking(sock, true);
  15750. auto cleanup =
  15751. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15752. // Try a 1-byte read to check connection status
  15753. // Note: This will consume the byte if data is available, but for the
  15754. // purpose of checking if peer is closed, this should be acceptable
  15755. // since we're only called when we expect the connection might be closing
  15756. unsigned char buf;
  15757. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15758. // If we got data or WANT_READ (would block), connection is alive
  15759. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15760. // If we get a peer close notify or a connection reset, the peer is closed
  15761. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15762. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15763. }
  15764. inline cert_t get_peer_cert(const_session_t session) {
  15765. if (!session) { return nullptr; }
  15766. auto msession =
  15767. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15768. // Mbed TLS returns a pointer to the internal peer cert chain.
  15769. // WARNING: This pointer is only valid while the session is active.
  15770. // Do not use the certificate after calling free_session().
  15771. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15772. return const_cast<mbedtls_x509_crt *>(cert);
  15773. }
  15774. inline void free_cert(cert_t cert) {
  15775. // Mbed TLS: peer certificate is owned by the SSL context.
  15776. // No-op here, but callers should still call this for cross-backend
  15777. // portability.
  15778. (void)cert;
  15779. }
  15780. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15781. if (!cert || !hostname) { return false; }
  15782. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15783. std::string host_str(hostname);
  15784. // Check if hostname is an IP address (IPv4 or IPv6)
  15785. unsigned char ip_bytes[16];
  15786. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15787. auto is_ip = ip_len > 0;
  15788. // Check Subject Alternative Names (SAN)
  15789. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15790. // - DNS names: raw string bytes
  15791. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15792. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15793. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15794. const unsigned char *p = san->buf.p;
  15795. size_t len = san->buf.len;
  15796. if (is_ip) {
  15797. // For an IP host, only a matching iPAddress SAN of the same family
  15798. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15799. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15800. } else {
  15801. // Check if this SAN is a DNS name (printable ASCII string)
  15802. bool is_dns = len > 0;
  15803. for (size_t i = 0; i < len && is_dns; i++) {
  15804. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15805. }
  15806. if (is_dns) {
  15807. std::string san_name(reinterpret_cast<const char *>(p), len);
  15808. if (detail::match_hostname(san_name, host_str)) { return true; }
  15809. }
  15810. }
  15811. san = san->next;
  15812. }
  15813. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15814. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15815. // the OpenSSL backend's X509_check_ip behaves the same way).
  15816. if (!is_ip) {
  15817. char cn[256];
  15818. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15819. if (ret > 0) {
  15820. std::string cn_str(cn);
  15821. // Look for "CN=" in the DN string
  15822. size_t cn_pos = cn_str.find("CN=");
  15823. if (cn_pos != std::string::npos) {
  15824. size_t start = cn_pos + 3;
  15825. size_t end = cn_str.find(',', start);
  15826. std::string cn_value =
  15827. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15828. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15829. }
  15830. }
  15831. }
  15832. return false;
  15833. }
  15834. inline uint64_t hostname_mismatch_code() {
  15835. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15836. }
  15837. inline long get_verify_result(const_session_t session) {
  15838. if (!session) { return -1; }
  15839. auto msession =
  15840. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15841. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15842. // Return 0 (X509_V_OK equivalent) if verification passed
  15843. return flags == 0 ? 0 : static_cast<long>(flags);
  15844. }
  15845. inline std::string get_cert_subject_cn(cert_t cert) {
  15846. if (!cert) return "";
  15847. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15848. // Find the CN in the subject
  15849. const mbedtls_x509_name *name = &x509->subject;
  15850. while (name != nullptr) {
  15851. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15852. return std::string(reinterpret_cast<const char *>(name->val.p),
  15853. name->val.len);
  15854. }
  15855. name = name->next;
  15856. }
  15857. return "";
  15858. }
  15859. inline std::string get_cert_issuer_name(cert_t cert) {
  15860. if (!cert) return "";
  15861. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15862. // Build a human-readable issuer name string
  15863. char buf[512];
  15864. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15865. if (ret < 0) return "";
  15866. return std::string(buf);
  15867. }
  15868. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15869. sans.clear();
  15870. if (!cert) return false;
  15871. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15872. // Parse the Subject Alternative Name extension
  15873. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15874. while (cur != nullptr) {
  15875. if (cur->buf.len > 0) {
  15876. // Mbed TLS stores SAN as ASN.1 sequences
  15877. // The tag byte indicates the type
  15878. const unsigned char *p = cur->buf.p;
  15879. size_t len = cur->buf.len;
  15880. // First byte is the tag
  15881. unsigned char tag = *p;
  15882. p++;
  15883. len--;
  15884. // Parse length (simple single-byte length assumed)
  15885. if (len > 0 && *p < 0x80) {
  15886. size_t value_len = *p;
  15887. p++;
  15888. len--;
  15889. if (value_len <= len) {
  15890. SanEntry entry;
  15891. // ASN.1 context tags for GeneralName
  15892. switch (tag & 0x1F) {
  15893. case 2: // dNSName
  15894. entry.type = SanType::DNS;
  15895. entry.value =
  15896. std::string(reinterpret_cast<const char *>(p), value_len);
  15897. break;
  15898. case 7: // iPAddress
  15899. entry.type = SanType::IP;
  15900. if (value_len == 4) {
  15901. // IPv4
  15902. char buf[16];
  15903. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15904. entry.value = buf;
  15905. } else if (value_len == 16) {
  15906. // IPv6
  15907. char buf[64];
  15908. snprintf(buf, sizeof(buf),
  15909. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15910. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15911. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15912. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15913. entry.value = buf;
  15914. }
  15915. break;
  15916. case 1: // rfc822Name (email)
  15917. entry.type = SanType::EMAIL;
  15918. entry.value =
  15919. std::string(reinterpret_cast<const char *>(p), value_len);
  15920. break;
  15921. case 6: // uniformResourceIdentifier
  15922. entry.type = SanType::URI;
  15923. entry.value =
  15924. std::string(reinterpret_cast<const char *>(p), value_len);
  15925. break;
  15926. default: entry.type = SanType::OTHER; break;
  15927. }
  15928. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15929. }
  15930. }
  15931. }
  15932. cur = cur->next;
  15933. }
  15934. return true;
  15935. }
  15936. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15937. time_t &not_after) {
  15938. if (!cert) return false;
  15939. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15940. // Convert mbedtls_x509_time to time_t
  15941. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15942. struct tm tm_time = {};
  15943. tm_time.tm_year = t.year - 1900;
  15944. tm_time.tm_mon = t.mon - 1;
  15945. tm_time.tm_mday = t.day;
  15946. tm_time.tm_hour = t.hour;
  15947. tm_time.tm_min = t.min;
  15948. tm_time.tm_sec = t.sec;
  15949. #ifdef _WIN32
  15950. return _mkgmtime(&tm_time);
  15951. #else
  15952. return timegm(&tm_time);
  15953. #endif
  15954. };
  15955. not_before = to_time_t(x509->valid_from);
  15956. not_after = to_time_t(x509->valid_to);
  15957. return true;
  15958. }
  15959. inline std::string get_cert_serial(cert_t cert) {
  15960. if (!cert) return "";
  15961. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15962. // Convert serial number to hex string
  15963. std::string result;
  15964. result.reserve(x509->serial.len * 2);
  15965. for (size_t i = 0; i < x509->serial.len; i++) {
  15966. char hex[3];
  15967. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15968. result += hex;
  15969. }
  15970. return result;
  15971. }
  15972. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15973. if (!cert) return false;
  15974. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  15975. if (!crt->raw.p || crt->raw.len == 0) return false;
  15976. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  15977. return true;
  15978. }
  15979. inline const char *get_sni(const_session_t session) {
  15980. if (!session) return nullptr;
  15981. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  15982. // For server: return SNI received from client during handshake
  15983. if (!msession->sni_hostname.empty()) {
  15984. return msession->sni_hostname.c_str();
  15985. }
  15986. // For client: return the hostname set via set_sni
  15987. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  15988. return nullptr;
  15989. }
  15990. inline uint64_t peek_error() {
  15991. // Mbed TLS doesn't have an error queue, return the last error
  15992. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  15993. }
  15994. inline uint64_t get_error() {
  15995. // Mbed TLS doesn't have an error queue, return and clear the last error
  15996. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  15997. impl::mbedtls_last_error() = 0;
  15998. return err;
  15999. }
  16000. inline std::string error_string(uint64_t code) {
  16001. char buf[256];
  16002. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16003. return std::string(buf);
  16004. }
  16005. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16006. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16007. if (!ca_chain) { return nullptr; }
  16008. mbedtls_x509_crt_init(ca_chain);
  16009. // mbedtls_x509_crt_parse expects null-terminated PEM
  16010. int ret = mbedtls_x509_crt_parse(ca_chain,
  16011. reinterpret_cast<const unsigned char *>(pem),
  16012. len + 1); // +1 for null terminator
  16013. if (ret != 0) {
  16014. // Try without +1 in case PEM is already null-terminated
  16015. ret = mbedtls_x509_crt_parse(
  16016. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16017. if (ret != 0) {
  16018. mbedtls_x509_crt_free(ca_chain);
  16019. delete ca_chain;
  16020. return nullptr;
  16021. }
  16022. }
  16023. return static_cast<ca_store_t>(ca_chain);
  16024. }
  16025. inline void free_ca_store(ca_store_t store) {
  16026. if (store) {
  16027. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16028. mbedtls_x509_crt_free(ca_chain);
  16029. delete ca_chain;
  16030. }
  16031. }
  16032. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16033. if (!ctx || !store) { return false; }
  16034. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16035. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16036. // Free existing CA chain
  16037. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16038. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16039. // Copy the CA chain (deep copy)
  16040. // Parse from the raw data of the source cert
  16041. mbedtls_x509_crt *src = ca_chain;
  16042. while (src != nullptr) {
  16043. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16044. src->raw.len);
  16045. if (ret != 0) {
  16046. free_ca_store(store);
  16047. return false;
  16048. }
  16049. src = src->next;
  16050. }
  16051. // This function takes ownership of the store; the chain was deep-copied
  16052. // above, so release the source
  16053. free_ca_store(store);
  16054. // Update the SSL config to use the new CA chain
  16055. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16056. return true;
  16057. }
  16058. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16059. certs.clear();
  16060. if (!ctx) { return 0; }
  16061. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16062. // Iterate through the CA chain
  16063. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16064. while (cert != nullptr && cert->raw.len > 0) {
  16065. // Create a copy of the certificate for the caller
  16066. auto *copy = new mbedtls_x509_crt;
  16067. mbedtls_x509_crt_init(copy);
  16068. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16069. if (ret == 0) {
  16070. certs.push_back(static_cast<cert_t>(copy));
  16071. } else {
  16072. mbedtls_x509_crt_free(copy);
  16073. delete copy;
  16074. }
  16075. cert = cert->next;
  16076. }
  16077. return certs.size();
  16078. }
  16079. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16080. std::vector<std::string> names;
  16081. if (!ctx) { return names; }
  16082. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16083. // Iterate through the CA chain
  16084. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16085. while (cert != nullptr && cert->raw.len > 0) {
  16086. char buf[512];
  16087. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16088. if (ret > 0) { names.push_back(buf); }
  16089. cert = cert->next;
  16090. }
  16091. return names;
  16092. }
  16093. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16094. const char *key_pem, const char *password) {
  16095. if (!ctx || !cert_pem || !key_pem) { return false; }
  16096. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16097. // Free existing certificate and key
  16098. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16099. mbedtls_pk_free(&mbed_ctx->own_key);
  16100. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16101. mbedtls_pk_init(&mbed_ctx->own_key);
  16102. // Parse certificate PEM
  16103. int ret = mbedtls_x509_crt_parse(
  16104. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16105. strlen(cert_pem) + 1);
  16106. if (ret != 0) {
  16107. impl::mbedtls_last_error() = ret;
  16108. return false;
  16109. }
  16110. // Parse private key PEM
  16111. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16112. ret = mbedtls_pk_parse_key(
  16113. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16114. strlen(key_pem) + 1,
  16115. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16116. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16117. &mbed_ctx->ctr_drbg);
  16118. #else
  16119. ret = mbedtls_pk_parse_key(
  16120. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16121. strlen(key_pem) + 1,
  16122. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16123. password ? strlen(password) : 0);
  16124. #endif
  16125. if (ret != 0) {
  16126. impl::mbedtls_last_error() = ret;
  16127. return false;
  16128. }
  16129. // Configure SSL to use the new certificate and key
  16130. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16131. &mbed_ctx->own_key);
  16132. if (ret != 0) {
  16133. impl::mbedtls_last_error() = ret;
  16134. return false;
  16135. }
  16136. return true;
  16137. }
  16138. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16139. if (!ctx || !ca_pem) { return false; }
  16140. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16141. // Free existing CA chain
  16142. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16143. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16144. // Parse CA PEM
  16145. int ret = mbedtls_x509_crt_parse(
  16146. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16147. strlen(ca_pem) + 1);
  16148. if (ret != 0) {
  16149. impl::mbedtls_last_error() = ret;
  16150. return false;
  16151. }
  16152. // Update SSL config to use new CA chain
  16153. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16154. return true;
  16155. }
  16156. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16157. if (!ctx) { return false; }
  16158. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16159. impl::get_verify_callback() = std::move(callback);
  16160. mbed_ctx->has_verify_callback =
  16161. static_cast<bool>(impl::get_verify_callback());
  16162. if (mbed_ctx->has_verify_callback) {
  16163. // Set OPTIONAL mode to ensure callback is called even when verification
  16164. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16165. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16166. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16167. nullptr);
  16168. } else {
  16169. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16170. }
  16171. return true;
  16172. }
  16173. inline long get_verify_error(const_session_t session) {
  16174. if (!session) { return -1; }
  16175. auto *msession =
  16176. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16177. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16178. }
  16179. inline std::string verify_error_string(long error_code) {
  16180. if (error_code == 0) { return ""; }
  16181. char buf[256];
  16182. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16183. static_cast<uint32_t>(error_code));
  16184. // Remove trailing newline if present
  16185. std::string result(buf);
  16186. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16187. result.pop_back();
  16188. }
  16189. return result;
  16190. }
  16191. } // namespace tls
  16192. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16193. /*
  16194. * Group 10: TLS abstraction layer - wolfSSL backend
  16195. */
  16196. /*
  16197. * wolfSSL Backend Implementation
  16198. */
  16199. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16200. namespace tls {
  16201. namespace impl {
  16202. // wolfSSL session wrapper
  16203. struct WolfSSLSession {
  16204. WOLFSSL *ssl = nullptr;
  16205. socket_t sock = INVALID_SOCKET;
  16206. std::string hostname; // For client: set via set_sni
  16207. std::string sni_hostname; // For server: received from client via SNI callback
  16208. WolfSSLSession() = default;
  16209. ~WolfSSLSession() {
  16210. if (ssl) { wolfSSL_free(ssl); }
  16211. }
  16212. WolfSSLSession(const WolfSSLSession &) = delete;
  16213. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16214. };
  16215. // Thread-local error code accessor for wolfSSL
  16216. inline uint64_t &wolfssl_last_error() {
  16217. static thread_local uint64_t err = 0;
  16218. return err;
  16219. }
  16220. // Helper to map wolfSSL error to ErrorCode.
  16221. // ssl_error is the value from wolfSSL_get_error().
  16222. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16223. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16224. int &out_errno) {
  16225. switch (ssl_error) {
  16226. case SSL_ERROR_NONE: return ErrorCode::Success;
  16227. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16228. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16229. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16230. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16231. default:
  16232. if (ssl) {
  16233. // wolfSSL stores the low-level error code as a negative value.
  16234. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16235. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16236. if (low_err == DOMAIN_NAME_MISMATCH) {
  16237. return ErrorCode::HostnameMismatch;
  16238. }
  16239. // Check verify result to distinguish cert verification from generic SSL
  16240. // errors.
  16241. long vr = wolfSSL_get_verify_result(ssl);
  16242. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16243. }
  16244. return ErrorCode::Fatal;
  16245. }
  16246. }
  16247. // WolfSSLContext constructor/destructor implementations
  16248. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16249. inline WolfSSLContext::~WolfSSLContext() {
  16250. if (ctx) { wolfSSL_CTX_free(ctx); }
  16251. }
  16252. // Thread-local storage for SNI captured during handshake
  16253. inline std::string &wolfssl_pending_sni() {
  16254. static thread_local std::string sni;
  16255. return sni;
  16256. }
  16257. // SNI callback for wolfSSL server to capture client's SNI hostname
  16258. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16259. (void)ret;
  16260. (void)exArg;
  16261. void *name_data = nullptr;
  16262. unsigned short name_len =
  16263. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16264. if (name_data && name_len > 0) {
  16265. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16266. name_len);
  16267. } else {
  16268. wolfssl_pending_sni().clear();
  16269. }
  16270. return 0; // Continue regardless
  16271. }
  16272. // wolfSSL verify callback wrapper
  16273. inline int wolfssl_verify_callback(int preverify_ok,
  16274. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16275. auto &callback = get_verify_callback();
  16276. if (!callback) { return preverify_ok; }
  16277. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16278. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16279. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16280. // Get the WOLFSSL object from the X509_STORE_CTX
  16281. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16282. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16283. VerifyContext verify_ctx;
  16284. verify_ctx.session = static_cast<session_t>(ssl);
  16285. verify_ctx.cert = static_cast<cert_t>(cert);
  16286. verify_ctx.depth = depth;
  16287. verify_ctx.preverify_ok = (preverify_ok != 0);
  16288. verify_ctx.error_code = static_cast<long>(err);
  16289. if (err != 0) {
  16290. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16291. } else {
  16292. verify_ctx.error_string = nullptr;
  16293. }
  16294. bool accepted = callback(verify_ctx);
  16295. return accepted ? 1 : 0;
  16296. }
  16297. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16298. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16299. wolfSSL_CTX_set_default_passwd_cb(
  16300. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16301. auto *pwd = static_cast<const char *>(userdata);
  16302. if (!pwd) return 0;
  16303. auto len = static_cast<int>(strlen(pwd));
  16304. if (len > size) len = size;
  16305. memcpy(buf, pwd, static_cast<size_t>(len));
  16306. return len;
  16307. });
  16308. }
  16309. } // namespace impl
  16310. inline ctx_t create_client_context() {
  16311. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16312. if (!ctx) { return nullptr; }
  16313. ctx->is_server = false;
  16314. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16315. if (!method) {
  16316. delete ctx;
  16317. return nullptr;
  16318. }
  16319. ctx->ctx = wolfSSL_CTX_new(method);
  16320. if (!ctx->ctx) {
  16321. delete ctx;
  16322. return nullptr;
  16323. }
  16324. // Default: verify peer certificate
  16325. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16326. return static_cast<ctx_t>(ctx);
  16327. }
  16328. inline ctx_t create_server_context() {
  16329. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16330. if (!ctx) { return nullptr; }
  16331. ctx->is_server = true;
  16332. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16333. if (!method) {
  16334. delete ctx;
  16335. return nullptr;
  16336. }
  16337. ctx->ctx = wolfSSL_CTX_new(method);
  16338. if (!ctx->ctx) {
  16339. delete ctx;
  16340. return nullptr;
  16341. }
  16342. // Default: don't verify client
  16343. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16344. // Enable SNI on server
  16345. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16346. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16347. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16348. return static_cast<ctx_t>(ctx);
  16349. }
  16350. inline void free_context(ctx_t ctx) {
  16351. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16352. }
  16353. inline bool set_min_version(ctx_t ctx, Version version) {
  16354. if (!ctx) { return false; }
  16355. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16356. int min_ver = WOLFSSL_TLSV1_2;
  16357. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16358. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16359. }
  16360. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16361. if (!ctx || !pem) { return false; }
  16362. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16363. int ret = wolfSSL_CTX_load_verify_buffer(
  16364. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16365. static_cast<long>(len), SSL_FILETYPE_PEM);
  16366. if (ret != SSL_SUCCESS) {
  16367. impl::wolfssl_last_error() =
  16368. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16369. return false;
  16370. }
  16371. wctx->ca_pem_data_.append(pem, len);
  16372. return true;
  16373. }
  16374. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16375. if (!ctx || !file_path) { return false; }
  16376. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16377. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16378. if (ret != SSL_SUCCESS) {
  16379. impl::wolfssl_last_error() =
  16380. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16381. return false;
  16382. }
  16383. return true;
  16384. }
  16385. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16386. if (!ctx || !dir_path) { return false; }
  16387. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16388. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16389. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16390. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16391. // immediately. Return true even on failure since the CA file may have
  16392. // already been loaded, matching OpenSSL's lenient behavior.
  16393. (void)ret;
  16394. return true;
  16395. }
  16396. inline bool load_system_certs(ctx_t ctx) {
  16397. if (!ctx) { return false; }
  16398. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16399. bool loaded = false;
  16400. #ifdef _WIN32
  16401. loaded = impl::enumerate_windows_system_certs(
  16402. [&](const unsigned char *data, size_t len) {
  16403. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16404. static_cast<long>(len),
  16405. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16406. });
  16407. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16408. loaded = impl::enumerate_macos_keychain_certs(
  16409. [&](const unsigned char *data, size_t len) {
  16410. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16411. static_cast<long>(len),
  16412. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16413. });
  16414. #else
  16415. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16416. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16417. SSL_SUCCESS) {
  16418. loaded = true;
  16419. break;
  16420. }
  16421. }
  16422. if (!loaded) {
  16423. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16424. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16425. SSL_SUCCESS) {
  16426. loaded = true;
  16427. break;
  16428. }
  16429. }
  16430. }
  16431. #endif
  16432. return loaded;
  16433. }
  16434. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16435. const char *password) {
  16436. if (!ctx || !cert || !key) { return false; }
  16437. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16438. // Load certificate
  16439. int ret = wolfSSL_CTX_use_certificate_buffer(
  16440. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16441. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16442. if (ret != SSL_SUCCESS) {
  16443. impl::wolfssl_last_error() =
  16444. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16445. return false;
  16446. }
  16447. // Set password callback if password is provided
  16448. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16449. // Load private key
  16450. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16451. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16452. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16453. if (ret != SSL_SUCCESS) {
  16454. impl::wolfssl_last_error() =
  16455. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16456. return false;
  16457. }
  16458. // Verify that the certificate and private key match
  16459. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16460. }
  16461. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16462. const char *key_path, const char *password) {
  16463. if (!ctx || !cert_path || !key_path) { return false; }
  16464. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16465. // Load certificate file
  16466. int ret =
  16467. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16468. if (ret != SSL_SUCCESS) {
  16469. impl::wolfssl_last_error() =
  16470. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16471. return false;
  16472. }
  16473. // Set password callback if password is provided
  16474. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16475. // Load private key file
  16476. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16477. if (ret != SSL_SUCCESS) {
  16478. impl::wolfssl_last_error() =
  16479. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16480. return false;
  16481. }
  16482. // Verify that the certificate and private key match
  16483. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16484. }
  16485. inline void set_verify_client(ctx_t ctx, bool require) {
  16486. if (!ctx) { return; }
  16487. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16488. wctx->verify_client = require;
  16489. if (require) {
  16490. wolfSSL_CTX_set_verify(
  16491. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16492. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16493. } else {
  16494. if (wctx->has_verify_callback) {
  16495. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16496. impl::wolfssl_verify_callback);
  16497. } else {
  16498. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16499. }
  16500. }
  16501. }
  16502. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16503. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16504. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16505. auto session = new (std::nothrow) impl::WolfSSLSession();
  16506. if (!session) { return nullptr; }
  16507. session->sock = sock;
  16508. session->ssl = wolfSSL_new(wctx->ctx);
  16509. if (!session->ssl) {
  16510. impl::wolfssl_last_error() =
  16511. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16512. delete session;
  16513. return nullptr;
  16514. }
  16515. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16516. return static_cast<session_t>(session);
  16517. }
  16518. inline void free_session(session_t session) {
  16519. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16520. }
  16521. inline bool set_sni(session_t session, const char *hostname) {
  16522. if (!session || !hostname) { return false; }
  16523. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16524. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16525. static_cast<word16>(strlen(hostname)));
  16526. if (ret != WOLFSSL_SUCCESS) {
  16527. impl::wolfssl_last_error() =
  16528. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16529. return false;
  16530. }
  16531. // Also set hostname for verification
  16532. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16533. wsession->hostname = hostname;
  16534. return true;
  16535. }
  16536. inline bool set_hostname(session_t session, const char *hostname) {
  16537. // In wolfSSL, set_hostname also sets up hostname verification
  16538. return set_sni(session, hostname);
  16539. }
  16540. inline TlsError connect(session_t session) {
  16541. TlsError err;
  16542. if (!session) {
  16543. err.code = ErrorCode::Fatal;
  16544. return err;
  16545. }
  16546. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16547. int ret = wolfSSL_connect(wsession->ssl);
  16548. if (ret == SSL_SUCCESS) {
  16549. err.code = ErrorCode::Success;
  16550. } else {
  16551. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16552. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16553. err.backend_code = static_cast<uint64_t>(ssl_error);
  16554. impl::wolfssl_last_error() = err.backend_code;
  16555. }
  16556. return err;
  16557. }
  16558. inline TlsError accept(session_t session) {
  16559. TlsError err;
  16560. if (!session) {
  16561. err.code = ErrorCode::Fatal;
  16562. return err;
  16563. }
  16564. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16565. int ret = wolfSSL_accept(wsession->ssl);
  16566. if (ret == SSL_SUCCESS) {
  16567. err.code = ErrorCode::Success;
  16568. // Capture SNI from thread-local storage after successful handshake
  16569. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16570. impl::wolfssl_pending_sni().clear();
  16571. } else {
  16572. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16573. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16574. err.backend_code = static_cast<uint64_t>(ssl_error);
  16575. impl::wolfssl_last_error() = err.backend_code;
  16576. }
  16577. return err;
  16578. }
  16579. inline bool connect_nonblocking(session_t session, socket_t sock,
  16580. time_t timeout_sec, time_t timeout_usec,
  16581. TlsError *err) {
  16582. if (!session) {
  16583. if (err) { err->code = ErrorCode::Fatal; }
  16584. return false;
  16585. }
  16586. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16587. // Set socket to non-blocking mode
  16588. detail::set_nonblocking(sock, true);
  16589. auto cleanup =
  16590. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16591. int ret;
  16592. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16593. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16594. if (ssl_error == SSL_ERROR_WANT_READ) {
  16595. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16596. continue;
  16597. }
  16598. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16599. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16600. continue;
  16601. }
  16602. }
  16603. // Error or timeout
  16604. if (err) {
  16605. err->code =
  16606. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16607. err->backend_code = static_cast<uint64_t>(ssl_error);
  16608. }
  16609. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16610. return false;
  16611. }
  16612. if (err) { err->code = ErrorCode::Success; }
  16613. return true;
  16614. }
  16615. inline bool accept_nonblocking(session_t session, socket_t sock,
  16616. time_t timeout_sec, time_t timeout_usec,
  16617. TlsError *err) {
  16618. if (!session) {
  16619. if (err) { err->code = ErrorCode::Fatal; }
  16620. return false;
  16621. }
  16622. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16623. // Set socket to non-blocking mode
  16624. detail::set_nonblocking(sock, true);
  16625. auto cleanup =
  16626. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16627. int ret;
  16628. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16629. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16630. if (ssl_error == SSL_ERROR_WANT_READ) {
  16631. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16632. continue;
  16633. }
  16634. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16635. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16636. continue;
  16637. }
  16638. }
  16639. // Error or timeout
  16640. if (err) {
  16641. err->code =
  16642. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16643. err->backend_code = static_cast<uint64_t>(ssl_error);
  16644. }
  16645. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16646. return false;
  16647. }
  16648. if (err) { 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. return true;
  16653. }
  16654. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16655. if (!session || !buf) {
  16656. err.code = ErrorCode::Fatal;
  16657. return -1;
  16658. }
  16659. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16660. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16661. if (ret > 0) {
  16662. err.code = ErrorCode::Success;
  16663. return static_cast<ssize_t>(ret);
  16664. }
  16665. if (ret == 0) {
  16666. err.code = ErrorCode::PeerClosed;
  16667. return 0;
  16668. }
  16669. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16670. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16671. err.backend_code = static_cast<uint64_t>(ssl_error);
  16672. impl::wolfssl_last_error() = err.backend_code;
  16673. return -1;
  16674. }
  16675. inline ssize_t write(session_t session, const void *buf, size_t len,
  16676. TlsError &err) {
  16677. if (!session || !buf) {
  16678. err.code = ErrorCode::Fatal;
  16679. return -1;
  16680. }
  16681. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16682. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16683. if (ret > 0) {
  16684. err.code = ErrorCode::Success;
  16685. return static_cast<ssize_t>(ret);
  16686. }
  16687. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16688. // Treat this as an error (return -1) so callers don't spin in a
  16689. // write loop adding zero to the offset.
  16690. if (ret == 0) {
  16691. err.code = ErrorCode::PeerClosed;
  16692. return -1;
  16693. }
  16694. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16695. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16696. err.backend_code = static_cast<uint64_t>(ssl_error);
  16697. impl::wolfssl_last_error() = err.backend_code;
  16698. return -1;
  16699. }
  16700. inline int pending(const_session_t session) {
  16701. if (!session) { return 0; }
  16702. auto wsession =
  16703. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16704. return wolfSSL_pending(wsession->ssl);
  16705. }
  16706. inline void shutdown(session_t session, bool graceful) {
  16707. if (!session) { return; }
  16708. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16709. if (graceful) {
  16710. int ret;
  16711. int attempts = 0;
  16712. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16713. attempts < 3) {
  16714. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16715. if (ssl_error != SSL_ERROR_WANT_READ &&
  16716. ssl_error != SSL_ERROR_WANT_WRITE) {
  16717. break;
  16718. }
  16719. attempts++;
  16720. }
  16721. } else {
  16722. wolfSSL_shutdown(wsession->ssl);
  16723. }
  16724. }
  16725. inline bool is_peer_closed(session_t session, socket_t sock) {
  16726. if (!session || sock == INVALID_SOCKET) { return true; }
  16727. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16728. // Check if there's already decrypted data available
  16729. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16730. // Set socket to non-blocking to avoid blocking on read
  16731. detail::set_nonblocking(sock, true);
  16732. auto cleanup =
  16733. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16734. // Peek 1 byte to check connection status without consuming data
  16735. unsigned char buf;
  16736. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16737. // If we got data or WANT_READ (would block), connection is alive
  16738. if (ret > 0) { return false; }
  16739. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16740. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16741. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16742. ret == 0;
  16743. }
  16744. inline cert_t get_peer_cert(const_session_t session) {
  16745. if (!session) { return nullptr; }
  16746. auto wsession =
  16747. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16748. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16749. return static_cast<cert_t>(cert);
  16750. }
  16751. inline void free_cert(cert_t cert) {
  16752. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16753. }
  16754. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16755. if (!cert || !hostname) { return false; }
  16756. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16757. std::string host_str(hostname);
  16758. // Check if hostname is an IP address (IPv4 or IPv6)
  16759. unsigned char ip_bytes[16];
  16760. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16761. auto is_ip = ip_len > 0;
  16762. // Check Subject Alternative Names
  16763. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16764. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16765. if (san_names) {
  16766. int san_count = wolfSSL_sk_num(san_names);
  16767. for (int i = 0; i < san_count; i++) {
  16768. auto *names =
  16769. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16770. if (!names) continue;
  16771. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16772. // DNS name
  16773. unsigned char *dns_name = nullptr;
  16774. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16775. if (dns_name && dns_len > 0) {
  16776. std::string san_name(reinterpret_cast<char *>(dns_name),
  16777. static_cast<size_t>(dns_len));
  16778. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16779. if (detail::match_hostname(san_name, host_str)) {
  16780. wolfSSL_sk_free(san_names);
  16781. return true;
  16782. }
  16783. }
  16784. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16785. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16786. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16787. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16788. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16789. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16790. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16791. wolfSSL_sk_free(san_names);
  16792. return true;
  16793. }
  16794. }
  16795. }
  16796. wolfSSL_sk_free(san_names);
  16797. }
  16798. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16799. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16800. // the OpenSSL backend's X509_check_ip behaves the same way).
  16801. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16802. if (subject) {
  16803. char cn[256] = {};
  16804. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16805. sizeof(cn));
  16806. if (cn_len > 0) {
  16807. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16808. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16809. }
  16810. }
  16811. return false;
  16812. }
  16813. inline uint64_t hostname_mismatch_code() {
  16814. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16815. }
  16816. inline long get_verify_result(const_session_t session) {
  16817. if (!session) { return -1; }
  16818. auto wsession =
  16819. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16820. long result = wolfSSL_get_verify_result(wsession->ssl);
  16821. return result;
  16822. }
  16823. inline std::string get_cert_subject_cn(cert_t cert) {
  16824. if (!cert) return "";
  16825. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16826. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16827. if (!subject) return "";
  16828. char cn[256] = {};
  16829. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16830. sizeof(cn));
  16831. if (cn_len <= 0) return "";
  16832. return std::string(cn, static_cast<size_t>(cn_len));
  16833. }
  16834. inline std::string get_cert_issuer_name(cert_t cert) {
  16835. if (!cert) return "";
  16836. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16837. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16838. if (!issuer) return "";
  16839. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16840. if (!name_str) return "";
  16841. std::string result(name_str);
  16842. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16843. return result;
  16844. }
  16845. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16846. sans.clear();
  16847. if (!cert) return false;
  16848. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16849. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16850. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16851. if (!san_names) return true; // No SANs is not an error
  16852. int count = wolfSSL_sk_num(san_names);
  16853. for (int i = 0; i < count; i++) {
  16854. auto *name =
  16855. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16856. if (!name) continue;
  16857. SanEntry entry;
  16858. switch (name->type) {
  16859. case WOLFSSL_GEN_DNS: {
  16860. entry.type = SanType::DNS;
  16861. unsigned char *dns_name = nullptr;
  16862. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16863. if (dns_name && dns_len > 0) {
  16864. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16865. static_cast<size_t>(dns_len));
  16866. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16867. }
  16868. break;
  16869. }
  16870. case WOLFSSL_GEN_IPADD: {
  16871. entry.type = SanType::IP;
  16872. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16873. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16874. if (ip_data && ip_len == 4) {
  16875. char buf[16];
  16876. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16877. ip_data[2], ip_data[3]);
  16878. entry.value = buf;
  16879. } else if (ip_data && ip_len == 16) {
  16880. char buf[64];
  16881. snprintf(buf, sizeof(buf),
  16882. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16883. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16884. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16885. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16886. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16887. ip_data[14], ip_data[15]);
  16888. entry.value = buf;
  16889. }
  16890. break;
  16891. }
  16892. case WOLFSSL_GEN_EMAIL:
  16893. entry.type = SanType::EMAIL;
  16894. {
  16895. unsigned char *email = nullptr;
  16896. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16897. if (email && email_len > 0) {
  16898. entry.value = std::string(reinterpret_cast<char *>(email),
  16899. static_cast<size_t>(email_len));
  16900. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16901. }
  16902. }
  16903. break;
  16904. case WOLFSSL_GEN_URI:
  16905. entry.type = SanType::URI;
  16906. {
  16907. unsigned char *uri = nullptr;
  16908. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16909. &uri, name->d.uniformResourceIdentifier);
  16910. if (uri && uri_len > 0) {
  16911. entry.value = std::string(reinterpret_cast<char *>(uri),
  16912. static_cast<size_t>(uri_len));
  16913. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16914. }
  16915. }
  16916. break;
  16917. default: entry.type = SanType::OTHER; break;
  16918. }
  16919. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16920. }
  16921. wolfSSL_sk_free(san_names);
  16922. return true;
  16923. }
  16924. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16925. time_t &not_after) {
  16926. if (!cert) return false;
  16927. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16928. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16929. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16930. if (!nb || !na) return false;
  16931. // wolfSSL_ASN1_TIME_to_tm is available
  16932. struct tm tm_nb = {}, tm_na = {};
  16933. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16934. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16935. #ifdef _WIN32
  16936. not_before = _mkgmtime(&tm_nb);
  16937. not_after = _mkgmtime(&tm_na);
  16938. #else
  16939. not_before = timegm(&tm_nb);
  16940. not_after = timegm(&tm_na);
  16941. #endif
  16942. return true;
  16943. }
  16944. inline std::string get_cert_serial(cert_t cert) {
  16945. if (!cert) return "";
  16946. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16947. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16948. if (!serial_asn1) return "";
  16949. // Get the serial number data
  16950. int len = serial_asn1->length;
  16951. unsigned char *data = serial_asn1->data;
  16952. if (!data || len <= 0) return "";
  16953. std::string result;
  16954. result.reserve(static_cast<size_t>(len) * 2);
  16955. for (int i = 0; i < len; i++) {
  16956. char hex[3];
  16957. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16958. result += hex;
  16959. }
  16960. return result;
  16961. }
  16962. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16963. if (!cert) return false;
  16964. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16965. int der_len = 0;
  16966. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16967. if (!der_data || der_len <= 0) return false;
  16968. der.assign(der_data, der_data + der_len);
  16969. return true;
  16970. }
  16971. inline const char *get_sni(const_session_t session) {
  16972. if (!session) return nullptr;
  16973. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  16974. // For server: return SNI received from client during handshake
  16975. if (!wsession->sni_hostname.empty()) {
  16976. return wsession->sni_hostname.c_str();
  16977. }
  16978. // For client: return the hostname set via set_sni
  16979. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  16980. return nullptr;
  16981. }
  16982. inline uint64_t peek_error() {
  16983. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16984. }
  16985. inline uint64_t get_error() {
  16986. uint64_t err = impl::wolfssl_last_error();
  16987. impl::wolfssl_last_error() = 0;
  16988. return err;
  16989. }
  16990. inline std::string error_string(uint64_t code) {
  16991. char buf[256];
  16992. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  16993. return std::string(buf);
  16994. }
  16995. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16996. if (!pem || len == 0) { return nullptr; }
  16997. // Validate by attempting to load into a temporary ctx
  16998. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  16999. if (!tmp_ctx) { return nullptr; }
  17000. int ret = wolfSSL_CTX_load_verify_buffer(
  17001. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17002. static_cast<long>(len), SSL_FILETYPE_PEM);
  17003. wolfSSL_CTX_free(tmp_ctx);
  17004. if (ret != SSL_SUCCESS) { return nullptr; }
  17005. return static_cast<ca_store_t>(
  17006. new impl::WolfSSLCAStore{std::string(pem, len)});
  17007. }
  17008. inline void free_ca_store(ca_store_t store) {
  17009. delete static_cast<impl::WolfSSLCAStore *>(store);
  17010. }
  17011. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17012. if (!ctx || !store) { return false; }
  17013. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17014. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17015. int ret = wolfSSL_CTX_load_verify_buffer(
  17016. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17017. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17018. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17019. // This function takes ownership of the store; the PEM data was copied into
  17020. // the context, so release the source
  17021. free_ca_store(store);
  17022. return ret == SSL_SUCCESS;
  17023. }
  17024. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17025. certs.clear();
  17026. if (!ctx) { return 0; }
  17027. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17028. if (wctx->ca_pem_data_.empty()) { return 0; }
  17029. const std::string &pem = wctx->ca_pem_data_;
  17030. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17031. const std::string end_marker = "-----END CERTIFICATE-----";
  17032. size_t pos = 0;
  17033. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17034. size_t end_pos = pem.find(end_marker, pos);
  17035. if (end_pos == std::string::npos) { break; }
  17036. end_pos += end_marker.size();
  17037. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17038. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17039. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17040. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17041. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17042. pos = end_pos;
  17043. }
  17044. return certs.size();
  17045. }
  17046. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17047. std::vector<std::string> names;
  17048. if (!ctx) { return names; }
  17049. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17050. if (wctx->ca_pem_data_.empty()) { return names; }
  17051. const std::string &pem = wctx->ca_pem_data_;
  17052. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17053. const std::string end_marker = "-----END CERTIFICATE-----";
  17054. size_t pos = 0;
  17055. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17056. size_t end_pos = pem.find(end_marker, pos);
  17057. if (end_pos == std::string::npos) { break; }
  17058. end_pos += end_marker.size();
  17059. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17060. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17061. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17062. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17063. if (x509) {
  17064. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17065. if (subject) {
  17066. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17067. if (name_str) {
  17068. names.push_back(name_str);
  17069. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17070. }
  17071. }
  17072. wolfSSL_X509_free(x509);
  17073. }
  17074. pos = end_pos;
  17075. }
  17076. return names;
  17077. }
  17078. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17079. const char *key_pem, const char *password) {
  17080. if (!ctx || !cert_pem || !key_pem) { return false; }
  17081. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17082. // Load new certificate
  17083. int ret = wolfSSL_CTX_use_certificate_buffer(
  17084. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17085. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17086. if (ret != SSL_SUCCESS) {
  17087. impl::wolfssl_last_error() =
  17088. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17089. return false;
  17090. }
  17091. // Set password if provided
  17092. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17093. // Load new private key
  17094. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17095. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17096. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17097. if (ret != SSL_SUCCESS) {
  17098. impl::wolfssl_last_error() =
  17099. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17100. return false;
  17101. }
  17102. return true;
  17103. }
  17104. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17105. if (!ctx || !ca_pem) { return false; }
  17106. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17107. int ret = wolfSSL_CTX_load_verify_buffer(
  17108. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17109. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17110. if (ret != SSL_SUCCESS) {
  17111. impl::wolfssl_last_error() =
  17112. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17113. return false;
  17114. }
  17115. return true;
  17116. }
  17117. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17118. if (!ctx) { return false; }
  17119. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17120. impl::get_verify_callback() = std::move(callback);
  17121. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17122. if (wctx->has_verify_callback) {
  17123. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17124. impl::wolfssl_verify_callback);
  17125. } else {
  17126. wolfSSL_CTX_set_verify(
  17127. wctx->ctx,
  17128. wctx->verify_client
  17129. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17130. : SSL_VERIFY_NONE,
  17131. nullptr);
  17132. }
  17133. return true;
  17134. }
  17135. inline long get_verify_error(const_session_t session) {
  17136. if (!session) { return -1; }
  17137. auto *wsession =
  17138. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17139. return wolfSSL_get_verify_result(wsession->ssl);
  17140. }
  17141. inline std::string verify_error_string(long error_code) {
  17142. if (error_code == 0) { return ""; }
  17143. const char *str =
  17144. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17145. return str ? std::string(str) : std::string();
  17146. }
  17147. } // namespace tls
  17148. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17149. // WebSocket implementation
  17150. namespace ws {
  17151. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17152. bool fin) {
  17153. std::lock_guard<std::mutex> lock(write_mutex_);
  17154. if (closed_) { return false; }
  17155. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17156. }
  17157. inline ReadResult WebSocket::read(std::string &msg) {
  17158. while (!closed_) {
  17159. Opcode opcode;
  17160. std::string payload;
  17161. bool fin;
  17162. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17163. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17164. closed_ = true;
  17165. return Fail;
  17166. }
  17167. switch (opcode) {
  17168. case Opcode::Ping: {
  17169. std::lock_guard<std::mutex> lock(write_mutex_);
  17170. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17171. payload.size(), true, !is_server_);
  17172. continue;
  17173. }
  17174. case Opcode::Pong: {
  17175. std::lock_guard<std::mutex> lock(ping_mutex_);
  17176. unacked_pings_ = 0;
  17177. continue;
  17178. }
  17179. case Opcode::Close: {
  17180. if (!closed_.exchange(true)) {
  17181. // Echo close frame back
  17182. std::lock_guard<std::mutex> lock(write_mutex_);
  17183. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17184. payload.size(), true, !is_server_);
  17185. }
  17186. return Fail;
  17187. }
  17188. case Opcode::Text:
  17189. case Opcode::Binary: {
  17190. auto result = opcode == Opcode::Text ? Text : Binary;
  17191. msg = std::move(payload);
  17192. // Handle fragmentation
  17193. if (!fin) {
  17194. while (true) {
  17195. Opcode cont_opcode;
  17196. std::string cont_payload;
  17197. bool cont_fin;
  17198. if (!impl::read_websocket_frame(
  17199. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17200. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17201. closed_ = true;
  17202. return Fail;
  17203. }
  17204. if (cont_opcode == Opcode::Ping) {
  17205. std::lock_guard<std::mutex> lock(write_mutex_);
  17206. detail::write_websocket_frame(
  17207. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17208. true, !is_server_);
  17209. continue;
  17210. }
  17211. if (cont_opcode == Opcode::Pong) {
  17212. std::lock_guard<std::mutex> lock(ping_mutex_);
  17213. unacked_pings_ = 0;
  17214. continue;
  17215. }
  17216. if (cont_opcode == Opcode::Close) {
  17217. if (!closed_.exchange(true)) {
  17218. std::lock_guard<std::mutex> lock(write_mutex_);
  17219. detail::write_websocket_frame(
  17220. strm_, Opcode::Close, cont_payload.data(),
  17221. cont_payload.size(), true, !is_server_);
  17222. }
  17223. return Fail;
  17224. }
  17225. // RFC 6455: continuation frames must use opcode 0x0
  17226. if (cont_opcode != Opcode::Continuation) {
  17227. closed_ = true;
  17228. return Fail;
  17229. }
  17230. msg += cont_payload;
  17231. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17232. closed_ = true;
  17233. return Fail;
  17234. }
  17235. if (cont_fin) { break; }
  17236. }
  17237. }
  17238. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17239. if (result == Text && !impl::is_valid_utf8(msg)) {
  17240. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17241. return Fail;
  17242. }
  17243. return result;
  17244. }
  17245. default: closed_ = true; return Fail;
  17246. }
  17247. }
  17248. return Fail;
  17249. }
  17250. inline bool WebSocket::send(const std::string &data) {
  17251. return send_frame(Opcode::Text, data.data(), data.size());
  17252. }
  17253. inline bool WebSocket::send(const char *data, size_t len) {
  17254. return send_frame(Opcode::Binary, data, len);
  17255. }
  17256. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17257. if (closed_.exchange(true)) { return; }
  17258. ping_cv_.notify_all();
  17259. std::string payload;
  17260. auto code = static_cast<uint16_t>(status);
  17261. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17262. payload.push_back(static_cast<char>(code & 0xFF));
  17263. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17264. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17265. payload += reason.substr(0, 123);
  17266. {
  17267. std::lock_guard<std::mutex> lock(write_mutex_);
  17268. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17269. payload.size(), true, !is_server_);
  17270. }
  17271. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17272. // Close response before closing the TCP connection. Use a short timeout to
  17273. // avoid hanging if the peer doesn't respond.
  17274. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17275. Opcode op;
  17276. std::string resp;
  17277. bool fin;
  17278. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17279. if (op == Opcode::Close) { break; }
  17280. }
  17281. }
  17282. inline WebSocket::~WebSocket() {
  17283. {
  17284. std::lock_guard<std::mutex> lock(ping_mutex_);
  17285. closed_ = true;
  17286. }
  17287. ping_cv_.notify_all();
  17288. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17289. }
  17290. inline void WebSocket::start_heartbeat() {
  17291. if (ping_interval_sec_ == 0) { return; }
  17292. ping_thread_ = std::thread([this]() {
  17293. std::unique_lock<std::mutex> lock(ping_mutex_);
  17294. while (!closed_) {
  17295. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17296. if (closed_) { break; }
  17297. // If the peer has failed to respond to the previous pings, give up.
  17298. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17299. // opt-in liveness check controlled by max_missed_pongs_.
  17300. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17301. lock.unlock();
  17302. close(CloseStatus::GoingAway, "pong timeout");
  17303. return;
  17304. }
  17305. lock.unlock();
  17306. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17307. lock.lock();
  17308. closed_ = true;
  17309. break;
  17310. }
  17311. lock.lock();
  17312. unacked_pings_++;
  17313. }
  17314. });
  17315. }
  17316. inline const Request &WebSocket::request() const { return req_; }
  17317. inline bool WebSocket::is_open() const { return !closed_; }
  17318. // WebSocketClient implementation
  17319. inline WebSocketClient::WebSocketClient(
  17320. const std::string &scheme_host_port_path, const Headers &headers)
  17321. : headers_(headers) {
  17322. detail::UrlComponents uc;
  17323. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17324. !uc.host.empty() && !uc.path.empty()) {
  17325. auto &scheme = uc.scheme;
  17326. #ifdef CPPHTTPLIB_SSL_ENABLED
  17327. if (scheme != "ws" && scheme != "wss") {
  17328. #else
  17329. if (scheme != "ws") {
  17330. #endif
  17331. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17332. std::string msg = "'" + scheme + "' scheme is not supported.";
  17333. throw std::invalid_argument(msg);
  17334. #endif
  17335. return;
  17336. }
  17337. auto is_ssl = scheme == "wss";
  17338. host_ = std::move(uc.host);
  17339. port_ = is_ssl ? 443 : 80;
  17340. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17341. path_ = std::move(uc.path);
  17342. if (!uc.query.empty()) { path_ += uc.query; }
  17343. #ifdef CPPHTTPLIB_SSL_ENABLED
  17344. is_ssl_ = is_ssl;
  17345. if (is_ssl_) {
  17346. // The context lives as long as the client so that CA configuration
  17347. // survives reconnects; sessions are created per connection.
  17348. tls_ctx_ = tls::create_client_context();
  17349. if (!tls_ctx_) { return; }
  17350. }
  17351. #else
  17352. if (is_ssl) { return; }
  17353. #endif
  17354. is_valid_ = true;
  17355. }
  17356. }
  17357. inline WebSocketClient::~WebSocketClient() {
  17358. shutdown_and_close();
  17359. #ifdef CPPHTTPLIB_SSL_ENABLED
  17360. if (tls_ctx_) {
  17361. tls::free_context(tls_ctx_);
  17362. tls_ctx_ = nullptr;
  17363. }
  17364. #endif
  17365. }
  17366. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17367. inline void WebSocketClient::shutdown_and_close() {
  17368. #ifdef CPPHTTPLIB_SSL_ENABLED
  17369. if (is_ssl_) {
  17370. if (tls_session_) {
  17371. tls::shutdown(tls_session_, true);
  17372. tls::free_session(tls_session_);
  17373. tls_session_ = nullptr;
  17374. }
  17375. }
  17376. #endif
  17377. if (ws_ && ws_->is_open()) { ws_->close(); }
  17378. ws_.reset();
  17379. if (sock_ != INVALID_SOCKET) {
  17380. detail::shutdown_socket(sock_);
  17381. detail::close_socket(sock_);
  17382. sock_ = INVALID_SOCKET;
  17383. }
  17384. }
  17385. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17386. #ifdef CPPHTTPLIB_SSL_ENABLED
  17387. if (is_ssl_) {
  17388. if (server_certificate_verification_ && !certs_loaded_) {
  17389. uint64_t backend_error = 0;
  17390. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17391. custom_ca_loaded_, system_ca_mode_,
  17392. backend_error);
  17393. certs_loaded_ = true;
  17394. }
  17395. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17396. server_certificate_verification_,
  17397. read_timeout_sec_,
  17398. read_timeout_usec_)) {
  17399. return false;
  17400. }
  17401. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17402. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17403. write_timeout_sec_, write_timeout_usec_));
  17404. return true;
  17405. }
  17406. #endif
  17407. strm = std::unique_ptr<Stream>(
  17408. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17409. write_timeout_sec_, write_timeout_usec_));
  17410. return true;
  17411. }
  17412. inline bool WebSocketClient::connect() {
  17413. if (!is_valid_) { return false; }
  17414. shutdown_and_close();
  17415. // Check is custom IP specified for host_
  17416. std::string ip;
  17417. auto it = addr_map_.find(host_);
  17418. if (it != addr_map_.end()) { ip = it->second; }
  17419. Error error;
  17420. sock_ = detail::create_client_socket(
  17421. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17422. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17423. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17424. write_timeout_usec_, interface_, error);
  17425. if (sock_ == INVALID_SOCKET) { return false; }
  17426. std::unique_ptr<Stream> strm;
  17427. if (!create_stream(strm)) {
  17428. shutdown_and_close();
  17429. return false;
  17430. }
  17431. std::string selected_subprotocol;
  17432. if (!detail::perform_websocket_handshake(*strm, host_, port_, path_, headers_,
  17433. selected_subprotocol)) {
  17434. shutdown_and_close();
  17435. return false;
  17436. }
  17437. subprotocol_ = std::move(selected_subprotocol);
  17438. Request req;
  17439. req.method = "GET";
  17440. req.path = path_;
  17441. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17442. websocket_ping_interval_sec_,
  17443. websocket_max_missed_pongs_));
  17444. return true;
  17445. }
  17446. inline ReadResult WebSocketClient::read(std::string &msg) {
  17447. if (!ws_) { return Fail; }
  17448. return ws_->read(msg);
  17449. }
  17450. inline bool WebSocketClient::send(const std::string &data) {
  17451. if (!ws_) { return false; }
  17452. return ws_->send(data);
  17453. }
  17454. inline bool WebSocketClient::send(const char *data, size_t len) {
  17455. if (!ws_) { return false; }
  17456. return ws_->send(data, len);
  17457. }
  17458. inline void WebSocketClient::close(CloseStatus status,
  17459. const std::string &reason) {
  17460. if (ws_) { ws_->close(status, reason); }
  17461. }
  17462. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17463. inline const std::string &WebSocketClient::subprotocol() const {
  17464. return subprotocol_;
  17465. }
  17466. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17467. read_timeout_sec_ = sec;
  17468. read_timeout_usec_ = usec;
  17469. }
  17470. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17471. write_timeout_sec_ = sec;
  17472. write_timeout_usec_ = usec;
  17473. }
  17474. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17475. websocket_ping_interval_sec_ = sec;
  17476. }
  17477. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17478. websocket_max_missed_pongs_ = count;
  17479. }
  17480. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17481. inline void WebSocketClient::set_address_family(int family) {
  17482. address_family_ = family;
  17483. }
  17484. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17485. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17486. socket_options_ = std::move(socket_options);
  17487. }
  17488. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17489. connection_timeout_sec_ = sec;
  17490. connection_timeout_usec_ = usec;
  17491. }
  17492. inline void WebSocketClient::set_interface(const std::string &intf) {
  17493. interface_ = intf;
  17494. }
  17495. inline void WebSocketClient::set_hostname_addr_map(
  17496. std::map<std::string, std::string> addr_map) {
  17497. addr_map_ = std::move(addr_map);
  17498. }
  17499. #ifdef CPPHTTPLIB_SSL_ENABLED
  17500. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17501. ca_cert_file_path_ = path;
  17502. }
  17503. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17504. if (store && tls_ctx_) {
  17505. // set_ca_store takes ownership of store
  17506. tls::set_ca_store(tls_ctx_, store);
  17507. custom_ca_loaded_ = true;
  17508. } else if (store) {
  17509. tls::free_ca_store(store);
  17510. }
  17511. }
  17512. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17513. std::size_t size) {
  17514. if (tls_ctx_ && ca_cert && size > 0) {
  17515. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17516. custom_ca_loaded_ = true;
  17517. }
  17518. }
  17519. inline void
  17520. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17521. server_certificate_verification_ = enabled;
  17522. }
  17523. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17524. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17525. }
  17526. #endif // CPPHTTPLIB_SSL_ENABLED
  17527. } // namespace ws
  17528. // ----------------------------------------------------------------------------
  17529. } // namespace httplib
  17530. #endif // CPPHTTPLIB_HTTPLIB_H