httplib.h 886 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671
  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.67.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x004300"
  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. #if defined(__SANITIZE_THREAD__)
  18. #define CPPHTTPLIB_THREAD_SANITIZER
  19. #elif defined(__has_feature)
  20. #if __has_feature(thread_sanitizer)
  21. #define CPPHTTPLIB_THREAD_SANITIZER
  22. #endif
  23. #endif
  24. /*
  25. * Configuration
  26. */
  27. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  28. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  29. #endif
  30. // Whether a Server starts with set_keep_alive_parking(true).
  31. #ifndef CPPHTTPLIB_KEEPALIVE_PARKING
  32. #define CPPHTTPLIB_KEEPALIVE_PARKING false
  33. #endif
  34. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  35. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  36. #endif
  37. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  38. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  39. #endif
  40. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  41. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  42. #endif
  43. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  44. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  45. #endif
  46. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  47. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  48. #endif
  49. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  50. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  51. #endif
  52. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  53. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  54. #endif
  55. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  56. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  57. #endif
  58. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  59. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  60. #endif
  61. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  62. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  63. #endif
  64. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  65. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  66. #endif
  67. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  68. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  69. #endif
  70. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  71. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  72. #endif
  73. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  74. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  75. #endif
  76. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  77. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  78. #endif
  79. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  80. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  81. #endif
  82. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  83. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  84. #endif
  85. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  86. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  87. #endif
  88. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  89. #ifdef _WIN32
  90. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  91. #else
  92. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  93. #endif
  94. #endif
  95. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  96. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  97. #endif
  98. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  99. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  100. #endif
  101. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  102. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  103. #endif
  104. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  105. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  106. #endif
  107. #ifndef CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT
  108. #define CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT 100
  109. #endif
  110. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  111. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  112. #endif
  113. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  114. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  115. #endif
  116. // How much of an unread request body the server skips to reuse the connection,
  117. // 0 for no limit
  118. #ifndef CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH
  119. #define CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH (256 * 1024) // 256KB
  120. #endif
  121. #ifndef CPPHTTPLIB_SSE_MAX_EVENT_LENGTH
  122. #define CPPHTTPLIB_SSE_MAX_EVENT_LENGTH (16 * 1024 * 1024) // 16MB
  123. #endif
  124. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  125. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  126. #endif
  127. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH
  128. // 1400 rather than a round number: a body that already fits in one 1500-byte
  129. // MTU gains nothing from being made smaller.
  130. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH 1400
  131. #endif
  132. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH
  133. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH (4 * 1024 * 1024) // 4MB
  134. #endif
  135. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  136. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  137. #endif
  138. // std::regex_match's backtracking implementation (most acutely on libstdc++)
  139. // recurses roughly once per matched character for quantified patterns such
  140. // as "(.*)", so a long enough path can exhaust the calling thread's stack; on
  141. // a default ~8MB thread stack that has been observed to take on the order of
  142. // a couple thousand characters for a simple pattern. 256 leaves a wide safety
  143. // margin below that (well under the 8192-byte request URI limit) while still
  144. // fitting any realistic route segment; raise it if a route legitimately needs
  145. // longer paths. Regex routes are never applied to paths longer than this.
  146. #ifndef CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH
  147. #define CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH 256
  148. #endif
  149. #ifndef CPPHTTPLIB_TCP_NODELAY
  150. #define CPPHTTPLIB_TCP_NODELAY false
  151. #endif
  152. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  153. #define CPPHTTPLIB_IPV6_V6ONLY false
  154. #endif
  155. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  156. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  157. #endif
  158. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  159. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  160. #endif
  161. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  162. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  163. #endif
  164. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  165. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  166. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  167. ? std::thread::hardware_concurrency() - 1 \
  168. : 0))
  169. #endif
  170. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  171. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  172. #endif
  173. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  174. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  175. #endif
  176. #ifndef CPPHTTPLIB_RECV_FLAGS
  177. #define CPPHTTPLIB_RECV_FLAGS 0
  178. #endif
  179. #ifndef CPPHTTPLIB_SEND_FLAGS
  180. #define CPPHTTPLIB_SEND_FLAGS 0
  181. #endif
  182. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  183. #define CPPHTTPLIB_LISTEN_BACKLOG 128
  184. #endif
  185. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  186. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  187. #endif
  188. // These bound the parsing of every request, so 0 cannot lift them.
  189. static_assert(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH > 0,
  190. "CPPHTTPLIB_REQUEST_URI_MAX_LENGTH must be positive");
  191. static_assert(CPPHTTPLIB_HEADER_MAX_LENGTH > 0,
  192. "CPPHTTPLIB_HEADER_MAX_LENGTH must be positive");
  193. static_assert(CPPHTTPLIB_HEADER_MAX_COUNT > 0,
  194. "CPPHTTPLIB_HEADER_MAX_COUNT must be positive");
  195. static_assert(CPPHTTPLIB_MAX_LINE_LENGTH > 0,
  196. "CPPHTTPLIB_MAX_LINE_LENGTH must be positive");
  197. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  198. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  199. #endif
  200. // One macro used to set the read timeout for both sides. They want different
  201. // defaults: a client's read timeout is the caller's own tool (it waits forever
  202. // until asked not to), while a server keeps a ceiling that reclaims a worker
  203. // from a peer that has gone quiet. The old name still works and sets both.
  204. #ifdef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  205. #pragma message( \
  206. "CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND is deprecated; define " \
  207. "CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND and/or " \
  208. "CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND instead")
  209. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  210. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND \
  211. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  212. #endif
  213. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  214. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND \
  215. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  216. #endif
  217. #endif
  218. // 0 waits forever. A read timeout is how a caller gets control back to send on
  219. // the same connection; it is not a liveness check (that is ping/pong). Only a
  220. // timeout set at runtime through set_read_timeout() is reported as
  221. // ws::Timeout; when one of these compile-time defaults elapses, read() returns
  222. // ws::Fail and closes the connection.
  223. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  224. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 0
  225. #endif
  226. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  227. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 300
  228. #endif
  229. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  230. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  231. #endif
  232. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  233. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  234. #endif
  235. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  236. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  237. #endif
  238. // A WebSocket connection carries small messages each way, which Nagle's
  239. // algorithm would hold back for the peer's delayed ACK (tens of milliseconds
  240. // on Linux), so it sets TCP_NODELAY unless this is false.
  241. #ifndef CPPHTTPLIB_WEBSOCKET_TCP_NODELAY
  242. #define CPPHTTPLIB_WEBSOCKET_TCP_NODELAY true
  243. #endif
  244. /*
  245. * Headers
  246. */
  247. #ifdef _WIN32
  248. #ifndef _CRT_SECURE_NO_WARNINGS
  249. #define _CRT_SECURE_NO_WARNINGS
  250. #endif //_CRT_SECURE_NO_WARNINGS
  251. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  252. #define _CRT_NONSTDC_NO_DEPRECATE
  253. #endif //_CRT_NONSTDC_NO_DEPRECATE
  254. #if defined(_MSC_VER)
  255. #if _MSC_VER < 1900
  256. #error Sorry, Visual Studio versions prior to 2015 are not supported
  257. #endif
  258. #pragma comment(lib, "ws2_32.lib")
  259. #ifndef _SSIZE_T_DEFINED
  260. using ssize_t = __int64;
  261. #define _SSIZE_T_DEFINED
  262. #endif
  263. #endif // _MSC_VER
  264. #ifndef S_ISREG
  265. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  266. #endif // S_ISREG
  267. #ifndef S_ISDIR
  268. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  269. #endif // S_ISDIR
  270. #ifndef NOMINMAX
  271. #define NOMINMAX
  272. #endif // NOMINMAX
  273. #include <io.h>
  274. #include <winsock2.h>
  275. #include <ws2tcpip.h>
  276. #if defined(__has_include)
  277. #if __has_include(<afunix.h>)
  278. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  279. #include <afunix.h>
  280. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  281. #endif
  282. #endif
  283. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  284. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  285. #endif
  286. using nfds_t = unsigned long;
  287. using socket_t = SOCKET;
  288. using socklen_t = int;
  289. #else // not _WIN32
  290. #include <arpa/inet.h>
  291. #if !defined(_AIX) && !defined(__MVS__)
  292. #include <ifaddrs.h>
  293. #endif
  294. #ifdef __MVS__
  295. #include <strings.h>
  296. #ifndef NI_MAXHOST
  297. #define NI_MAXHOST 1025
  298. #endif
  299. #endif
  300. #include <net/if.h>
  301. #include <netdb.h>
  302. #include <netinet/in.h>
  303. #ifdef __linux__
  304. #include <resolv.h>
  305. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  306. #include <sys/epoll.h>
  307. #include <sys/eventfd.h>
  308. #endif
  309. #include <csignal>
  310. #include <netinet/tcp.h>
  311. #include <poll.h>
  312. #include <pthread.h>
  313. #include <sys/socket.h>
  314. #include <sys/un.h>
  315. #include <unistd.h>
  316. using socket_t = int;
  317. #ifndef INVALID_SOCKET
  318. #define INVALID_SOCKET (-1)
  319. #endif
  320. #endif //_WIN32
  321. #if defined(__APPLE__)
  322. #include <TargetConditionals.h>
  323. #endif
  324. #if defined(__APPLE__) || defined(__FreeBSD__)
  325. #define CPPHTTPLIB_KQUEUE_POLLER
  326. #include <sys/event.h>
  327. #endif
  328. #include <algorithm>
  329. #include <array>
  330. #include <atomic>
  331. #include <cassert>
  332. #include <chrono>
  333. #include <climits>
  334. #include <condition_variable>
  335. #include <cstdlib>
  336. #include <cstring>
  337. #include <errno.h>
  338. #include <exception>
  339. #include <fcntl.h>
  340. #include <fstream>
  341. #include <functional>
  342. #include <iomanip>
  343. #include <iostream>
  344. #include <iterator>
  345. #include <list>
  346. #include <map>
  347. #include <memory>
  348. #include <mutex>
  349. #include <random>
  350. #include <regex>
  351. #include <set>
  352. #include <sstream>
  353. #include <string>
  354. #include <sys/stat.h>
  355. #include <system_error>
  356. #include <thread>
  357. #include <type_traits>
  358. #include <unordered_map>
  359. #include <unordered_set>
  360. #include <utility>
  361. #include <vector>
  362. // On macOS with a TLS backend, enable Keychain root certificates by default
  363. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  364. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  365. // only; on those platforms the user must provide a CA bundle explicitly.
  366. #if defined(__APPLE__) && defined(__clang__) && \
  367. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  368. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  369. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  370. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  371. #if TARGET_OS_OSX
  372. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  373. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  374. #endif
  375. #endif
  376. #endif
  377. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  378. defined(__APPLE__) && !TARGET_OS_OSX
  379. #error \
  380. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  381. #endif
  382. // On Windows, enable Schannel certificate verification by default
  383. // unless the user explicitly opts out.
  384. #if defined(_WIN32) && \
  385. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  386. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  387. #endif
  388. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  389. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  390. #if TARGET_OS_MAC && defined(__clang__)
  391. #include <CFNetwork/CFHost.h>
  392. #include <CoreFoundation/CoreFoundation.h>
  393. #endif
  394. #endif
  395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  396. #ifdef _WIN32
  397. #include <wincrypt.h>
  398. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  399. // used
  400. #undef X509_NAME
  401. #undef X509_CERT_PAIR
  402. #undef X509_EXTENSIONS
  403. #undef PKCS7_SIGNER_INFO
  404. #ifdef _MSC_VER
  405. #pragma comment(lib, "crypt32.lib")
  406. #endif
  407. #endif // _WIN32
  408. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  409. #if TARGET_OS_OSX
  410. #include <Security/Security.h>
  411. #endif
  412. #endif
  413. #include <openssl/err.h>
  414. #include <openssl/evp.h>
  415. #include <openssl/rand.h>
  416. #include <openssl/ssl.h>
  417. #include <openssl/x509v3.h>
  418. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  419. #include <openssl/applink.c>
  420. #endif
  421. #include <iostream>
  422. #include <sstream>
  423. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  424. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  425. #error Please use OpenSSL or a current version of BoringSSL
  426. #endif
  427. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  428. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  429. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  430. #endif
  431. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  432. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  433. // version.h defines MBEDTLS_VERSION_MAJOR (on 2.x/3.x/4.x alike); it is pulled
  434. // in with this first include group so the version gating below can use it.
  435. #include <mbedtls/error.h>
  436. #include <mbedtls/net_sockets.h>
  437. #include <mbedtls/oid.h>
  438. #include <mbedtls/pk.h>
  439. #include <mbedtls/ssl.h>
  440. #include <mbedtls/version.h>
  441. #include <mbedtls/x509_crt.h>
  442. #if MBEDTLS_VERSION_MAJOR >= 4
  443. // Mbed TLS 4.x moved hashing/RNG to PSA Crypto and removed these headers.
  444. #include <psa/crypto.h>
  445. #else
  446. #include <mbedtls/ctr_drbg.h>
  447. #include <mbedtls/entropy.h>
  448. #include <mbedtls/md5.h>
  449. #include <mbedtls/sha1.h>
  450. #include <mbedtls/sha256.h>
  451. #include <mbedtls/sha512.h>
  452. #endif
  453. #ifdef _WIN32
  454. #include <wincrypt.h>
  455. #ifdef _MSC_VER
  456. #pragma comment(lib, "crypt32.lib")
  457. #endif
  458. #endif // _WIN32
  459. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  460. #if TARGET_OS_OSX
  461. #include <Security/Security.h>
  462. #endif
  463. #endif
  464. // Mbed TLS version API compatibility. Note: V4 implies V3 (both defined on
  465. // 4.x), so version-specific 3.x-only code must check V3 && !V4.
  466. #if MBEDTLS_VERSION_MAJOR >= 4
  467. #define CPPHTTPLIB_MBEDTLS_V4
  468. #endif
  469. #if MBEDTLS_VERSION_MAJOR >= 3
  470. #define CPPHTTPLIB_MBEDTLS_V3
  471. #endif
  472. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  473. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  474. #include <wolfssl/options.h>
  475. #include <wolfssl/openssl/x509v3.h>
  476. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  477. #ifndef WOLFSSL_GEN_EMAIL
  478. #define WOLFSSL_GEN_EMAIL 1
  479. #endif
  480. #ifndef WOLFSSL_GEN_DNS
  481. #define WOLFSSL_GEN_DNS 2
  482. #endif
  483. #ifndef WOLFSSL_GEN_URI
  484. #define WOLFSSL_GEN_URI 6
  485. #endif
  486. #ifndef WOLFSSL_GEN_IPADD
  487. #define WOLFSSL_GEN_IPADD 7
  488. #endif
  489. #include <wolfssl/ssl.h>
  490. #include <wolfssl/wolfcrypt/hash.h>
  491. #include <wolfssl/wolfcrypt/md5.h>
  492. #include <wolfssl/wolfcrypt/sha256.h>
  493. #include <wolfssl/wolfcrypt/sha512.h>
  494. #ifdef _WIN32
  495. #include <wincrypt.h>
  496. #ifdef _MSC_VER
  497. #pragma comment(lib, "crypt32.lib")
  498. #endif
  499. #endif // _WIN32
  500. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  501. #if TARGET_OS_OSX
  502. #include <Security/Security.h>
  503. #endif
  504. #endif
  505. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  506. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  507. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  508. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  509. #define CPPHTTPLIB_SSL_ENABLED
  510. #endif
  511. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  512. #include <zlib.h>
  513. #endif
  514. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  515. #include <brotli/decode.h>
  516. #include <brotli/encode.h>
  517. #endif
  518. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  519. #include <zstd.h>
  520. #endif
  521. /*
  522. * Declaration
  523. */
  524. namespace httplib {
  525. namespace ws {
  526. class WebSocket;
  527. } // namespace ws
  528. namespace sse {
  529. class SSEClient;
  530. } // namespace sse
  531. namespace detail {
  532. /*
  533. * Backport std::make_unique from C++14.
  534. *
  535. * NOTE: This code came up with the following stackoverflow post:
  536. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  537. *
  538. */
  539. template <class T, class... Args>
  540. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  541. make_unique(Args &&...args) {
  542. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  543. }
  544. template <class T>
  545. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  546. make_unique(std::size_t n) {
  547. typedef typename std::remove_extent<T>::type RT;
  548. return std::unique_ptr<T>(new RT[n]);
  549. }
  550. // Locale-independent ASCII character classification. The <cctype>
  551. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  552. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  553. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  554. // classified without regard to the locale.
  555. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  556. inline bool is_ascii_alpha(char c) {
  557. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  558. }
  559. inline bool is_ascii_alnum(char c) {
  560. return is_ascii_digit(c) || is_ascii_alpha(c);
  561. }
  562. namespace case_ignore {
  563. inline unsigned char to_lower(int c) {
  564. const static unsigned char table[256] = {
  565. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  566. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  567. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  568. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  569. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  570. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  571. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  572. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  573. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  574. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  575. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  576. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  577. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  578. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  579. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  580. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  581. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  582. 255,
  583. };
  584. return table[(unsigned char)(char)c];
  585. }
  586. inline std::string to_lower(const std::string &s) {
  587. std::string result = s;
  588. std::transform(
  589. result.begin(), result.end(), result.begin(),
  590. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  591. return result;
  592. }
  593. inline bool equal(const std::string &a, const std::string &b) {
  594. return a.size() == b.size() &&
  595. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  596. return to_lower(ca) == to_lower(cb);
  597. });
  598. }
  599. // For a literal, without building a std::string from it.
  600. template <size_t N>
  601. inline bool equal(const std::string &a, const char (&b)[N]) {
  602. return a.size() == N - 1 &&
  603. std::equal(a.begin(), a.end(), b, [](char ca, char cb) {
  604. return to_lower(ca) == to_lower(cb);
  605. });
  606. }
  607. struct equal_to {
  608. bool operator()(const std::string &a, const std::string &b) const {
  609. return equal(a, b);
  610. }
  611. };
  612. struct hash {
  613. size_t operator()(const std::string &key) const {
  614. size_t h = 0;
  615. for (auto c : key) {
  616. // Unsets the 6 high bits of h, therefore no overflow happens
  617. h = (((std::numeric_limits<size_t>::max)() >> 6) & h * 33) ^
  618. static_cast<unsigned char>(to_lower(c));
  619. }
  620. return h;
  621. }
  622. };
  623. template <typename T>
  624. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  625. detail::case_ignore::equal_to>;
  626. } // namespace case_ignore
  627. // This is based on
  628. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  629. struct scope_exit {
  630. explicit scope_exit(std::function<void(void)> &&f)
  631. : exit_function(std::move(f)), execute_on_destruction{true} {}
  632. scope_exit(scope_exit &&rhs) noexcept
  633. : exit_function(std::move(rhs.exit_function)),
  634. execute_on_destruction{rhs.execute_on_destruction} {
  635. rhs.release();
  636. }
  637. ~scope_exit() {
  638. if (execute_on_destruction) { this->exit_function(); }
  639. }
  640. void release() { this->execute_on_destruction = false; }
  641. private:
  642. scope_exit(const scope_exit &) = delete;
  643. void operator=(const scope_exit &) = delete;
  644. scope_exit &operator=(scope_exit &&) = delete;
  645. std::function<void(void)> exit_function;
  646. bool execute_on_destruction;
  647. };
  648. // Simple from_chars implementation for integer and double types (C++17
  649. // substitute)
  650. template <typename T> struct from_chars_result {
  651. const char *ptr;
  652. std::errc ec;
  653. };
  654. template <typename T>
  655. inline from_chars_result<T> from_chars(const char *first, const char *last,
  656. T &value, int base = 10) {
  657. value = 0;
  658. const char *p = first;
  659. bool negative = false;
  660. if (p != last && *p == '-') {
  661. negative = true;
  662. ++p;
  663. }
  664. if (p == last) { return {first, std::errc::invalid_argument}; }
  665. auto radix = static_cast<T>(base);
  666. T result = 0;
  667. for (; p != last; ++p) {
  668. char c = *p;
  669. int digit = -1;
  670. if (is_ascii_digit(c)) {
  671. digit = c - '0';
  672. } else if ('a' <= c && c <= 'z') {
  673. digit = c - 'a' + 10;
  674. } else if ('A' <= c && c <= 'Z') {
  675. digit = c - 'A' + 10;
  676. } else {
  677. break;
  678. }
  679. if (digit < 0 || digit >= base) { break; }
  680. auto d = static_cast<T>(digit);
  681. if (result > ((std::numeric_limits<T>::max)() - d) / radix) {
  682. return {p, std::errc::result_out_of_range};
  683. }
  684. result = result * radix + d;
  685. }
  686. if (p == first || (negative && p == first + 1)) {
  687. return {first, std::errc::invalid_argument};
  688. }
  689. value = negative ? T(0) - result : result;
  690. return {p, std::errc{}};
  691. }
  692. // from_chars for double (hand-written, locale-independent)
  693. //
  694. // The only double consumed by this library is the HTTP quality value, whose
  695. // grammar is (RFC 9110 12.4.2):
  696. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  697. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  698. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  699. // '.' always the decimal separator (std::strtod would instead read it from the
  700. // global C locale, mis-parsing q-values once an embedder calls
  701. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  702. // the result to [0, 1], so inputs outside that range need not be distinguished
  703. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  704. // cases that exponent and wide-range handling would introduce.
  705. inline from_chars_result<double> from_chars(const char *first, const char *last,
  706. double &value) {
  707. value = 0.0;
  708. const char *p = first;
  709. // Each 1eN is exactly representable, so a single final division by the
  710. // matching entry yields a correctly-rounded result.
  711. static const double powers_of_ten[] = {
  712. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  713. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  714. const int max_frac_digits =
  715. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  716. // Accumulate digits into a 64-bit integer and remember how many were
  717. // fractional. Two independent caps keep this bounded and safe:
  718. // * accumulation saturates before mantissa could overflow uint64_t, and
  719. // * frac_digits is capped at max_frac_digits so it is always a valid index
  720. // into powers_of_ten (without this an input like "0.000...0" would never
  721. // grow mantissa, so the saturation cap alone would not bound it).
  722. // Both caps only drop digits far beyond the precision a q-value needs; any
  723. // value they would change is well outside [0, 1] and rejected by the caller.
  724. uint64_t mantissa = 0;
  725. int frac_digits = 0;
  726. bool seen_digit = false;
  727. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  728. auto accumulate = [&](char c) {
  729. if (mantissa <= limit) {
  730. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  731. return true;
  732. }
  733. return false;
  734. };
  735. for (; p != last && is_ascii_digit(*p); ++p) {
  736. seen_digit = true;
  737. accumulate(*p);
  738. }
  739. if (p != last && *p == '.') {
  740. ++p;
  741. for (; p != last && is_ascii_digit(*p); ++p) {
  742. seen_digit = true;
  743. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  744. }
  745. }
  746. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  747. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  748. return {p, std::errc{}};
  749. }
  750. inline bool parse_int_in_range(const char *s, size_t len, int lo, int hi,
  751. int &out) {
  752. int val = 0;
  753. auto r = from_chars(s, s + len, val);
  754. if (r.ec != std::errc{} || r.ptr != s + len || val < lo || val > hi) {
  755. return false;
  756. }
  757. out = val;
  758. return true;
  759. }
  760. inline bool parse_port(const char *s, size_t len, int &port) {
  761. return parse_int_in_range(s, len, 1, 65535, port);
  762. }
  763. inline bool parse_port(const std::string &s, int &port) {
  764. return parse_port(s.data(), s.size(), port);
  765. }
  766. struct UrlComponents {
  767. std::string scheme;
  768. std::string host;
  769. std::string port;
  770. std::string path;
  771. std::string query;
  772. };
  773. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  774. uc = {};
  775. size_t pos = 0;
  776. auto sep = url.find("://");
  777. if (sep != std::string::npos) {
  778. // Schemes are case-insensitive (RFC 3986 3.1)
  779. uc.scheme = case_ignore::to_lower(url.substr(0, sep));
  780. // Scheme must be [a-z]+ only
  781. if (uc.scheme.empty()) { return false; }
  782. for (auto c : uc.scheme) {
  783. if (c < 'a' || c > 'z') { return false; }
  784. }
  785. pos = sep + 3;
  786. } else if (url.compare(0, 2, "//") == 0) {
  787. pos = 2;
  788. }
  789. auto has_authority_prefix = pos > 0;
  790. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  791. url[0] != '?' && url[0] != '#');
  792. if (has_authority) {
  793. // userinfo is not supported, and a backslash that some parsers take for
  794. // '/' would leave them seeing another host than this one.
  795. if (url.find_first_of("@\\", pos) < url.find_first_of("/?#", pos)) {
  796. return false;
  797. }
  798. if (pos < url.size() && url[pos] == '[') {
  799. auto close = url.find(']', pos);
  800. if (close == std::string::npos) { return false; }
  801. uc.host = url.substr(pos + 1, close - pos - 1);
  802. // IPv6 host must be [a-fA-F0-9:]+ only
  803. if (uc.host.empty()) { return false; }
  804. for (auto c : uc.host) {
  805. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  806. (c >= 'A' && c <= 'F') || c == ':')) {
  807. return false;
  808. }
  809. }
  810. pos = close + 1;
  811. // The IPv6 literal is the whole host, so ']' must be followed by a port,
  812. // path, query or fragment delimiter (or the end of input). Otherwise the
  813. // trailing bytes would be folded into the path while the connection
  814. // still targets the bracketed address.
  815. if (pos < url.size()) {
  816. auto c = url[pos];
  817. if (c != ':' && c != '/' && c != '?' && c != '#') { return false; }
  818. }
  819. } else {
  820. auto end = url.find_first_of(":/?#", pos);
  821. if (end == std::string::npos) { end = url.size(); }
  822. uc.host = url.substr(pos, end - pos);
  823. pos = end;
  824. }
  825. if (pos < url.size() && url[pos] == ':') {
  826. ++pos;
  827. auto end = url.find_first_of("/?#", pos);
  828. if (end == std::string::npos) { end = url.size(); }
  829. uc.port = url.substr(pos, end - pos);
  830. pos = end;
  831. }
  832. // Without :// or //, the entire input must be consumed as host[:port].
  833. // If there is leftover (path, query, etc.), this is not a valid
  834. // host[:port] string — clear and reparse as a plain path.
  835. if (!has_authority_prefix && pos < url.size()) {
  836. uc.host.clear();
  837. uc.port.clear();
  838. pos = 0;
  839. }
  840. }
  841. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  842. auto end = url.find_first_of("?#", pos);
  843. if (end == std::string::npos) { end = url.size(); }
  844. uc.path = url.substr(pos, end - pos);
  845. pos = end;
  846. }
  847. if (pos < url.size() && url[pos] == '?') {
  848. auto end = url.find('#', pos);
  849. if (end == std::string::npos) { end = url.size(); }
  850. uc.query = url.substr(pos, end - pos);
  851. }
  852. return true;
  853. }
  854. // Removes "." and ".." segments from a path that starts with '/' (RFC 3986
  855. // section 5.2.4).
  856. inline std::string remove_dot_segments(const std::string &path) {
  857. std::string out;
  858. size_t i = 0;
  859. while (i < path.size()) {
  860. auto next = (std::min)(path.find('/', i + 1), path.size());
  861. auto segment = path.substr(i + 1, next - i - 1);
  862. auto is_last = next == path.size();
  863. if (segment == "." || segment == "..") {
  864. if (segment == "..") {
  865. out.erase((std::min)(out.rfind('/'), out.size()));
  866. }
  867. if (is_last) { out += '/'; }
  868. } else {
  869. out += '/';
  870. out += segment;
  871. }
  872. i = next;
  873. }
  874. if (out.empty()) { out = "/"; }
  875. return out;
  876. }
  877. // Resolves a relative-path or query-only Location value against the path of
  878. // the request being redirected (RFC 3986 section 5.2). Absolute URIs and
  879. // references starting with '/' are returned unchanged.
  880. inline std::string resolve_relative_location(const std::string &location,
  881. const std::string &base) {
  882. if (location.empty() || location[0] == '/') { return location; }
  883. // A ':' in the first segment means the value has a scheme.
  884. if (location.find(':') < location.find_first_of("/?#")) { return location; }
  885. // A path starting with "//" would be re-parsed as an authority. Prefix "/."
  886. // (as the URL Standard does); remove_dot_segments strips it later.
  887. auto on_this_host = [](std::string path) -> std::string {
  888. if (path.compare(0, 2, "//") == 0) { path.insert(0, "/."); }
  889. return path;
  890. };
  891. if (location[0] == '#') {
  892. return on_this_host(base.substr(0, base.find('#')) + location);
  893. }
  894. auto base_path = base.substr(0, base.find_first_of("?#"));
  895. if (location[0] == '?') { return on_this_host(base_path + location); }
  896. if (base_path.empty() || base_path[0] != '/') { base_path = "/"; }
  897. auto merged = base_path.substr(0, base_path.rfind('/') + 1) + location;
  898. // Remove "." and ".." segments from the merged path.
  899. auto path_end = (std::min)(merged.find_first_of("?#"), merged.size());
  900. return on_this_host(remove_dot_segments(merged.substr(0, path_end)) +
  901. merged.substr(path_end));
  902. }
  903. } // namespace detail
  904. enum class SSLVerifierResponse {
  905. // no decision has been made, use the built-in certificate verifier
  906. NoDecisionMade,
  907. // connection certificate is verified and accepted
  908. CertificateAccepted,
  909. // connection certificate was processed but is rejected
  910. CertificateRejected
  911. };
  912. // System CA loading policy for SSL clients. Auto (the default) loads system
  913. // CA certs only when no custom CA is configured; enable_system_ca() switches
  914. // to an explicit policy.
  915. enum class SystemCAMode { Auto, Enabled, Disabled };
  916. enum StatusCode {
  917. // Information responses
  918. Continue_100 = 100,
  919. SwitchingProtocol_101 = 101,
  920. Processing_102 = 102,
  921. EarlyHints_103 = 103,
  922. // Successful responses
  923. OK_200 = 200,
  924. Created_201 = 201,
  925. Accepted_202 = 202,
  926. NonAuthoritativeInformation_203 = 203,
  927. NoContent_204 = 204,
  928. ResetContent_205 = 205,
  929. PartialContent_206 = 206,
  930. MultiStatus_207 = 207,
  931. AlreadyReported_208 = 208,
  932. IMUsed_226 = 226,
  933. // Redirection messages
  934. MultipleChoices_300 = 300,
  935. MovedPermanently_301 = 301,
  936. Found_302 = 302,
  937. SeeOther_303 = 303,
  938. NotModified_304 = 304,
  939. UseProxy_305 = 305,
  940. unused_306 = 306,
  941. TemporaryRedirect_307 = 307,
  942. PermanentRedirect_308 = 308,
  943. // Client error responses
  944. BadRequest_400 = 400,
  945. Unauthorized_401 = 401,
  946. PaymentRequired_402 = 402,
  947. Forbidden_403 = 403,
  948. NotFound_404 = 404,
  949. MethodNotAllowed_405 = 405,
  950. NotAcceptable_406 = 406,
  951. ProxyAuthenticationRequired_407 = 407,
  952. RequestTimeout_408 = 408,
  953. Conflict_409 = 409,
  954. Gone_410 = 410,
  955. LengthRequired_411 = 411,
  956. PreconditionFailed_412 = 412,
  957. PayloadTooLarge_413 = 413,
  958. UriTooLong_414 = 414,
  959. UnsupportedMediaType_415 = 415,
  960. RangeNotSatisfiable_416 = 416,
  961. ExpectationFailed_417 = 417,
  962. ImATeapot_418 = 418,
  963. MisdirectedRequest_421 = 421,
  964. UnprocessableContent_422 = 422,
  965. Locked_423 = 423,
  966. FailedDependency_424 = 424,
  967. TooEarly_425 = 425,
  968. UpgradeRequired_426 = 426,
  969. PreconditionRequired_428 = 428,
  970. TooManyRequests_429 = 429,
  971. RequestHeaderFieldsTooLarge_431 = 431,
  972. UnavailableForLegalReasons_451 = 451,
  973. // Server error responses
  974. InternalServerError_500 = 500,
  975. NotImplemented_501 = 501,
  976. BadGateway_502 = 502,
  977. ServiceUnavailable_503 = 503,
  978. GatewayTimeout_504 = 504,
  979. HttpVersionNotSupported_505 = 505,
  980. VariantAlsoNegotiates_506 = 506,
  981. InsufficientStorage_507 = 507,
  982. LoopDetected_508 = 508,
  983. NotExtended_510 = 510,
  984. NetworkAuthenticationRequired_511 = 511,
  985. };
  986. namespace detail {
  987. // A multimap that keeps its entries in the order they were inserted.
  988. //
  989. // HTTP needs that order in two places. RFC 9110 5.3 makes the order of header
  990. // fields sharing a field name significant and forbids a proxy from reordering
  991. // them, and a query string's parameters are meaningful in the order the caller
  992. // wrote them. Neither standard container expresses it: std::unordered_multimap
  993. // gives no ordering guarantee at all for equivalent keys (libstdc++ yields
  994. // reverse insertion order, libc++ insertion order), and std::multimap sorts by
  995. // key, which would drop control data such as Host behind whatever else the
  996. // message carries and alphabetise a query string.
  997. //
  998. // Entries are therefore kept in a flat vector, in order. Lookup is a linear
  999. // scan, which beats hashing for the handful of entries a message carries
  1000. // (headers are capped at CPPHTTPLIB_HEADER_MAX_COUNT).
  1001. //
  1002. // KeyEqual compares keys; it is what makes Headers case-insensitive and
  1003. // Params, whose parameter names are case-sensitive, not.
  1004. template <typename Mapped, typename KeyEqual> class insertion_ordered_multimap {
  1005. public:
  1006. using key_type = std::string;
  1007. using mapped_type = Mapped;
  1008. using value_type = std::pair<std::string, Mapped>;
  1009. using size_type = std::size_t;
  1010. using difference_type = std::ptrdiff_t;
  1011. using reference = value_type &;
  1012. using const_reference = const value_type &;
  1013. private:
  1014. static size_type npos() { return static_cast<size_type>(-1); }
  1015. static bool keys_equal(const std::string &a, const std::string &b) {
  1016. return KeyEqual()(a, b);
  1017. }
  1018. // Iterating yields every entry in insertion order, but equal_range() and
  1019. // find() have to walk only the entries sharing one key, which are not
  1020. // adjacent. Both are the same iterator type: key_idx_ selects between the
  1021. // two traversals, and since equality compares only the position, an iterator
  1022. // restricted to one key still compares equal to end().
  1023. template <typename V> class iterator_t {
  1024. public:
  1025. using iterator_category = std::bidirectional_iterator_tag;
  1026. using value_type = insertion_ordered_multimap::value_type;
  1027. using difference_type = insertion_ordered_multimap::difference_type;
  1028. using pointer = V *;
  1029. using reference = V &;
  1030. iterator_t() : data_(nullptr), idx_(0), size_(0), key_idx_(npos()) {}
  1031. template <typename U,
  1032. typename std::enable_if<std::is_convertible<U *, V *>::value,
  1033. int>::type = 0>
  1034. iterator_t(const iterator_t<U> &rhs)
  1035. : data_(rhs.data_), idx_(rhs.idx_), size_(rhs.size_),
  1036. key_idx_(rhs.key_idx_) {}
  1037. reference operator*() const { return data_[idx_]; }
  1038. pointer operator->() const { return data_ + idx_; }
  1039. iterator_t &operator++() {
  1040. // Saturating, so that advancing past the last entry of a key stays at
  1041. // end() instead of running off the container.
  1042. if (idx_ >= size_) { return *this; }
  1043. ++idx_;
  1044. if (key_idx_ != npos()) {
  1045. while (idx_ < size_ && !matches(idx_)) {
  1046. ++idx_;
  1047. }
  1048. }
  1049. return *this;
  1050. }
  1051. iterator_t operator++(int) {
  1052. auto tmp = *this;
  1053. ++*this;
  1054. return tmp;
  1055. }
  1056. iterator_t &operator--() {
  1057. if (idx_ == 0) { return *this; }
  1058. --idx_;
  1059. if (key_idx_ != npos()) {
  1060. while (idx_ > 0 && !matches(idx_)) {
  1061. --idx_;
  1062. }
  1063. }
  1064. return *this;
  1065. }
  1066. iterator_t operator--(int) {
  1067. auto tmp = *this;
  1068. --*this;
  1069. return tmp;
  1070. }
  1071. template <typename U> bool operator==(const iterator_t<U> &rhs) const {
  1072. return idx_ == rhs.idx_;
  1073. }
  1074. template <typename U> bool operator!=(const iterator_t<U> &rhs) const {
  1075. return idx_ != rhs.idx_;
  1076. }
  1077. private:
  1078. friend class insertion_ordered_multimap;
  1079. template <typename> friend class iterator_t;
  1080. iterator_t(V *data, size_type idx, size_type size, size_type key_idx)
  1081. : data_(data), idx_(idx), size_(size), key_idx_(key_idx) {}
  1082. bool matches(size_type i) const {
  1083. return keys_equal(data_[i].first, data_[key_idx_].first);
  1084. }
  1085. V *data_;
  1086. size_type idx_;
  1087. size_type size_;
  1088. size_type key_idx_;
  1089. };
  1090. public:
  1091. using iterator = iterator_t<value_type>;
  1092. using const_iterator = iterator_t<const value_type>;
  1093. insertion_ordered_multimap() = default;
  1094. insertion_ordered_multimap(std::initializer_list<value_type> il)
  1095. : entries_(il) {}
  1096. template <typename InputIt>
  1097. insertion_ordered_multimap(InputIt first, InputIt last)
  1098. : entries_(first, last) {}
  1099. iterator begin() { return make_iter(0, npos()); }
  1100. iterator end() { return make_iter(entries_.size(), npos()); }
  1101. const_iterator begin() const { return make_citer(0, npos()); }
  1102. const_iterator end() const { return make_citer(entries_.size(), npos()); }
  1103. const_iterator cbegin() const { return begin(); }
  1104. const_iterator cend() const { return end(); }
  1105. bool empty() const { return entries_.empty(); }
  1106. size_type size() const { return entries_.size(); }
  1107. void clear() { entries_.clear(); }
  1108. void swap(insertion_ordered_multimap &rhs) { entries_.swap(rhs.entries_); }
  1109. iterator insert(const value_type &val) {
  1110. entries_.push_back(val);
  1111. return make_iter(entries_.size() - 1, npos());
  1112. }
  1113. iterator insert(value_type &&val) {
  1114. entries_.push_back(std::move(val));
  1115. return make_iter(entries_.size() - 1, npos());
  1116. }
  1117. template <typename... Args> iterator emplace(Args &&...args) {
  1118. entries_.emplace_back(std::forward<Args>(args)...);
  1119. return make_iter(entries_.size() - 1, npos());
  1120. }
  1121. // For entries that have to lead the message, such as the Host header field
  1122. // (RFC 9110 5.3 recommends sending control data first).
  1123. template <typename... Args> iterator emplace_front(Args &&...args) {
  1124. entries_.emplace(entries_.begin(), std::forward<Args>(args)...);
  1125. return make_iter(0, npos());
  1126. }
  1127. iterator find(const std::string &key) {
  1128. auto i = index_of(key);
  1129. return i == npos() ? end() : make_iter(i, i);
  1130. }
  1131. const_iterator find(const std::string &key) const {
  1132. auto i = index_of(key);
  1133. return i == npos() ? end() : make_citer(i, i);
  1134. }
  1135. size_type count(const std::string &key) const {
  1136. size_type n = 0;
  1137. for (const auto &entry : entries_) {
  1138. if (keys_equal(entry.first, key)) { n++; }
  1139. }
  1140. return n;
  1141. }
  1142. std::pair<iterator, iterator> equal_range(const std::string &key) {
  1143. auto i = index_of(key);
  1144. return i == npos() ? std::make_pair(end(), end())
  1145. : std::make_pair(make_iter(i, i), end());
  1146. }
  1147. std::pair<const_iterator, const_iterator>
  1148. equal_range(const std::string &key) const {
  1149. auto i = index_of(key);
  1150. return i == npos() ? std::make_pair(end(), end())
  1151. : std::make_pair(make_citer(i, i), end());
  1152. }
  1153. size_type erase(const std::string &key) {
  1154. auto before = entries_.size();
  1155. entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
  1156. [key](const value_type &entry) {
  1157. return keys_equal(entry.first, key);
  1158. }),
  1159. entries_.end());
  1160. return before - entries_.size();
  1161. }
  1162. iterator erase(const_iterator pos) {
  1163. entries_.erase(entries_.begin() + static_cast<difference_type>(pos.idx_));
  1164. return make_iter(pos.idx_, npos());
  1165. }
  1166. // Erases what iterating [first, last) would actually visit, so erasing an
  1167. // equal_range() removes only the entries with that key, not everything
  1168. // positioned between them.
  1169. iterator erase(const_iterator first, const_iterator last) {
  1170. auto from = first.idx_;
  1171. auto to = last.idx_;
  1172. if (from >= to) { return make_iter(from, npos()); }
  1173. auto begin_it = entries_.begin();
  1174. auto from_it = begin_it + static_cast<difference_type>(from);
  1175. auto to_it = begin_it + static_cast<difference_type>(to);
  1176. if (first.key_idx_ == npos()) {
  1177. entries_.erase(from_it, to_it);
  1178. } else {
  1179. auto key = entries_[first.key_idx_].first;
  1180. auto keep = from_it;
  1181. for (auto it = from_it; it != to_it; ++it) {
  1182. if (!keys_equal(it->first, key)) {
  1183. if (keep != it) { *keep = std::move(*it); }
  1184. ++keep;
  1185. }
  1186. }
  1187. if (keep != to_it) {
  1188. keep = std::move(to_it, entries_.end(), keep);
  1189. } else {
  1190. keep = entries_.end();
  1191. }
  1192. entries_.erase(keep, entries_.end());
  1193. }
  1194. return make_iter(from, npos());
  1195. }
  1196. friend bool operator==(const insertion_ordered_multimap &lhs,
  1197. const insertion_ordered_multimap &rhs) {
  1198. return lhs.entries_ == rhs.entries_;
  1199. }
  1200. friend bool operator!=(const insertion_ordered_multimap &lhs,
  1201. const insertion_ordered_multimap &rhs) {
  1202. return !(lhs == rhs);
  1203. }
  1204. private:
  1205. size_type index_of(const std::string &key) const {
  1206. for (size_type i = 0; i < entries_.size(); i++) {
  1207. if (keys_equal(entries_[i].first, key)) { return i; }
  1208. }
  1209. return npos();
  1210. }
  1211. iterator make_iter(size_type idx, size_type key_idx) {
  1212. return iterator(entries_.data(), idx, entries_.size(), key_idx);
  1213. }
  1214. const_iterator make_citer(size_type idx, size_type key_idx) const {
  1215. return const_iterator(entries_.data(), idx, entries_.size(), key_idx);
  1216. }
  1217. std::vector<value_type> entries_;
  1218. };
  1219. } // namespace detail
  1220. using Headers =
  1221. detail::insertion_ordered_multimap<std::string,
  1222. detail::case_ignore::equal_to>;
  1223. // Query parameter names are case-sensitive, unlike header field names.
  1224. using Params =
  1225. detail::insertion_ordered_multimap<std::string, std::equal_to<std::string>>;
  1226. using Match = std::smatch;
  1227. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  1228. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  1229. /*
  1230. * detail: type-erased storage used by UserData.
  1231. * ABI-stable regardless of C++ standard — always uses this custom
  1232. * implementation instead of std::any.
  1233. */
  1234. namespace detail {
  1235. using any_type_id = const void *;
  1236. template <typename T> any_type_id any_typeid() noexcept {
  1237. static const char id = 0;
  1238. return &id;
  1239. }
  1240. struct any_storage {
  1241. virtual ~any_storage() = default;
  1242. virtual std::unique_ptr<any_storage> clone() const = 0;
  1243. virtual any_type_id type_id() const noexcept = 0;
  1244. };
  1245. template <typename T> struct any_value final : any_storage {
  1246. T value;
  1247. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  1248. std::unique_ptr<any_storage> clone() const override {
  1249. return std::unique_ptr<any_storage>(new any_value<T>(value));
  1250. }
  1251. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  1252. };
  1253. } // namespace detail
  1254. class UserData {
  1255. public:
  1256. UserData() = default;
  1257. UserData(UserData &&) noexcept = default;
  1258. UserData &operator=(UserData &&) noexcept = default;
  1259. UserData(const UserData &o) {
  1260. for (const auto &e : o.entries_) {
  1261. if (e.second) { entries_[e.first] = e.second->clone(); }
  1262. }
  1263. }
  1264. UserData &operator=(const UserData &o) {
  1265. if (this != &o) {
  1266. entries_.clear();
  1267. for (const auto &e : o.entries_) {
  1268. if (e.second) { entries_[e.first] = e.second->clone(); }
  1269. }
  1270. }
  1271. return *this;
  1272. }
  1273. template <typename T> void set(const std::string &key, T &&value) {
  1274. using D = typename std::decay<T>::type;
  1275. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  1276. }
  1277. template <typename T> T *get(const std::string &key) noexcept {
  1278. auto it = entries_.find(key);
  1279. if (it == entries_.end() || !it->second) { return nullptr; }
  1280. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1281. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  1282. }
  1283. template <typename T> const T *get(const std::string &key) const noexcept {
  1284. auto it = entries_.find(key);
  1285. if (it == entries_.end() || !it->second) { return nullptr; }
  1286. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1287. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  1288. }
  1289. bool has(const std::string &key) const noexcept {
  1290. return entries_.find(key) != entries_.end();
  1291. }
  1292. void erase(const std::string &key) { entries_.erase(key); }
  1293. void clear() noexcept { entries_.clear(); }
  1294. private:
  1295. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  1296. entries_;
  1297. };
  1298. struct Response;
  1299. using ResponseHandler = std::function<bool(const Response &response)>;
  1300. struct FormData {
  1301. std::string name;
  1302. std::string content;
  1303. std::string filename;
  1304. std::string content_type;
  1305. Headers headers;
  1306. };
  1307. struct FormField {
  1308. std::string name;
  1309. std::string content;
  1310. Headers headers;
  1311. };
  1312. // RFC 7578 5.2: a form processor "SHOULD send back results in order" and
  1313. // "Intermediaries MUST NOT reorder the results", so a handler walking these
  1314. // should see the parts as they were sent. A std::multimap sorts by field name
  1315. // and loses that. Field names are case-sensitive, hence std::equal_to rather
  1316. // than the case-insensitive predicate Headers uses.
  1317. using FormFields =
  1318. detail::insertion_ordered_multimap<FormField, std::equal_to<std::string>>;
  1319. using FormFiles =
  1320. detail::insertion_ordered_multimap<FormData, std::equal_to<std::string>>;
  1321. struct MultipartFormData {
  1322. FormFields fields; // Text fields from multipart
  1323. FormFiles files; // Files from multipart
  1324. // Text field access
  1325. std::string get_field(const std::string &key, size_t id = 0) const;
  1326. std::vector<std::string> get_fields(const std::string &key) const;
  1327. bool has_field(const std::string &key) const;
  1328. size_t get_field_count(const std::string &key) const;
  1329. // File access
  1330. FormData get_file(const std::string &key, size_t id = 0) const;
  1331. std::vector<FormData> get_files(const std::string &key) const;
  1332. bool has_file(const std::string &key) const;
  1333. size_t get_file_count(const std::string &key) const;
  1334. };
  1335. struct UploadFormData {
  1336. std::string name;
  1337. std::string content;
  1338. std::string filename;
  1339. std::string content_type;
  1340. };
  1341. using UploadFormDataItems = std::vector<UploadFormData>;
  1342. class DataSink {
  1343. public:
  1344. DataSink() : os(&sb_), sb_(*this) {}
  1345. DataSink(const DataSink &) = delete;
  1346. DataSink &operator=(const DataSink &) = delete;
  1347. DataSink(DataSink &&) = delete;
  1348. DataSink &operator=(DataSink &&) = delete;
  1349. std::function<bool(const char *data, size_t data_len)> write;
  1350. // Only `write` is mandatory. The rest are defaulted so that a provider
  1351. // calling one on a writer that does not set it gets sensible behaviour
  1352. // rather than std::bad_function_call thrown from a worker thread. Capturing
  1353. // `this` is safe: DataSink is neither copyable nor movable.
  1354. std::function<bool()> is_writable = []() { return true; };
  1355. std::function<void()> done = []() {};
  1356. std::function<void(const Headers &trailer)> done_with_trailer =
  1357. [this](const Headers & /*trailer*/) { done(); };
  1358. std::ostream os;
  1359. private:
  1360. class data_sink_streambuf final : public std::streambuf {
  1361. public:
  1362. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  1363. protected:
  1364. std::streamsize xsputn(const char *s, std::streamsize n) override {
  1365. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  1366. return 0;
  1367. }
  1368. private:
  1369. DataSink &sink_;
  1370. };
  1371. data_sink_streambuf sb_;
  1372. };
  1373. using ContentProvider =
  1374. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  1375. using ContentProviderWithoutLength =
  1376. std::function<bool(size_t offset, DataSink &sink)>;
  1377. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  1378. struct FormDataProvider {
  1379. std::string name;
  1380. ContentProviderWithoutLength provider;
  1381. std::string filename;
  1382. std::string content_type;
  1383. };
  1384. using FormDataProviderItems = std::vector<FormDataProvider>;
  1385. inline FormDataProvider
  1386. make_file_provider(const std::string &name, const std::string &filepath,
  1387. const std::string &filename = std::string(),
  1388. const std::string &content_type = std::string()) {
  1389. FormDataProvider fdp;
  1390. fdp.name = name;
  1391. fdp.filename = filename.empty() ? filepath : filename;
  1392. fdp.content_type = content_type;
  1393. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  1394. std::ifstream f(filepath, std::ios::binary);
  1395. if (!f) { return false; }
  1396. if (offset > 0) {
  1397. f.seekg(static_cast<std::streamoff>(offset));
  1398. if (!f.good()) {
  1399. sink.done();
  1400. return true;
  1401. }
  1402. }
  1403. char buf[8192];
  1404. f.read(buf, sizeof(buf));
  1405. auto n = static_cast<size_t>(f.gcount());
  1406. if (n > 0) { return sink.write(buf, n); }
  1407. sink.done(); // EOF
  1408. return true;
  1409. };
  1410. return fdp;
  1411. }
  1412. inline std::pair<size_t, ContentProvider>
  1413. make_file_body(const std::string &filepath) {
  1414. size_t size = 0;
  1415. {
  1416. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  1417. if (!f) { return {0, ContentProvider{}}; }
  1418. size = static_cast<size_t>(f.tellg());
  1419. }
  1420. ContentProvider provider = [filepath](size_t offset, size_t length,
  1421. DataSink &sink) -> bool {
  1422. std::ifstream f(filepath, std::ios::binary);
  1423. if (!f) { return false; }
  1424. f.seekg(static_cast<std::streamoff>(offset));
  1425. if (!f.good()) { return false; }
  1426. char buf[8192];
  1427. while (length > 0) {
  1428. auto to_read = (std::min)(sizeof(buf), length);
  1429. f.read(buf, static_cast<std::streamsize>(to_read));
  1430. auto n = static_cast<size_t>(f.gcount());
  1431. // The file is shorter than the size make_file_body() measured, which the
  1432. // caller has already committed to as Content-Length. The body cannot be
  1433. // completed, so fail as every other error here does.
  1434. if (n == 0) { return false; }
  1435. if (!sink.write(buf, n)) { return false; }
  1436. length -= n;
  1437. }
  1438. return true;
  1439. };
  1440. return {size, std::move(provider)};
  1441. }
  1442. using ContentReceiverWithProgress = std::function<bool(
  1443. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1444. using ContentReceiver =
  1445. std::function<bool(const char *data, size_t data_length)>;
  1446. using FormDataHeader = std::function<bool(const FormData &file)>;
  1447. class ContentReader {
  1448. public:
  1449. using Reader = std::function<bool(ContentReceiver receiver)>;
  1450. using FormDataReader =
  1451. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1452. ContentReader(Reader reader, FormDataReader multipart_reader)
  1453. : reader_(std::move(reader)),
  1454. formdata_reader_(std::move(multipart_reader)) {}
  1455. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1456. return formdata_reader_(std::move(header), std::move(receiver));
  1457. }
  1458. bool operator()(ContentReceiver receiver) const {
  1459. return reader_(std::move(receiver));
  1460. }
  1461. Reader reader_;
  1462. FormDataReader formdata_reader_;
  1463. };
  1464. using Range = std::pair<ssize_t, ssize_t>;
  1465. using Ranges = std::vector<Range>;
  1466. #ifdef CPPHTTPLIB_SSL_ENABLED
  1467. // TLS abstraction layer - public type definitions and API
  1468. namespace tls {
  1469. // Opaque handles (defined as void* for abstraction)
  1470. using ctx_t = void *;
  1471. using session_t = void *;
  1472. using const_session_t = const void *; // For read-only session access
  1473. using cert_t = void *;
  1474. using ca_store_t = void *;
  1475. // TLS versions
  1476. enum class Version {
  1477. TLS1_2 = 0x0303,
  1478. TLS1_3 = 0x0304,
  1479. };
  1480. // Subject Alternative Names (SAN) entry types
  1481. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1482. // SAN entry structure
  1483. struct SanEntry {
  1484. SanType type;
  1485. std::string value;
  1486. };
  1487. // Verification context for certificate verification callback
  1488. struct VerifyContext {
  1489. session_t session; // TLS session handle
  1490. cert_t cert; // Current certificate being verified
  1491. int depth; // Certificate chain depth (0 = leaf)
  1492. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1493. long error_code; // Backend-specific error code (0 = no error)
  1494. const char *error_string; // Human-readable error description
  1495. // Certificate introspection methods
  1496. std::string subject_cn() const;
  1497. std::string issuer_name() const;
  1498. bool check_hostname(const char *hostname) const;
  1499. std::vector<SanEntry> sans() const;
  1500. bool validity(time_t &not_before, time_t &not_after) const;
  1501. std::string serial() const;
  1502. };
  1503. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1504. // TlsError codes for TLS operations (backend-independent)
  1505. enum class ErrorCode : int {
  1506. Success = 0,
  1507. WantRead, // Non-blocking: need to wait for read
  1508. WantWrite, // Non-blocking: need to wait for write
  1509. PeerClosed, // Peer closed the connection
  1510. Fatal, // Unrecoverable error
  1511. SyscallError, // System call error (check sys_errno)
  1512. CertVerifyFailed, // Certificate verification failed
  1513. HostnameMismatch, // Hostname verification failed
  1514. };
  1515. // TLS error information
  1516. struct TlsError {
  1517. ErrorCode code = ErrorCode::Fatal;
  1518. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1519. int sys_errno = 0; // errno when SyscallError
  1520. // Convert verification error code to human-readable string
  1521. static std::string verify_error_to_string(long error_code);
  1522. };
  1523. // RAII wrapper for peer certificate
  1524. class PeerCert {
  1525. public:
  1526. PeerCert();
  1527. PeerCert(PeerCert &&other) noexcept;
  1528. PeerCert &operator=(PeerCert &&other) noexcept;
  1529. ~PeerCert();
  1530. PeerCert(const PeerCert &) = delete;
  1531. PeerCert &operator=(const PeerCert &) = delete;
  1532. explicit operator bool() const;
  1533. std::string subject_cn() const;
  1534. std::string issuer_name() const;
  1535. bool check_hostname(const char *hostname) const;
  1536. std::vector<SanEntry> sans() const;
  1537. bool validity(time_t &not_before, time_t &not_after) const;
  1538. std::string serial() const;
  1539. private:
  1540. explicit PeerCert(cert_t cert);
  1541. cert_t cert_ = nullptr;
  1542. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1543. };
  1544. // Callback for TLS context setup (used by SSLServer constructor)
  1545. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1546. } // namespace tls
  1547. #endif
  1548. struct Request {
  1549. std::string method;
  1550. std::string path;
  1551. std::string matched_route;
  1552. Params params;
  1553. Headers headers;
  1554. Headers trailers;
  1555. std::string body;
  1556. std::string remote_addr;
  1557. int remote_port = -1;
  1558. std::string local_addr;
  1559. int local_port = -1;
  1560. // for server
  1561. std::string version;
  1562. std::string target;
  1563. MultipartFormData form;
  1564. Ranges ranges;
  1565. Match matches;
  1566. std::unordered_map<std::string, std::string> path_params;
  1567. std::function<bool()> is_connection_closed = []() { return true; };
  1568. // for client
  1569. std::vector<std::string> accept_content_types;
  1570. ResponseHandler response_handler;
  1571. ContentReceiverWithProgress content_receiver;
  1572. DownloadProgress download_progress;
  1573. UploadProgress upload_progress;
  1574. bool has_header(const std::string &key) const;
  1575. std::string get_header_value(const std::string &key, const char *def = "",
  1576. size_t id = 0) const;
  1577. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1578. size_t id = 0) const;
  1579. size_t get_header_value_count(const std::string &key) const;
  1580. void set_header(const std::string &key, const std::string &val);
  1581. bool has_trailer(const std::string &key) const;
  1582. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1583. size_t get_trailer_value_count(const std::string &key) const;
  1584. bool has_param(const std::string &key) const;
  1585. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1586. std::vector<std::string> get_param_values(const std::string &key) const;
  1587. size_t get_param_value_count(const std::string &key) const;
  1588. bool is_multipart_form_data() const;
  1589. // private members...
  1590. bool body_read_started_ = false;
  1591. bool body_consumed_ = false;
  1592. bool expect_100_continue_pending_ = false;
  1593. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1594. size_t content_length_ = 0;
  1595. ContentProvider content_provider_;
  1596. bool is_chunked_content_provider_ = false;
  1597. size_t authorization_count_ = 0;
  1598. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1599. (std::chrono::steady_clock::time_point::min)();
  1600. #ifdef CPPHTTPLIB_SSL_ENABLED
  1601. tls::const_session_t ssl = nullptr;
  1602. tls::PeerCert peer_cert() const;
  1603. std::string sni() const;
  1604. #endif
  1605. };
  1606. namespace detail {
  1607. // Declared up here, away from the rest of the compression helpers, because
  1608. // `Response` stores one.
  1609. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1610. } // namespace detail
  1611. struct Response {
  1612. std::string version;
  1613. int status = -1;
  1614. std::string reason;
  1615. Headers headers;
  1616. Headers trailers;
  1617. std::string body;
  1618. std::string location; // Redirect location
  1619. // User-defined context — set by pre-routing/pre-request handlers and read
  1620. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1621. UserData user_data;
  1622. bool has_header(const std::string &key) const;
  1623. std::string get_header_value(const std::string &key, const char *def = "",
  1624. size_t id = 0) const;
  1625. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1626. size_t id = 0) const;
  1627. size_t get_header_value_count(const std::string &key) const;
  1628. void set_header(const std::string &key, const std::string &val);
  1629. bool has_trailer(const std::string &key) const;
  1630. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1631. size_t get_trailer_value_count(const std::string &key) const;
  1632. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1633. void set_content(const char *s, size_t n, const std::string &content_type);
  1634. void set_content(const std::string &s, const std::string &content_type);
  1635. void set_content(std::string &&s, const std::string &content_type);
  1636. void set_content_provider(
  1637. size_t length, const std::string &content_type, ContentProvider provider,
  1638. ContentProviderResourceReleaser resource_releaser = nullptr);
  1639. void set_content_provider(
  1640. const std::string &content_type, ContentProviderWithoutLength provider,
  1641. ContentProviderResourceReleaser resource_releaser = nullptr);
  1642. void set_chunked_content_provider(
  1643. const std::string &content_type, ContentProviderWithoutLength provider,
  1644. ContentProviderResourceReleaser resource_releaser = nullptr);
  1645. void set_file_content(const std::string &path,
  1646. const std::string &content_type);
  1647. void set_file_content(const std::string &path);
  1648. Response() = default;
  1649. Response(const Response &) = default;
  1650. Response &operator=(const Response &) = default;
  1651. Response(Response &&) = default;
  1652. Response &operator=(Response &&) = default;
  1653. ~Response() {
  1654. if (content_provider_resource_releaser_) {
  1655. content_provider_resource_releaser_(content_provider_success_);
  1656. }
  1657. }
  1658. // private members...
  1659. size_t content_length_ = 0;
  1660. ContentProvider content_provider_;
  1661. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1662. bool is_chunked_content_provider_ = false;
  1663. bool is_file_content_provider_ = false;
  1664. bool content_provider_success_ = false;
  1665. std::string file_content_path_;
  1666. std::string file_content_content_type_;
  1667. // Content coding chosen for the response body, decided once so that the
  1668. // headers and the body cannot disagree: where the file is opened for a
  1669. // file-backed content provider (keeping the ETag honest), and in
  1670. // `apply_ranges()` for a chunked content provider. `EncodingType::None`
  1671. // for every other kind of response.
  1672. detail::EncodingType content_coding_ = detail::EncodingType::None;
  1673. };
  1674. enum class Error {
  1675. Success = 0,
  1676. Unknown,
  1677. Connection,
  1678. BindIPAddress,
  1679. Read,
  1680. Write,
  1681. ExceedRedirectCount,
  1682. Canceled,
  1683. SSLConnection,
  1684. SSLLoadingCerts,
  1685. SSLServerVerification,
  1686. SSLServerHostnameVerification,
  1687. UnsupportedMultipartBoundaryChars,
  1688. Compression,
  1689. ConnectionTimeout,
  1690. ProxyConnection,
  1691. ConnectionClosed,
  1692. Timeout,
  1693. ResourceExhaustion,
  1694. TooManyFormDataFiles,
  1695. ExceedMaxPayloadSize,
  1696. ExceedUriMaxLength,
  1697. ExceedMaxSocketDescriptorCount,
  1698. InvalidRequestLine,
  1699. InvalidHTTPMethod,
  1700. InvalidHTTPVersion,
  1701. InvalidHeaders,
  1702. MultipartParsing,
  1703. OpenFile,
  1704. Listen,
  1705. GetSockName,
  1706. UnsupportedAddressFamily,
  1707. HTTPParsing,
  1708. InvalidRangeHeader,
  1709. UnsupportedContentEncoding,
  1710. WebSocketHandshake,
  1711. UserCallbackException,
  1712. // For internal use only
  1713. SSLPeerCouldBeClosed_,
  1714. };
  1715. std::string to_string(Error error);
  1716. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1717. class Stream {
  1718. public:
  1719. virtual ~Stream() = default;
  1720. virtual bool is_readable() const = 0;
  1721. virtual bool wait_readable() const = 0;
  1722. virtual bool wait_writable() const = 0;
  1723. virtual bool is_peer_alive() const { return wait_writable(); }
  1724. virtual ssize_t read(char *ptr, size_t size) = 0;
  1725. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1726. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1727. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1728. virtual socket_t socket() const = 0;
  1729. virtual time_t duration() const = 0;
  1730. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1731. (void)sec;
  1732. (void)usec;
  1733. }
  1734. // Bounds the reads from now on to `msec` in total, on top of the timeout of
  1735. // each one. 0 lifts the bound.
  1736. virtual void set_max_timeout(time_t msec) { (void)msec; }
  1737. // Lets a wait for data end early once `interrupted` returns true, so that
  1738. // another thread can stop a blocked read on every platform.
  1739. virtual void set_read_interrupt(std::function<bool()> interrupted) {
  1740. (void)interrupted;
  1741. }
  1742. // Bytes already pulled off the socket and sitting in this stream's own
  1743. // buffer. Exposing them lets a line reader scan for a terminator in one
  1744. // pass instead of asking for a byte at a time. A stream that does no
  1745. // buffering of its own reports none, and readers fall back to read().
  1746. virtual const char *buffered_data(size_t &size) const {
  1747. size = 0;
  1748. return nullptr;
  1749. }
  1750. // Discards `size` bytes previously returned by buffered_data().
  1751. virtual void consume_buffered(size_t size) { (void)size; }
  1752. ssize_t write(const char *ptr);
  1753. ssize_t write(const std::string &s);
  1754. Error get_error() const { return error_; }
  1755. protected:
  1756. Error error_ = Error::Success;
  1757. };
  1758. class TaskQueue {
  1759. public:
  1760. TaskQueue() = default;
  1761. virtual ~TaskQueue() = default;
  1762. virtual bool enqueue(std::function<void()> fn) = 0;
  1763. virtual void shutdown() = 0;
  1764. virtual void on_idle() {}
  1765. };
  1766. class ThreadPool final : public TaskQueue {
  1767. public:
  1768. explicit ThreadPool(
  1769. size_t n, size_t max_n = 0, size_t mqr = 0,
  1770. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1771. ThreadPool(const ThreadPool &) = delete;
  1772. ~ThreadPool() override = default;
  1773. bool enqueue(std::function<void()> fn) override;
  1774. void shutdown() override;
  1775. private:
  1776. void worker(bool is_dynamic);
  1777. void move_to_finished(std::thread::id id);
  1778. void cleanup_finished_threads();
  1779. size_t base_thread_count_;
  1780. size_t max_thread_count_;
  1781. size_t max_queued_requests_;
  1782. time_t idle_timeout_sec_;
  1783. size_t idle_thread_count_;
  1784. bool shutdown_;
  1785. std::list<std::function<void()>> jobs_;
  1786. std::vector<std::thread> threads_; // base threads
  1787. std::list<std::thread> dynamic_threads_; // dynamic threads
  1788. std::vector<std::thread>
  1789. finished_threads_; // exited dynamic threads awaiting join
  1790. std::condition_variable cond_;
  1791. std::mutex mutex_;
  1792. };
  1793. using Logger = std::function<void(const Request &, const Response &)>;
  1794. // Forward declaration for Error type
  1795. enum class Error;
  1796. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1797. using SocketOptions = std::function<void(socket_t sock)>;
  1798. void default_socket_options(socket_t sock);
  1799. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1800. const char *status_message(int status);
  1801. std::string to_string(Error error);
  1802. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1803. std::string get_bearer_token_auth(const Request &req);
  1804. namespace detail {
  1805. class MatcherBase {
  1806. public:
  1807. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1808. virtual ~MatcherBase() = default;
  1809. const std::string &pattern() const { return pattern_; }
  1810. // Match request path and populate its matches and
  1811. virtual bool match(Request &request) const = 0;
  1812. private:
  1813. std::string pattern_;
  1814. };
  1815. /**
  1816. * Captures parameters in request path and stores them in Request::path_params
  1817. *
  1818. * Capture name is a substring of a pattern from : to /.
  1819. * The rest of the pattern is matched against the request path directly
  1820. * Parameters are captured starting from the next character after
  1821. * the end of the last matched static pattern fragment until the next /.
  1822. *
  1823. * Example pattern:
  1824. * "/path/fragments/:capture/more/fragments/:second_capture"
  1825. * Static fragments:
  1826. * "/path/fragments/", "more/fragments/"
  1827. *
  1828. * Given the following request path:
  1829. * "/path/fragments/:1/more/fragments/:2"
  1830. * the resulting capture will be
  1831. * {{"capture", "1"}, {"second_capture", "2"}}
  1832. */
  1833. class PathParamsMatcher final : public MatcherBase {
  1834. public:
  1835. PathParamsMatcher(const std::string &pattern);
  1836. bool match(Request &request) const override;
  1837. private:
  1838. // Treat segment separators as the end of path parameter capture
  1839. // Does not need to handle query parameters as they are parsed before path
  1840. // matching
  1841. static constexpr char separator = '/';
  1842. // Contains static path fragments to match against, excluding the '/' after
  1843. // path params
  1844. // Fragments are separated by path params
  1845. std::vector<std::string> static_fragments_;
  1846. // Stores the names of the path parameters to be used as keys in the
  1847. // Request::path_params map
  1848. std::vector<std::string> param_names_;
  1849. };
  1850. /**
  1851. * Performs std::regex_match on request path
  1852. * and stores the result in Request::matches
  1853. *
  1854. * Note that regex match is performed directly on the whole request.
  1855. * This means that wildcard patterns may match multiple path segments with /:
  1856. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1857. */
  1858. class RegexMatcher final : public MatcherBase {
  1859. public:
  1860. RegexMatcher(const std::string &pattern)
  1861. : MatcherBase(pattern), regex_(pattern) {}
  1862. bool match(Request &request) const override;
  1863. private:
  1864. std::regex regex_;
  1865. };
  1866. int close_socket(socket_t sock) noexcept;
  1867. bool is_accept_resource_error();
  1868. bool is_accept_transient_error();
  1869. ssize_t write_headers(Stream &strm, const Headers &headers);
  1870. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1871. time_t usec);
  1872. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1873. const std::string &boundary);
  1874. ContentProvider
  1875. make_multipart_content_provider(const UploadFormDataItems &items,
  1876. const std::string &boundary);
  1877. } // namespace detail
  1878. bool is_valid_multipart_boundary(const std::string &boundary);
  1879. // Serializer for multipart/form-data request bodies. The boundary is owned
  1880. // by the writer so that per-part framing and the final terminator always
  1881. // agree. Field names and filenames are escaped following the WHATWG HTML
  1882. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1883. // in content types.
  1884. class MultipartFormDataWriter {
  1885. public:
  1886. MultipartFormDataWriter();
  1887. // precondition: is_valid_multipart_boundary(boundary)
  1888. explicit MultipartFormDataWriter(std::string boundary);
  1889. const std::string &boundary() const;
  1890. std::string content_type() const;
  1891. // In-memory items -> whole body (known length)
  1892. std::string serialize(const UploadFormDataItems &items) const;
  1893. size_t content_length(const UploadFormDataItems &items) const;
  1894. // Per-part framing for streaming via a content provider
  1895. std::string item_begin(const UploadFormData &item) const;
  1896. static std::string item_end();
  1897. std::string finish() const;
  1898. private:
  1899. std::string boundary_;
  1900. };
  1901. class Server {
  1902. public:
  1903. using Handler = std::function<void(const Request &, Response &)>;
  1904. using ExceptionHandler =
  1905. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1906. enum class HandlerResponse {
  1907. Handled,
  1908. Unhandled,
  1909. };
  1910. using HandlerWithResponse =
  1911. std::function<HandlerResponse(const Request &, Response &)>;
  1912. using HandlerWithContentReader = std::function<void(
  1913. const Request &, Response &, const ContentReader &content_reader)>;
  1914. using Expect100ContinueHandler =
  1915. std::function<int(const Request &, Response &)>;
  1916. using StartHandler = std::function<void()>;
  1917. using WebSocketHandler =
  1918. std::function<void(const Request &, ws::WebSocket &)>;
  1919. using SubProtocolSelector =
  1920. std::function<std::string(const std::vector<std::string> &protocols)>;
  1921. Server();
  1922. virtual ~Server();
  1923. virtual bool is_valid() const;
  1924. Server &Get(const std::string &pattern, Handler handler);
  1925. Server &Post(const std::string &pattern, Handler handler);
  1926. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1927. Server &Put(const std::string &pattern, Handler handler);
  1928. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1929. Server &Patch(const std::string &pattern, Handler handler);
  1930. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1931. Server &Delete(const std::string &pattern, Handler handler);
  1932. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1933. Server &Options(const std::string &pattern, Handler handler);
  1934. // Register a handler for an HTTP method outside the built-in set (e.g. the
  1935. // WebDAV methods from RFC 4918). Registering a method here is what makes the
  1936. // server accept it; an unregistered method is still rejected with 400.
  1937. // `method` must be a valid HTTP method token and must not be one of the
  1938. // built-in methods, which have their own registration functions above. A
  1939. // rejected registration makes is_valid() return false, so listen() fails.
  1940. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1941. Handler handler);
  1942. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1943. HandlerWithContentReader handler);
  1944. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1945. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1946. SubProtocolSelector sub_protocol_selector);
  1947. bool set_base_dir(const std::string &dir,
  1948. const std::string &mount_point = std::string());
  1949. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1950. Headers headers = Headers());
  1951. bool remove_mount_point(const std::string &mount_point);
  1952. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1953. const std::string &mime);
  1954. Server &set_default_file_mimetype(const std::string &mime);
  1955. Server &set_file_request_handler(Handler handler);
  1956. template <class ErrorHandlerFunc>
  1957. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1958. return set_error_handler_core(
  1959. std::forward<ErrorHandlerFunc>(handler),
  1960. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1961. }
  1962. Server &set_exception_handler(ExceptionHandler handler);
  1963. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1964. Server &set_post_routing_handler(Handler handler);
  1965. Server &set_pre_request_handler(HandlerWithResponse handler);
  1966. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1967. Server &set_start_handler(StartHandler handler);
  1968. Server &set_logger(Logger logger);
  1969. Server &set_pre_compression_logger(Logger logger);
  1970. Server &set_error_logger(ErrorLogger error_logger);
  1971. Server &set_address_family(int family);
  1972. Server &set_tcp_nodelay(bool on);
  1973. Server &set_ipv6_v6only(bool on);
  1974. Server &set_socket_options(SocketOptions socket_options);
  1975. Server &set_default_headers(Headers headers);
  1976. Server &
  1977. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1978. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1979. Server &set_keep_alive_max_count(size_t count);
  1980. Server &set_keep_alive_timeout(time_t sec);
  1981. template <class Rep, class Period>
  1982. Server &
  1983. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1984. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1985. template <class Rep, class Period>
  1986. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1987. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1988. template <class Rep, class Period>
  1989. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1990. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1991. template <class Rep, class Period>
  1992. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1993. // Keeps idle keep-alive connections in an event loop instead of a worker
  1994. // thread each. Call it before listen(). See README for what changes.
  1995. Server &set_keep_alive_parking(bool on);
  1996. Server &set_payload_max_length(size_t length);
  1997. Server &set_compress(bool on);
  1998. Server &set_static_file_compression(bool on);
  1999. Server &set_static_file_compression_min_length(size_t length);
  2000. Server &set_static_file_compression_max_length(size_t length);
  2001. Server &set_websocket_ping_interval(time_t sec);
  2002. template <class Rep, class Period>
  2003. Server &set_websocket_ping_interval(
  2004. const std::chrono::duration<Rep, Period> &duration);
  2005. Server &set_websocket_max_missed_pongs(int count);
  2006. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  2007. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  2008. bool listen_after_bind();
  2009. bool listen(const std::string &host, int port, int socket_flags = 0);
  2010. bool is_running() const;
  2011. void wait_until_ready() const;
  2012. void stop() noexcept;
  2013. void decommission();
  2014. std::function<TaskQueue *(void)> new_task_queue;
  2015. protected:
  2016. bool process_request(Stream &strm, const std::string &remote_addr,
  2017. int remote_port, const std::string &local_addr,
  2018. int local_port, bool close_connection,
  2019. bool &connection_closed,
  2020. const std::function<void(Request &)> &setup_request,
  2021. bool *websocket_upgraded = nullptr);
  2022. // Runs the per-connection serving loop and stops an exception thrown by a
  2023. // user callback from escaping the worker thread.
  2024. //
  2025. // process_request() wraps only routing() and the hooks before a WebSocket
  2026. // upgrade in a try/catch. Content providers, the post-routing, error,
  2027. // logging and expect-100 handlers and WebSocket handlers all run outside
  2028. // it, and the task queue calls the job without a catch, so an exception
  2029. // from any of those would terminate the process.
  2030. //
  2031. // No 500 is possible here: by the time a content provider runs, the status
  2032. // line and headers are already on the wire. Report it through the error
  2033. // logger and drop the connection, which is what the peer observes either
  2034. // way. Other connections are unaffected.
  2035. template <typename Serve> bool serve_guarded(Serve &&serve) const {
  2036. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  2037. return serve();
  2038. #else
  2039. try {
  2040. return serve();
  2041. } catch (...) {
  2042. // The error logger is a user callback too, so it must not be able to
  2043. // throw the guard back open.
  2044. try {
  2045. output_error_log(Error::UserCallbackException, nullptr);
  2046. } catch (...) {}
  2047. return false;
  2048. }
  2049. #endif
  2050. }
  2051. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  2052. // stop() takes the listening socket away; listen() then waits for handlers
  2053. bool is_stopping() const { return svr_sock_ == INVALID_SOCKET; }
  2054. // See set_keep_alive_parking(). Defined in the implementation part.
  2055. struct KeepAliveConnection;
  2056. struct ParkingState;
  2057. std::unique_ptr<ParkingState> parking_;
  2058. bool keep_alive_parking_ = false;
  2059. bool idle_interval_set_ = false;
  2060. std::vector<std::string> trusted_proxies_;
  2061. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  2062. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  2063. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  2064. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  2065. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  2066. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  2067. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  2068. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  2069. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2070. bool compress_ = true;
  2071. bool static_file_compression_ = false;
  2072. size_t static_file_compression_min_length_ =
  2073. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH;
  2074. size_t static_file_compression_max_length_ =
  2075. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH;
  2076. time_t websocket_ping_interval_sec_ =
  2077. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  2078. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  2079. private:
  2080. using Handlers =
  2081. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  2082. using HandlersForContentReader =
  2083. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  2084. HandlerWithContentReader>>;
  2085. // Both handler tables for one custom method live in a single entry, so that
  2086. // routing() needs only one map lookup per request to reach either of them.
  2087. struct CustomHandlerEntry {
  2088. Handlers handlers;
  2089. HandlersForContentReader handlers_for_content_reader;
  2090. };
  2091. using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
  2092. static std::unique_ptr<detail::MatcherBase>
  2093. make_matcher(const std::string &pattern);
  2094. static const std::set<std::string> &builtin_methods();
  2095. CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
  2096. const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
  2097. template <typename H>
  2098. Server &add_handler(
  2099. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  2100. const std::string &pattern, H handler) {
  2101. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  2102. return *this;
  2103. }
  2104. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  2105. Server &set_error_handler_core(Handler handler, std::false_type);
  2106. socket_t create_server_socket(const std::string &host, int port,
  2107. int socket_flags,
  2108. SocketOptions socket_options) const;
  2109. int bind_internal(const std::string &host, int port, int socket_flags);
  2110. bool listen_internal();
  2111. bool accept_loop(TaskQueue &task_queue);
  2112. bool parking_loop(TaskQueue &task_queue);
  2113. void prepare_accepted_socket(socket_t sock) const;
  2114. struct PlainConnection;
  2115. void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
  2116. bool abandon_listen_socket();
  2117. bool routing(Request &req, Response &res, Stream &strm,
  2118. bool skip_pre_routing);
  2119. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2120. bool handle_exception(Request &req, Response &res);
  2121. #endif
  2122. bool handle_file_request(Request &req, Response &res);
  2123. bool check_if_not_modified(const Request &req, Response &res,
  2124. const std::string &etag, time_t mtime) const;
  2125. bool check_if_range(Request &req, const std::string &etag,
  2126. time_t mtime) const;
  2127. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  2128. Stream &strm);
  2129. bool dispatch_request_for_content_reader(
  2130. Request &req, Response &res, ContentReader content_reader,
  2131. const HandlersForContentReader &handlers) const;
  2132. bool parse_request_line(const char *s, Request &req) const;
  2133. detail::EncodingType static_file_encoding(const Request &req,
  2134. const Response &res,
  2135. const std::string &content_type,
  2136. size_t length) const;
  2137. bool apply_static_file_compression(const Request &req, Response &res) const;
  2138. void apply_ranges(const Request &req, Response &res,
  2139. std::string &content_type, std::string &boundary) const;
  2140. bool write_response(Stream &strm, bool close_connection, Request &req,
  2141. Response &res);
  2142. bool write_response_with_content(Stream &strm, bool close_connection,
  2143. const Request &req, Response &res);
  2144. bool write_response_core(Stream &strm, bool close_connection,
  2145. const Request &req, Response &res,
  2146. bool need_apply_ranges);
  2147. bool write_content_with_provider(Stream &strm, const Request &req,
  2148. Response &res, const std::string &boundary,
  2149. const std::string &content_type);
  2150. bool read_content(Stream &strm, Request &req, Response &res);
  2151. bool read_content_with_content_receiver(Stream &strm, Request &req,
  2152. Response &res,
  2153. ContentReceiver receiver,
  2154. FormDataHeader multipart_header,
  2155. ContentReceiver multipart_receiver);
  2156. bool read_content_core(Stream &strm, Request &req, Response &res,
  2157. ContentReceiver receiver,
  2158. FormDataHeader multipart_header,
  2159. ContentReceiver multipart_receiver) const;
  2160. virtual bool process_and_close_socket(socket_t sock);
  2161. // The connection that parking_loop() keeps for a socket it has accepted.
  2162. virtual std::shared_ptr<KeepAliveConnection>
  2163. new_keep_alive_connection(socket_t sock);
  2164. void output_log(const Request &req, const Response &res) const;
  2165. void output_pre_compression_log(const Request &req,
  2166. const Response &res) const;
  2167. void output_error_log(const Error &err, const Request *req) const;
  2168. std::atomic<bool> is_running_{false};
  2169. std::atomic<bool> is_decommissioned{false};
  2170. // Set when CustomRoute() refuses a registration. Written before listen(),
  2171. // read by is_valid() on the same thread, so it needs no synchronization.
  2172. bool has_invalid_registration_ = false;
  2173. struct MountPointEntry {
  2174. std::string mount_point;
  2175. std::string base_dir;
  2176. std::string resolved_base_dir;
  2177. Headers headers;
  2178. };
  2179. std::vector<MountPointEntry> base_dirs_;
  2180. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  2181. std::string default_file_mimetype_ = "application/octet-stream";
  2182. Handler file_request_handler_;
  2183. Handlers get_handlers_;
  2184. Handlers post_handlers_;
  2185. HandlersForContentReader post_handlers_for_content_reader_;
  2186. Handlers put_handlers_;
  2187. HandlersForContentReader put_handlers_for_content_reader_;
  2188. Handlers patch_handlers_;
  2189. HandlersForContentReader patch_handlers_for_content_reader_;
  2190. Handlers delete_handlers_;
  2191. HandlersForContentReader delete_handlers_for_content_reader_;
  2192. Handlers options_handlers_;
  2193. CustomHandlers custom_handlers_;
  2194. struct WebSocketHandlerEntry {
  2195. std::unique_ptr<detail::MatcherBase> matcher;
  2196. WebSocketHandler handler;
  2197. SubProtocolSelector sub_protocol_selector;
  2198. };
  2199. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  2200. WebSocketHandlers websocket_handlers_;
  2201. HandlerWithResponse error_handler_;
  2202. ExceptionHandler exception_handler_;
  2203. HandlerWithResponse pre_routing_handler_;
  2204. Handler post_routing_handler_;
  2205. HandlerWithResponse pre_request_handler_;
  2206. Expect100ContinueHandler expect_100_continue_handler_;
  2207. StartHandler start_handler_;
  2208. mutable std::mutex logger_mutex_;
  2209. Logger logger_;
  2210. Logger pre_compression_logger_;
  2211. ErrorLogger error_logger_;
  2212. int address_family_ = AF_UNSPEC;
  2213. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2214. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2215. SocketOptions socket_options_ = default_socket_options;
  2216. Headers default_headers_;
  2217. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2218. detail::write_headers;
  2219. };
  2220. class Result {
  2221. public:
  2222. Result() = default;
  2223. Result(std::unique_ptr<Response> &&res, Error err,
  2224. Headers &&request_headers = Headers{})
  2225. : res_(std::move(res)), err_(err),
  2226. request_headers_(std::move(request_headers)) {}
  2227. // Response
  2228. operator bool() const { return res_ != nullptr; }
  2229. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  2230. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  2231. const Response &value() const { return *res_; }
  2232. Response &value() { return *res_; }
  2233. const Response &operator*() const { return *res_; }
  2234. Response &operator*() { return *res_; }
  2235. const Response *operator->() const { return res_.get(); }
  2236. Response *operator->() { return res_.get(); }
  2237. // Error
  2238. Error error() const { return err_; }
  2239. // Request Headers
  2240. bool has_request_header(const std::string &key) const;
  2241. std::string get_request_header_value(const std::string &key,
  2242. const char *def = "",
  2243. size_t id = 0) const;
  2244. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  2245. size_t id = 0) const;
  2246. size_t get_request_header_value_count(const std::string &key) const;
  2247. private:
  2248. std::unique_ptr<Response> res_;
  2249. Error err_ = Error::Unknown;
  2250. Headers request_headers_;
  2251. #ifdef CPPHTTPLIB_SSL_ENABLED
  2252. public:
  2253. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2254. int ssl_error)
  2255. : res_(std::move(res)), err_(err),
  2256. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  2257. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2258. int ssl_error, uint64_t ssl_backend_error)
  2259. : res_(std::move(res)), err_(err),
  2260. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  2261. ssl_backend_error_(ssl_backend_error) {}
  2262. int ssl_error() const { return ssl_error_; }
  2263. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  2264. private:
  2265. int ssl_error_ = 0;
  2266. uint64_t ssl_backend_error_ = 0;
  2267. #endif
  2268. };
  2269. struct ClientConnection {
  2270. socket_t sock = INVALID_SOCKET;
  2271. bool is_open() const { return sock != INVALID_SOCKET; }
  2272. ClientConnection() = default;
  2273. ~ClientConnection();
  2274. ClientConnection(const ClientConnection &) = delete;
  2275. ClientConnection &operator=(const ClientConnection &) = delete;
  2276. ClientConnection(ClientConnection &&other) noexcept
  2277. : sock(other.sock)
  2278. #ifdef CPPHTTPLIB_SSL_ENABLED
  2279. ,
  2280. session(other.session)
  2281. #endif
  2282. {
  2283. other.sock = INVALID_SOCKET;
  2284. #ifdef CPPHTTPLIB_SSL_ENABLED
  2285. other.session = nullptr;
  2286. #endif
  2287. }
  2288. ClientConnection &operator=(ClientConnection &&other) noexcept {
  2289. if (this != &other) {
  2290. sock = other.sock;
  2291. other.sock = INVALID_SOCKET;
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. session = other.session;
  2294. other.session = nullptr;
  2295. #endif
  2296. }
  2297. return *this;
  2298. }
  2299. #ifdef CPPHTTPLIB_SSL_ENABLED
  2300. tls::session_t session = nullptr;
  2301. #endif
  2302. };
  2303. namespace detail {
  2304. struct ChunkedDecoder;
  2305. struct BodyReader {
  2306. Stream *stream = nullptr;
  2307. bool has_content_length = false;
  2308. size_t content_length = 0;
  2309. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2310. size_t bytes_read = 0;
  2311. bool chunked = false;
  2312. bool eof = false;
  2313. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  2314. Error last_error = Error::Success;
  2315. ssize_t read(char *buf, size_t len);
  2316. bool has_error() const { return last_error != Error::Success; }
  2317. };
  2318. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  2319. size_t len) {
  2320. (void)stream;
  2321. return br.read(buf, len);
  2322. }
  2323. class decompressor;
  2324. enum class NoProxyKind {
  2325. Wildcard, // "*"
  2326. HostnameSuffix, // "example.com" or ".example.com"
  2327. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  2328. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  2329. };
  2330. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  2331. // Lets one CIDR matcher cover both families.
  2332. using IPBytes = std::array<uint8_t, 16>;
  2333. struct NoProxyEntry {
  2334. NoProxyKind kind = NoProxyKind::Wildcard;
  2335. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  2336. IPBytes net{};
  2337. int prefix_bits = 0;
  2338. };
  2339. struct NormalizedTarget {
  2340. std::string hostname; // lowercase; brackets and trailing dot removed
  2341. bool is_ipv4 = false;
  2342. bool is_ipv6 = false;
  2343. IPBytes ip{};
  2344. };
  2345. } // namespace detail
  2346. class ClientImpl {
  2347. public:
  2348. explicit ClientImpl(const std::string &host);
  2349. explicit ClientImpl(const std::string &host, int port);
  2350. explicit ClientImpl(const std::string &host, int port,
  2351. const std::string &client_cert_path,
  2352. const std::string &client_key_path);
  2353. virtual ~ClientImpl();
  2354. virtual bool is_valid() const;
  2355. struct StreamHandle {
  2356. std::unique_ptr<Response> response;
  2357. Error error = Error::Success;
  2358. StreamHandle() = default;
  2359. StreamHandle(const StreamHandle &) = delete;
  2360. StreamHandle &operator=(const StreamHandle &) = delete;
  2361. StreamHandle(StreamHandle &&) = default;
  2362. StreamHandle &operator=(StreamHandle &&) = default;
  2363. ~StreamHandle() = default;
  2364. bool is_valid() const {
  2365. return response != nullptr && error == Error::Success;
  2366. }
  2367. ssize_t read(char *buf, size_t len);
  2368. void parse_trailers_if_needed();
  2369. Error get_read_error() const { return body_reader_.last_error; }
  2370. bool has_read_error() const { return body_reader_.has_error(); }
  2371. bool trailers_parsed_ = false;
  2372. private:
  2373. friend class ClientImpl;
  2374. friend class sse::SSEClient;
  2375. ssize_t read_with_decompression(char *buf, size_t len);
  2376. std::unique_ptr<ClientConnection> connection_;
  2377. std::unique_ptr<Stream> socket_stream_;
  2378. Stream *stream_ = nullptr;
  2379. detail::BodyReader body_reader_;
  2380. std::unique_ptr<detail::decompressor> decompressor_;
  2381. std::string decompress_buffer_;
  2382. size_t decompress_offset_ = 0;
  2383. size_t decompressed_bytes_read_ = 0;
  2384. };
  2385. // clang-format off
  2386. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2387. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2388. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2389. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2390. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2391. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2392. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2393. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2394. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2395. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2396. Result Head(const std::string &path);
  2397. Result Head(const std::string &path, const Headers &headers);
  2398. Result Post(const std::string &path);
  2399. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2400. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2401. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2402. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2403. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2404. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2405. Result Post(const std::string &path, const Params &params);
  2406. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2407. Result Post(const std::string &path, const Headers &headers);
  2408. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2409. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2410. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2411. 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);
  2412. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2413. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2414. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2415. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2416. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2417. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2418. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2419. Result Put(const std::string &path);
  2420. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2421. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2422. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2423. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2424. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2425. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2426. Result Put(const std::string &path, const Params &params);
  2427. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2428. Result Put(const std::string &path, const Headers &headers);
  2429. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2430. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2431. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2432. 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);
  2433. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2434. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2435. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2436. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2437. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2438. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2439. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2440. Result Patch(const std::string &path);
  2441. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2442. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2443. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2444. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2445. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2446. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2447. Result Patch(const std::string &path, const Params &params);
  2448. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2449. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  2450. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2451. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2452. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2453. 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);
  2454. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2455. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2456. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2457. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2458. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2459. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2460. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2461. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2462. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2463. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2464. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2465. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2466. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2467. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2468. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2469. Result Options(const std::string &path);
  2470. Result Options(const std::string &path, const Headers &headers);
  2471. // clang-format on
  2472. // Streaming API: Open a stream for reading response body incrementally
  2473. // Socket ownership is transferred to StreamHandle for true streaming
  2474. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2475. StreamHandle open_stream(const std::string &method, const std::string &path,
  2476. const Params &params = {},
  2477. const Headers &headers = {},
  2478. const std::string &body = {},
  2479. const std::string &content_type = {});
  2480. bool send(Request &req, Response &res, Error &error);
  2481. Result send(const Request &req);
  2482. void stop();
  2483. std::string host() const;
  2484. int port() const;
  2485. size_t is_socket_open() const;
  2486. socket_t socket() const;
  2487. [[deprecated("Use set_direct_hostname_addr_map() instead.")]]
  2488. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2489. void
  2490. set_direct_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2491. void
  2492. set_tunnel_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2493. void set_default_headers(Headers headers);
  2494. void
  2495. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2496. void set_address_family(int family);
  2497. void set_tcp_nodelay(bool on);
  2498. void set_ipv6_v6only(bool on);
  2499. void set_socket_options(SocketOptions socket_options);
  2500. void set_connection_timeout(time_t sec, time_t usec = 0);
  2501. template <class Rep, class Period>
  2502. void
  2503. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2504. void set_read_timeout(time_t sec, time_t usec = 0);
  2505. template <class Rep, class Period>
  2506. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2507. void set_write_timeout(time_t sec, time_t usec = 0);
  2508. template <class Rep, class Period>
  2509. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2510. void set_max_timeout(time_t msec);
  2511. template <class Rep, class Period>
  2512. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2513. void set_basic_auth(const std::string &username, const std::string &password);
  2514. void set_bearer_token_auth(const std::string &token);
  2515. void set_keep_alive(bool on);
  2516. void set_follow_location(bool on);
  2517. void set_path_encode(bool on);
  2518. void set_compress(bool on);
  2519. void set_decompress(bool on);
  2520. void set_payload_max_length(size_t length);
  2521. void set_interface(const std::string &intf);
  2522. void set_proxy(const std::string &host, int port);
  2523. void set_proxy_basic_auth(const std::string &username,
  2524. const std::string &password);
  2525. void set_proxy_bearer_token_auth(const std::string &token);
  2526. void set_no_proxy(const std::vector<std::string> &patterns);
  2527. void set_logger(Logger logger);
  2528. void set_error_logger(ErrorLogger error_logger);
  2529. protected:
  2530. struct Socket {
  2531. socket_t sock = INVALID_SOCKET;
  2532. // For Mbed TLS compatibility: start_time for request timeout tracking
  2533. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2534. bool is_open() const { return sock != INVALID_SOCKET; }
  2535. #ifdef CPPHTTPLIB_SSL_ENABLED
  2536. tls::session_t ssl = nullptr;
  2537. #endif
  2538. };
  2539. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  2540. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  2541. virtual bool setup_proxy_connection(
  2542. Socket &socket,
  2543. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2544. Response &res, bool &success, Error &error);
  2545. bool is_proxy_enabled_for_host(const std::string &host) const;
  2546. // All of:
  2547. // shutdown_ssl
  2548. // shutdown_socket
  2549. // close_socket
  2550. // disconnect
  2551. // should ONLY be called on socket_ with socket_mutex_ locked, or on a
  2552. // connection being opened, and only when no other thread is using it.
  2553. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  2554. void shutdown_socket(Socket &socket) const;
  2555. void close_socket(Socket &socket);
  2556. void disconnect(bool gracefully);
  2557. // Under socket_mutex_: whether the connection kept alive can take another
  2558. // request. One with anything to read, or one set up under TLS settings
  2559. // changed since, is closed instead.
  2560. bool socket_reusable();
  2561. // Makes socket_ ready for a request, with socket_mutex_ held by guard. A new
  2562. // connection is opened without the lock, so that stop() can end it.
  2563. bool
  2564. prepare_socket(std::unique_lock<std::mutex> &guard,
  2565. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2566. Response &res, bool &success, Error &error);
  2567. // TLS settings apply as a connection is set up, so a change makes the
  2568. // connection kept alive unfit for the next request.
  2569. void tls_settings_changed() { tls_settings_version_++; }
  2570. std::string make_request_target(const Request &req) const;
  2571. bool process_request(Stream &strm, Request &req, Response &res,
  2572. bool close_connection, Error &error);
  2573. bool write_content_with_provider(Stream &strm, const Request &req,
  2574. Error &error) const;
  2575. void output_log(const Request &req, const Response &res) const;
  2576. void output_error_log(const Error &err, const Request *req) const;
  2577. // Socket endpoint information
  2578. const std::string host_;
  2579. const int port_;
  2580. // Current open socket
  2581. Socket socket_;
  2582. mutable std::mutex socket_mutex_;
  2583. std::recursive_mutex request_mutex_;
  2584. // How many send() calls are running on this client, guarded by
  2585. // request_mutex_
  2586. size_t send_depth_ = 0;
  2587. // Also guarded by request_mutex_
  2588. size_t socket_tls_settings_version_ = 0;
  2589. // These are all protected under socket_mutex
  2590. size_t socket_requests_in_flight_ = 0;
  2591. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2592. bool socket_should_be_closed_when_request_is_done_ = false;
  2593. // Set by stop(), cleared as a send() or an open_stream() starts. Its waits
  2594. // poll it: shutdown() does not reach a connection being opened, nor wake a
  2595. // read on Windows.
  2596. std::atomic<bool> stop_requested_{false};
  2597. std::function<bool()> stop_interrupt() const {
  2598. return [this] { return stop_requested_.load(); };
  2599. }
  2600. std::atomic<size_t> tls_settings_version_{0};
  2601. // Hostname to connection target map. The value is an IP literal or another
  2602. // hostname; only the connection target changes, never the identity.
  2603. std::map<std::string, std::string> addr_map_;
  2604. // Hostname to CONNECT target map, used only through a proxy.
  2605. std::map<std::string, std::string> tunnel_addr_map_;
  2606. // Default headers
  2607. Headers default_headers_;
  2608. // Header writer
  2609. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2610. detail::write_headers;
  2611. // Settings
  2612. std::string client_cert_path_;
  2613. std::string client_key_path_;
  2614. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2615. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2616. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2617. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2618. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2619. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2620. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2621. std::string basic_auth_username_;
  2622. std::string basic_auth_password_;
  2623. std::string bearer_token_auth_token_;
  2624. bool keep_alive_ = false;
  2625. bool follow_location_ = false;
  2626. bool path_encode_ = true;
  2627. int address_family_ = AF_UNSPEC;
  2628. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2629. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2630. SocketOptions socket_options_ = nullptr;
  2631. bool compress_ = false;
  2632. bool decompress_ = true;
  2633. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2634. bool has_payload_max_length_ = false;
  2635. std::string interface_;
  2636. std::string proxy_host_;
  2637. int proxy_port_ = -1;
  2638. std::string proxy_basic_auth_username_;
  2639. std::string proxy_basic_auth_password_;
  2640. std::string proxy_bearer_token_auth_token_;
  2641. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2642. mutable detail::NormalizedTarget host_normalized_;
  2643. mutable bool host_normalized_valid_ = false;
  2644. mutable std::mutex logger_mutex_;
  2645. Logger logger_;
  2646. ErrorLogger error_logger_;
  2647. private:
  2648. bool send_(Request &req, Response &res, Error &error);
  2649. Result send_(Request &&req);
  2650. socket_t create_client_socket(Error &error) const;
  2651. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2652. bool skip_100_continue = true) const;
  2653. bool write_request(Stream &strm, Request &req, bool close_connection,
  2654. Error &error, bool skip_body, bool &rejected_locally);
  2655. bool write_request_body(Stream &strm, Request &req, Error &error);
  2656. void prepare_default_headers(Request &r, bool for_stream,
  2657. const std::string &ct);
  2658. bool redirect(Request &req, Response &res, Error &error);
  2659. bool create_redirect_client(const std::string &scheme,
  2660. const std::string &host, int port, Request &req,
  2661. Response &res, const std::string &path,
  2662. const std::string &location, Error &error);
  2663. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2664. bool handle_request(Stream &strm, Request &req, Response &res,
  2665. bool close_connection, Error &error);
  2666. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2667. Request &req, const char *body, size_t content_length,
  2668. ContentProvider content_provider,
  2669. ContentProviderWithoutLength content_provider_without_length,
  2670. const std::string &content_type, ContentReceiver content_receiver,
  2671. Error &error);
  2672. Result send_with_content_provider_and_receiver(
  2673. const std::string &method, const std::string &path,
  2674. const Headers &headers, const char *body, size_t content_length,
  2675. ContentProvider content_provider,
  2676. ContentProviderWithoutLength content_provider_without_length,
  2677. const std::string &content_type, ContentReceiver content_receiver,
  2678. UploadProgress progress);
  2679. ContentProviderWithoutLength get_multipart_content_provider(
  2680. const std::string &boundary, const UploadFormDataItems &items,
  2681. const FormDataProviderItems &provider_items) const;
  2682. virtual bool
  2683. process_socket(const Socket &socket,
  2684. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2685. std::function<bool(Stream &strm)> callback);
  2686. virtual bool is_ssl() const;
  2687. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2688. StreamHandle open_stream_(Request &req);
  2689. void add_credential_headers(Request &req);
  2690. std::string proxy_target_prefix() const;
  2691. #ifdef CPPHTTPLIB_SSL_ENABLED
  2692. public:
  2693. void set_digest_auth(const std::string &username,
  2694. const std::string &password);
  2695. void set_proxy_digest_auth(const std::string &username,
  2696. const std::string &password);
  2697. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2698. const std::string &ca_cert_dir_path = std::string());
  2699. void enable_server_certificate_verification(bool enabled);
  2700. void enable_server_hostname_verification(bool enabled);
  2701. void enable_system_ca(bool enabled);
  2702. protected:
  2703. std::string digest_auth_username_;
  2704. std::string digest_auth_password_;
  2705. std::string proxy_digest_auth_username_;
  2706. std::string proxy_digest_auth_password_;
  2707. std::string ca_cert_file_path_;
  2708. std::string ca_cert_dir_path_;
  2709. bool server_certificate_verification_ = true;
  2710. bool server_hostname_verification_ = true;
  2711. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2712. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2713. int last_ssl_error_ = 0;
  2714. uint64_t last_backend_error_ = 0;
  2715. #endif
  2716. };
  2717. namespace detail {
  2718. // Stands in for a client that Client could not make from its arguments, so a
  2719. // request fails rather than going through a null pointer.
  2720. class InvalidClientImpl final : public ClientImpl {
  2721. public:
  2722. InvalidClientImpl() : ClientImpl(std::string(), 0) {}
  2723. bool is_valid() const override { return false; }
  2724. private:
  2725. bool create_and_connect_socket(Socket &, Error &error) override {
  2726. error = Error::Connection;
  2727. return false;
  2728. }
  2729. };
  2730. } // namespace detail
  2731. class Client {
  2732. public:
  2733. // Universal interface
  2734. explicit Client(const std::string &scheme_host_port);
  2735. explicit Client(const std::string &scheme_host_port,
  2736. const std::string &client_cert_path,
  2737. const std::string &client_key_path);
  2738. // HTTP only interface
  2739. explicit Client(const std::string &host, int port);
  2740. explicit Client(const std::string &host, int port,
  2741. const std::string &client_cert_path,
  2742. const std::string &client_key_path);
  2743. Client(Client &&) = default;
  2744. Client &operator=(Client &&) = default;
  2745. ~Client();
  2746. bool is_valid() const;
  2747. // clang-format off
  2748. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2749. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2750. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2751. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2752. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2753. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2754. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2755. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2756. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2757. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2758. Result Head(const std::string &path);
  2759. Result Head(const std::string &path, const Headers &headers);
  2760. Result Post(const std::string &path);
  2761. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2762. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2763. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2764. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2765. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2766. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2767. Result Post(const std::string &path, const Params &params);
  2768. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2769. Result Post(const std::string &path, const Headers &headers);
  2770. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2771. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2772. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2773. 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);
  2774. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2775. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2776. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2777. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2778. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2779. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2780. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2781. Result Put(const std::string &path);
  2782. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2783. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2784. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2785. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2786. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2787. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2788. Result Put(const std::string &path, const Params &params);
  2789. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2790. Result Put(const std::string &path, const Headers &headers);
  2791. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2792. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2793. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2794. 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);
  2795. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2796. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2797. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2798. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2799. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2800. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2801. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2802. Result Patch(const std::string &path);
  2803. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2804. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2805. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2806. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2807. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2808. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2809. Result Patch(const std::string &path, const Params &params);
  2810. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2811. Result Patch(const std::string &path, const Headers &headers);
  2812. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2813. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2814. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2815. 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);
  2816. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2817. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2818. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2819. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2820. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2821. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2822. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2823. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2824. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2825. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2826. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2827. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2828. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2829. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2830. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2831. Result Options(const std::string &path);
  2832. Result Options(const std::string &path, const Headers &headers);
  2833. // clang-format on
  2834. // Streaming API: Open a stream for reading response body incrementally
  2835. // Socket ownership is transferred to StreamHandle for true streaming
  2836. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2837. ClientImpl::StreamHandle open_stream(const std::string &method,
  2838. const std::string &path,
  2839. const Params &params = {},
  2840. const Headers &headers = {},
  2841. const std::string &body = {},
  2842. const std::string &content_type = {});
  2843. bool send(Request &req, Response &res, Error &error);
  2844. Result send(const Request &req);
  2845. void stop();
  2846. std::string host() const;
  2847. int port() const;
  2848. size_t is_socket_open() const;
  2849. socket_t socket() const;
  2850. [[deprecated("Use set_direct_hostname_addr_map() instead.")]]
  2851. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2852. void
  2853. set_direct_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2854. void
  2855. set_tunnel_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2856. void set_default_headers(Headers headers);
  2857. void
  2858. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2859. void set_address_family(int family);
  2860. void set_tcp_nodelay(bool on);
  2861. void set_socket_options(SocketOptions socket_options);
  2862. void set_connection_timeout(time_t sec, time_t usec = 0);
  2863. template <class Rep, class Period>
  2864. void
  2865. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2866. void set_read_timeout(time_t sec, time_t usec = 0);
  2867. template <class Rep, class Period>
  2868. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2869. void set_write_timeout(time_t sec, time_t usec = 0);
  2870. template <class Rep, class Period>
  2871. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2872. void set_max_timeout(time_t msec);
  2873. template <class Rep, class Period>
  2874. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2875. void set_basic_auth(const std::string &username, const std::string &password);
  2876. void set_bearer_token_auth(const std::string &token);
  2877. void set_keep_alive(bool on);
  2878. void set_follow_location(bool on);
  2879. void set_path_encode(bool on);
  2880. void set_compress(bool on);
  2881. void set_decompress(bool on);
  2882. void set_payload_max_length(size_t length);
  2883. void set_interface(const std::string &intf);
  2884. void set_proxy(const std::string &host, int port);
  2885. void set_proxy_basic_auth(const std::string &username,
  2886. const std::string &password);
  2887. void set_proxy_bearer_token_auth(const std::string &token);
  2888. void set_no_proxy(const std::vector<std::string> &patterns);
  2889. void set_logger(Logger logger);
  2890. void set_error_logger(ErrorLogger error_logger);
  2891. private:
  2892. std::unique_ptr<ClientImpl> cli_;
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. public:
  2895. void set_digest_auth(const std::string &username,
  2896. const std::string &password);
  2897. void set_proxy_digest_auth(const std::string &username,
  2898. const std::string &password);
  2899. void enable_server_certificate_verification(bool enabled);
  2900. void enable_server_hostname_verification(bool enabled);
  2901. void enable_system_ca(bool enabled);
  2902. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2903. const std::string &ca_cert_dir_path = std::string());
  2904. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2905. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2906. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2907. void set_session_verifier(
  2908. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2909. tls::ctx_t tls_context() const;
  2910. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2911. void enable_windows_certificate_verification(bool enabled);
  2912. #endif
  2913. private:
  2914. bool is_ssl_ = false;
  2915. #endif
  2916. };
  2917. #ifdef CPPHTTPLIB_SSL_ENABLED
  2918. class SSLServer : public Server {
  2919. public:
  2920. SSLServer(const char *cert_path, const char *private_key_path,
  2921. const char *client_ca_cert_file_path = nullptr,
  2922. const char *client_ca_cert_dir_path = nullptr,
  2923. const char *private_key_password = nullptr);
  2924. struct PemMemory {
  2925. const char *cert_pem;
  2926. size_t cert_pem_len;
  2927. const char *key_pem;
  2928. size_t key_pem_len;
  2929. const char *client_ca_pem;
  2930. size_t client_ca_pem_len;
  2931. const char *private_key_password;
  2932. };
  2933. explicit SSLServer(const PemMemory &pem);
  2934. // The callback receives the ctx_t handle which can be cast to the
  2935. // appropriate backend type (SSL_CTX* for OpenSSL,
  2936. // tls::impl::MbedTlsContext* for Mbed TLS)
  2937. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2938. ~SSLServer() override;
  2939. bool is_valid() const override;
  2940. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2941. const char *client_ca_pem = nullptr,
  2942. const char *password = nullptr);
  2943. tls::ctx_t tls_context() const { return ctx_; }
  2944. int ssl_last_error() const { return last_ssl_error_; }
  2945. private:
  2946. bool process_and_close_socket(socket_t sock) override;
  2947. std::shared_ptr<KeepAliveConnection>
  2948. new_keep_alive_connection(socket_t sock) override;
  2949. struct TlsConnection;
  2950. // Creates a session and runs the handshake. Null on failure, which sets
  2951. // last_ssl_error_.
  2952. tls::session_t start_session(socket_t sock);
  2953. tls::ctx_t ctx_ = nullptr;
  2954. // update_certs_pem() replaces the certificates and CAs that handshakes read
  2955. // from ctx_, so it waits for the handshakes in progress, which their timeout
  2956. // bounds, and new ones wait while it is pending so that they cannot keep it
  2957. // waiting.
  2958. std::mutex ctx_mutex_;
  2959. std::condition_variable ctx_cv_;
  2960. size_t handshakes_in_progress_ = 0;
  2961. size_t updates_pending_ = 0;
  2962. int last_ssl_error_ = 0;
  2963. };
  2964. class SSLClient final : public ClientImpl {
  2965. public:
  2966. explicit SSLClient(const std::string &host);
  2967. explicit SSLClient(const std::string &host, int port);
  2968. explicit SSLClient(const std::string &host, int port,
  2969. const std::string &client_cert_path,
  2970. const std::string &client_key_path,
  2971. const std::string &private_key_password = std::string());
  2972. struct PemMemory {
  2973. const char *cert_pem;
  2974. size_t cert_pem_len;
  2975. const char *key_pem;
  2976. size_t key_pem_len;
  2977. const char *private_key_password;
  2978. };
  2979. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2980. ~SSLClient() override;
  2981. bool is_valid() const override;
  2982. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2983. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2984. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2985. // Post-handshake session verifier (backend-independent)
  2986. void set_session_verifier(
  2987. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2988. tls::ctx_t tls_context() const { return ctx_; }
  2989. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2990. void enable_windows_certificate_verification(bool enabled);
  2991. #endif
  2992. private:
  2993. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2994. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2995. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2996. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2997. bool
  2998. process_socket(const Socket &socket,
  2999. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3000. std::function<bool(Stream &strm)> callback) override;
  3001. bool is_ssl() const override;
  3002. bool setup_proxy_connection(
  3003. Socket &socket,
  3004. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3005. Response &res, bool &success, Error &error) override;
  3006. bool connect_with_proxy(
  3007. Socket &sock,
  3008. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3009. Response &res, bool &success, Error &error);
  3010. bool initialize_ssl(Socket &socket, Error &error);
  3011. void init_ctx();
  3012. void reset_ctx_on_error();
  3013. bool load_certs();
  3014. tls::ctx_t ctx_ = nullptr;
  3015. std::mutex ctx_mutex_;
  3016. std::once_flag initialize_cert_;
  3017. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  3018. // since the store handle itself is owned by ctx_ and leaves no other trace.
  3019. bool ca_cert_store_set_ = false;
  3020. // Set by set_ca_cert_store() and load_ca_cert_store() even when they bring
  3021. // no certificate, so that a CA that failed to come through fails
  3022. // verification instead of letting the system CAs in.
  3023. bool custom_ca_loaded_ = false;
  3024. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  3025. // Like ca_cert_store_set_, keeps what ctx_ cannot report back: the verifier
  3026. // set_server_certificate_verifier() installed there.
  3027. tls::VerifyCallback server_certificate_verifier_;
  3028. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  3029. bool enable_windows_cert_verification_ = true;
  3030. #endif
  3031. friend class ClientImpl;
  3032. };
  3033. #endif // CPPHTTPLIB_SSL_ENABLED
  3034. namespace detail {
  3035. template <typename T, typename U>
  3036. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  3037. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  3038. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  3039. duration - std::chrono::seconds(sec))
  3040. .count();
  3041. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  3042. }
  3043. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  3044. return N - 1;
  3045. }
  3046. inline bool is_numeric(const std::string &str) {
  3047. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  3048. }
  3049. // std::ranges::next(first, n, last) for C++11
  3050. template <typename It> inline It bounded_next(It first, size_t n, It last) {
  3051. for (; n > 0 && first != last; --n) {
  3052. ++first;
  3053. }
  3054. return first;
  3055. }
  3056. inline size_t get_header_value_u64(const Headers &headers,
  3057. const std::string &key, size_t def,
  3058. size_t id, bool &is_invalid_value) {
  3059. is_invalid_value = false;
  3060. auto rng = headers.equal_range(key);
  3061. auto it = bounded_next(rng.first, id, rng.second);
  3062. if (it != rng.second) {
  3063. if (is_numeric(it->second)) {
  3064. // Parse at size_t width so an out-of-range Content-Length is reported
  3065. // rather than silently saturated/truncated (a value above 2^32 would
  3066. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  3067. // and return SIZE_MAX so the existing oversized-value guards reject it.
  3068. size_t val = 0;
  3069. const auto &s = it->second;
  3070. auto r = from_chars(s.data(), s.data() + s.size(), val);
  3071. if (r.ec == std::errc::result_out_of_range) {
  3072. is_invalid_value = true;
  3073. return (std::numeric_limits<size_t>::max)();
  3074. }
  3075. return val;
  3076. } else {
  3077. is_invalid_value = true;
  3078. }
  3079. }
  3080. return def;
  3081. }
  3082. inline size_t get_header_value_u64(const Headers &headers,
  3083. const std::string &key, size_t def,
  3084. size_t id) {
  3085. auto dummy = false;
  3086. return get_header_value_u64(headers, key, def, id, dummy);
  3087. }
  3088. } // namespace detail
  3089. template <class Rep, class Period>
  3090. inline Server &
  3091. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3092. detail::duration_to_sec_and_usec(
  3093. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3094. return *this;
  3095. }
  3096. template <class Rep, class Period>
  3097. inline Server &
  3098. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3099. detail::duration_to_sec_and_usec(
  3100. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3101. return *this;
  3102. }
  3103. template <class Rep, class Period>
  3104. inline Server &
  3105. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  3106. detail::duration_to_sec_and_usec(
  3107. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  3108. return *this;
  3109. }
  3110. template <class Rep, class Period>
  3111. inline void ClientImpl::set_connection_timeout(
  3112. const std::chrono::duration<Rep, Period> &duration) {
  3113. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  3114. set_connection_timeout(sec, usec);
  3115. });
  3116. }
  3117. template <class Rep, class Period>
  3118. inline void ClientImpl::set_read_timeout(
  3119. const std::chrono::duration<Rep, Period> &duration) {
  3120. detail::duration_to_sec_and_usec(
  3121. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3122. }
  3123. template <class Rep, class Period>
  3124. inline void ClientImpl::set_write_timeout(
  3125. const std::chrono::duration<Rep, Period> &duration) {
  3126. detail::duration_to_sec_and_usec(
  3127. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3128. }
  3129. template <class Rep, class Period>
  3130. inline void ClientImpl::set_max_timeout(
  3131. const std::chrono::duration<Rep, Period> &duration) {
  3132. auto msec =
  3133. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  3134. set_max_timeout(static_cast<time_t>(msec));
  3135. }
  3136. template <class Rep, class Period>
  3137. inline void Client::set_connection_timeout(
  3138. const std::chrono::duration<Rep, Period> &duration) {
  3139. cli_->set_connection_timeout(duration);
  3140. }
  3141. template <class Rep, class Period>
  3142. inline void
  3143. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3144. cli_->set_read_timeout(duration);
  3145. }
  3146. template <class Rep, class Period>
  3147. inline void
  3148. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3149. cli_->set_write_timeout(duration);
  3150. }
  3151. inline void Client::set_max_timeout(time_t msec) {
  3152. cli_->set_max_timeout(msec);
  3153. }
  3154. template <class Rep, class Period>
  3155. inline void
  3156. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3157. cli_->set_max_timeout(duration);
  3158. }
  3159. /*
  3160. * Forward declarations and types that will be part of the .h file if split into
  3161. * .h + .cc.
  3162. */
  3163. std::string hosted_at(const std::string &hostname);
  3164. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  3165. // JavaScript-style URL encoding/decoding functions
  3166. std::string encode_uri_component(const std::string &value);
  3167. std::string encode_uri(const std::string &value);
  3168. std::string decode_uri_component(const std::string &value);
  3169. std::string decode_uri(const std::string &value);
  3170. // RFC 3986 compliant URL component encoding/decoding functions
  3171. std::string encode_path_component(const std::string &component);
  3172. std::string decode_path_component(const std::string &component);
  3173. std::string encode_query_component(const std::string &component,
  3174. bool space_as_plus = true);
  3175. std::string decode_query_component(const std::string &component,
  3176. bool plus_as_space = true);
  3177. std::string sanitize_filename(const std::string &filename);
  3178. std::string append_query_params(const std::string &path, const Params &params);
  3179. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  3180. std::pair<std::string, std::string>
  3181. make_basic_authentication_header(const std::string &username,
  3182. const std::string &password,
  3183. bool is_proxy = false);
  3184. namespace detail {
  3185. #if defined(_WIN32)
  3186. inline std::wstring u8string_to_wstring(const char *s) {
  3187. if (!s) { return std::wstring(); }
  3188. auto len = static_cast<int>(strlen(s));
  3189. if (!len) { return std::wstring(); }
  3190. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  3191. if (!wlen) { return std::wstring(); }
  3192. std::wstring ws;
  3193. ws.resize(wlen);
  3194. wlen = ::MultiByteToWideChar(
  3195. CP_UTF8, 0, s, len,
  3196. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  3197. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  3198. return ws;
  3199. }
  3200. #endif
  3201. struct FileStat {
  3202. FileStat(const std::string &path);
  3203. bool is_file() const;
  3204. bool is_dir() const;
  3205. time_t mtime() const;
  3206. size_t size() const;
  3207. private:
  3208. #if defined(_WIN32)
  3209. struct _stat st_;
  3210. #else
  3211. struct stat st_;
  3212. #endif
  3213. int ret_ = -1;
  3214. };
  3215. std::string make_host_and_port_string(const std::string &host, int port,
  3216. bool is_ssl);
  3217. template <typename T>
  3218. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  3219. Error &error);
  3220. bool write_data(Stream &strm, const char *d, size_t l);
  3221. std::string trim_copy(const std::string &s);
  3222. void divide(
  3223. const char *data, std::size_t size, char d,
  3224. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3225. fn);
  3226. void divide(
  3227. const std::string &str, char d,
  3228. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3229. fn);
  3230. void split(const char *b, const char *e, char d,
  3231. std::function<void(const char *, const char *)> fn);
  3232. void split(const char *b, const char *e, char d, size_t m,
  3233. std::function<void(const char *, const char *)> fn);
  3234. bool split_find(const char *b, const char *e, char d,
  3235. std::function<bool(const char *, const char *)> fn);
  3236. bool has_header_token(const Headers &headers, const std::string &key,
  3237. const std::string &token);
  3238. std::string websocket_accept_key(const std::string &client_key);
  3239. bool is_websocket_upgrade(const Request &req);
  3240. bool process_client_socket(
  3241. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3242. time_t write_timeout_sec, time_t write_timeout_usec,
  3243. time_t max_timeout_msec,
  3244. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3245. std::function<bool(Stream &)> callback);
  3246. socket_t create_client_socket(
  3247. const std::string &host, const std::string &ip, int port,
  3248. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  3249. SocketOptions socket_options, time_t connection_timeout_sec,
  3250. time_t connection_timeout_usec, time_t read_timeout_sec,
  3251. time_t read_timeout_usec, time_t write_timeout_sec,
  3252. time_t write_timeout_usec, const std::string &intf, Error &error,
  3253. const std::function<bool()> &interrupted = nullptr);
  3254. const char *get_header_value(const Headers &headers, const std::string &key,
  3255. const char *def, size_t id);
  3256. std::string get_combined_header_value(const Headers &headers,
  3257. const std::string &key);
  3258. std::string params_to_query_str(const Params &params);
  3259. void parse_query_text(const char *data, std::size_t size, Params &params);
  3260. void parse_query_text(const std::string &s, Params &params);
  3261. bool parse_multipart_boundary(const std::string &content_type,
  3262. std::string &boundary);
  3263. bool parse_range_header(const std::string &s, Ranges &ranges);
  3264. bool parse_accept_header(const std::string &s,
  3265. std::vector<std::string> &content_types);
  3266. void parse_disposition_params(const std::string &s, Params &params);
  3267. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  3268. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  3269. EncodingType encoding_type(const Request &req, const std::string &content_type);
  3270. EncodingType encoding_type(const Request &req, const Response &res,
  3271. const std::string &content_type);
  3272. EncodingType encoding_type(const Request &req, const Response &res);
  3273. // Creates a connected pair of stream sockets that child processes do not
  3274. // inherit. Windows has no socketpair(), so it is emulated there.
  3275. bool create_socket_pair(socket_t sv[2]);
  3276. // Ends a Poller's wait() from another thread. The poller watches fd() for
  3277. // readability, level-triggered, and calls drain() when it is reported.
  3278. class PollerWaker {
  3279. public:
  3280. ~PollerWaker();
  3281. // An eventfd on Linux, a socket pair elsewhere.
  3282. bool open();
  3283. socket_t fd() const { return fd_; }
  3284. // An address inside the poller, which no caller's token can be.
  3285. uintptr_t token() const { return reinterpret_cast<uintptr_t>(this); }
  3286. // From any thread. While one is pending, later calls make no syscall.
  3287. void wake() noexcept;
  3288. void drain() noexcept;
  3289. private:
  3290. socket_t fd_ = INVALID_SOCKET;
  3291. socket_t pair_fd_ = INVALID_SOCKET; // the end wake() writes; none on Linux
  3292. std::atomic<bool> pending_{false};
  3293. };
  3294. // One-shot readiness notification for a reactor:
  3295. // - A delivered event disarms the descriptor; arm() it again to wait again.
  3296. // - A hang-up or an error counts as readable.
  3297. // - Only an unarmed descriptor may be armed, and an armed one must be
  3298. // disarmed before it is closed.
  3299. // - wake() may be called from any thread; the rest belongs to one thread.
  3300. class Poller {
  3301. public:
  3302. using Token = uintptr_t;
  3303. virtual ~Poller() = default;
  3304. virtual bool arm(socket_t fd, Token token) = 0;
  3305. virtual void disarm(socket_t fd) = 0;
  3306. // Fills `ready` in no particular order and returns whether wake() was
  3307. // called. A negative timeout waits until either happens.
  3308. virtual bool wait(int timeout_ms, std::vector<Token> &ready) = 0;
  3309. virtual void wake() noexcept = 0;
  3310. };
  3311. // poll() on POSIX, WSAPoll() on Windows. Works everywhere.
  3312. class PollPoller final : public Poller {
  3313. public:
  3314. // nullptr when the descriptors cannot be created.
  3315. static std::unique_ptr<Poller> create();
  3316. bool arm(socket_t fd, Token token) override;
  3317. void disarm(socket_t fd) override;
  3318. bool wait(int timeout_ms, std::vector<Token> &ready) override;
  3319. void wake() noexcept override { waker_.wake(); }
  3320. private:
  3321. PollPoller() = default;
  3322. void remove_at(size_t index);
  3323. PollerWaker waker_;
  3324. // fds_[0] is the waker's, which is always armed; tokens_[i] belongs to
  3325. // fds_[i].
  3326. std::vector<struct pollfd> fds_;
  3327. std::vector<Token> tokens_;
  3328. std::unordered_map<socket_t, size_t> index_;
  3329. };
  3330. #ifdef __linux__
  3331. // epoll with EPOLLONESHOT. Waits in O(ready) instead of O(armed).
  3332. class EpollPoller final : public Poller {
  3333. public:
  3334. // nullptr when the descriptors cannot be created.
  3335. static std::unique_ptr<Poller> create();
  3336. ~EpollPoller() override;
  3337. bool arm(socket_t fd, Token token) override;
  3338. void disarm(socket_t fd) override;
  3339. bool wait(int timeout_ms, std::vector<Token> &ready) override;
  3340. void wake() noexcept override { waker_.wake(); }
  3341. private:
  3342. EpollPoller() = default;
  3343. int epfd_ = -1;
  3344. PollerWaker waker_; // always armed
  3345. std::vector<struct epoll_event> events_;
  3346. };
  3347. #endif
  3348. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  3349. // kqueue with EV_ONESHOT. Waits in O(ready) instead of O(armed).
  3350. class KqueuePoller final : public Poller {
  3351. public:
  3352. // nullptr when the descriptors cannot be created.
  3353. static std::unique_ptr<Poller> create();
  3354. ~KqueuePoller() override;
  3355. bool arm(socket_t fd, Token token) override;
  3356. void disarm(socket_t fd) override;
  3357. bool wait(int timeout_ms, std::vector<Token> &ready) override;
  3358. void wake() noexcept override { waker_.wake(); }
  3359. private:
  3360. KqueuePoller() = default;
  3361. int kq_ = -1;
  3362. PollerWaker waker_; // always armed
  3363. std::vector<struct kevent> events_;
  3364. };
  3365. #endif
  3366. // The best poller for this platform, or nullptr when it cannot be created.
  3367. std::unique_ptr<Poller> make_poller();
  3368. class BufferStream final : public Stream {
  3369. public:
  3370. BufferStream() = default;
  3371. ~BufferStream() override = default;
  3372. bool is_readable() const override;
  3373. bool wait_readable() const override;
  3374. bool wait_writable() const override;
  3375. ssize_t read(char *ptr, size_t size) override;
  3376. ssize_t write(const char *ptr, size_t size) override;
  3377. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3378. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3379. socket_t socket() const override;
  3380. time_t duration() const override;
  3381. const std::string &get_buffer() const;
  3382. private:
  3383. std::string buffer;
  3384. size_t position = 0;
  3385. };
  3386. class compressor {
  3387. public:
  3388. virtual ~compressor() = default;
  3389. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3390. virtual bool compress(const char *data, size_t data_length, bool last,
  3391. Callback callback) = 0;
  3392. };
  3393. class decompressor {
  3394. public:
  3395. virtual ~decompressor() = default;
  3396. virtual bool is_valid() const = 0;
  3397. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3398. virtual bool decompress(const char *data, size_t data_length,
  3399. Callback callback) = 0;
  3400. };
  3401. class nocompressor final : public compressor {
  3402. public:
  3403. ~nocompressor() override = default;
  3404. bool compress(const char *data, size_t data_length, bool /*last*/,
  3405. Callback callback) override;
  3406. };
  3407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3408. class gzip_compressor final : public compressor {
  3409. public:
  3410. gzip_compressor();
  3411. ~gzip_compressor() override;
  3412. bool compress(const char *data, size_t data_length, bool last,
  3413. Callback callback) override;
  3414. private:
  3415. bool is_valid_ = false;
  3416. z_stream strm_;
  3417. };
  3418. class gzip_decompressor final : public decompressor {
  3419. public:
  3420. gzip_decompressor();
  3421. ~gzip_decompressor() override;
  3422. bool is_valid() const override;
  3423. bool decompress(const char *data, size_t data_length,
  3424. Callback callback) override;
  3425. private:
  3426. bool is_valid_ = false;
  3427. z_stream strm_;
  3428. };
  3429. #endif
  3430. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3431. class brotli_compressor final : public compressor {
  3432. public:
  3433. brotli_compressor();
  3434. ~brotli_compressor();
  3435. bool compress(const char *data, size_t data_length, bool last,
  3436. Callback callback) override;
  3437. private:
  3438. BrotliEncoderState *state_ = nullptr;
  3439. };
  3440. class brotli_decompressor final : public decompressor {
  3441. public:
  3442. brotli_decompressor();
  3443. ~brotli_decompressor();
  3444. bool is_valid() const override;
  3445. bool decompress(const char *data, size_t data_length,
  3446. Callback callback) override;
  3447. private:
  3448. BrotliDecoderResult decoder_r;
  3449. BrotliDecoderState *decoder_s = nullptr;
  3450. };
  3451. #endif
  3452. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3453. class zstd_compressor : public compressor {
  3454. public:
  3455. zstd_compressor();
  3456. ~zstd_compressor();
  3457. bool compress(const char *data, size_t data_length, bool last,
  3458. Callback callback) override;
  3459. private:
  3460. ZSTD_CCtx *ctx_ = nullptr;
  3461. };
  3462. class zstd_decompressor : public decompressor {
  3463. public:
  3464. zstd_decompressor();
  3465. ~zstd_decompressor();
  3466. bool is_valid() const override;
  3467. bool decompress(const char *data, size_t data_length,
  3468. Callback callback) override;
  3469. private:
  3470. ZSTD_DCtx *ctx_ = nullptr;
  3471. };
  3472. #endif
  3473. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  3474. // to store data. The call can set memory on stack for performance.
  3475. class stream_line_reader {
  3476. public:
  3477. stream_line_reader(Stream &strm, char *fixed_buffer,
  3478. size_t fixed_buffer_size);
  3479. const char *ptr() const;
  3480. size_t size() const;
  3481. bool end_with_crlf() const;
  3482. bool getline();
  3483. private:
  3484. void append(char c);
  3485. void append(const char *data, size_t size);
  3486. Stream &strm_;
  3487. char *fixed_buffer_;
  3488. const size_t fixed_buffer_size_;
  3489. size_t fixed_buffer_used_size_ = 0;
  3490. std::string growable_buffer_;
  3491. };
  3492. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3493. const Headers &src_headers);
  3494. struct ChunkedDecoder {
  3495. Stream &strm;
  3496. size_t chunk_remaining = 0;
  3497. bool finished = false;
  3498. char line_buf[64];
  3499. size_t last_chunk_total = 0;
  3500. size_t last_chunk_offset = 0;
  3501. size_t overhead = 0;
  3502. explicit ChunkedDecoder(Stream &s);
  3503. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  3504. size_t &out_chunk_total);
  3505. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  3506. };
  3507. // A regular file opened to be served: mapped on Windows, read with pread()
  3508. // elsewhere.
  3509. class mmap {
  3510. public:
  3511. mmap(const char *path);
  3512. ~mmap();
  3513. bool open(const char *path);
  3514. void close();
  3515. bool is_open() const;
  3516. size_t size() const;
  3517. // Copies up to len bytes from offset into buf and returns how many: fewer,
  3518. // down to 0, if the file has shrunk since it was opened.
  3519. size_t read(size_t offset, char *buf, size_t len) const;
  3520. private:
  3521. #if defined(_WIN32)
  3522. HANDLE hFile_ = NULL;
  3523. HANDLE hMapping_ = NULL;
  3524. void *addr_ = nullptr;
  3525. bool is_open_empty_file = false;
  3526. #else
  3527. int fd_ = -1;
  3528. #endif
  3529. size_t size_ = 0;
  3530. };
  3531. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  3532. namespace fields {
  3533. bool is_token_char(char c);
  3534. bool is_token(const std::string &s);
  3535. bool is_field_name(const std::string &s);
  3536. bool is_vchar(char c);
  3537. bool is_obs_text(char c);
  3538. bool is_field_vchar(char c);
  3539. bool is_field_content(const std::string &s);
  3540. bool is_field_value(const std::string &s);
  3541. bool is_field_valid(const std::string &name, const std::string &value);
  3542. bool is_request_target(const std::string &s);
  3543. bool is_host(const std::string &s);
  3544. } // namespace fields
  3545. } // namespace detail
  3546. /*
  3547. * TLS Abstraction Layer Declarations
  3548. */
  3549. #ifdef CPPHTTPLIB_SSL_ENABLED
  3550. // TLS abstraction layer - backend-specific type declarations
  3551. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  3552. namespace tls {
  3553. namespace impl {
  3554. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  3555. // cert/key). This struct is accessible via tls::impl for use in SSL context
  3556. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  3557. struct MbedTlsContext {
  3558. mbedtls_ssl_config conf;
  3559. #ifndef CPPHTTPLIB_MBEDTLS_V4
  3560. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  3561. mbedtls_entropy_context entropy;
  3562. mbedtls_ctr_drbg_context ctr_drbg;
  3563. #endif
  3564. mbedtls_x509_crt ca_chain;
  3565. mbedtls_x509_crt own_cert;
  3566. mbedtls_pk_context own_key;
  3567. bool is_server = false;
  3568. // Peer certificate required (set_verify_client()); a client defaults to true
  3569. bool verify_client = false;
  3570. // Set by tls::set_verify_callback().
  3571. VerifyCallback verify_callback;
  3572. MbedTlsContext();
  3573. ~MbedTlsContext();
  3574. MbedTlsContext(const MbedTlsContext &) = delete;
  3575. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  3576. };
  3577. } // namespace impl
  3578. } // namespace tls
  3579. #endif
  3580. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  3581. namespace tls {
  3582. namespace impl {
  3583. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  3584. // This struct is accessible via tls::impl for use in SSL context
  3585. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  3586. struct WolfSSLContext {
  3587. WOLFSSL_CTX *ctx = nullptr;
  3588. bool is_server = false;
  3589. // Peer certificate required (set_verify_client()); a client defaults to true
  3590. bool verify_client = false;
  3591. // Replaced under verify_callback_mutex()
  3592. std::shared_ptr<VerifyCallback> verify_callback;
  3593. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  3594. WolfSSLContext();
  3595. ~WolfSSLContext();
  3596. WolfSSLContext(const WolfSSLContext &) = delete;
  3597. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  3598. };
  3599. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  3600. struct WolfSSLCAStore {
  3601. std::string pem_data;
  3602. };
  3603. } // namespace impl
  3604. } // namespace tls
  3605. #endif
  3606. #endif // CPPHTTPLIB_SSL_ENABLED
  3607. namespace stream {
  3608. class Result {
  3609. public:
  3610. Result();
  3611. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  3612. Result(Result &&other) noexcept;
  3613. Result &operator=(Result &&other) noexcept;
  3614. Result(const Result &) = delete;
  3615. Result &operator=(const Result &) = delete;
  3616. // Response info
  3617. bool is_valid() const;
  3618. explicit operator bool() const;
  3619. int status() const;
  3620. const Headers &headers() const;
  3621. std::string get_header_value(const std::string &key,
  3622. const char *def = "") const;
  3623. bool has_header(const std::string &key) const;
  3624. Error error() const;
  3625. Error read_error() const;
  3626. bool has_read_error() const;
  3627. // Stream reading
  3628. bool next();
  3629. const char *data() const;
  3630. size_t size() const;
  3631. std::string read_all();
  3632. private:
  3633. ClientImpl::StreamHandle handle_;
  3634. std::string buffer_;
  3635. size_t current_size_ = 0;
  3636. size_t chunk_size_;
  3637. bool finished_ = false;
  3638. };
  3639. // GET
  3640. template <typename ClientType>
  3641. inline Result Get(ClientType &cli, const std::string &path,
  3642. size_t chunk_size = 8192) {
  3643. return Result{cli.open_stream("GET", path), chunk_size};
  3644. }
  3645. template <typename ClientType>
  3646. inline Result Get(ClientType &cli, const std::string &path,
  3647. const Headers &headers, size_t chunk_size = 8192) {
  3648. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  3649. }
  3650. template <typename ClientType>
  3651. inline Result Get(ClientType &cli, const std::string &path,
  3652. const Params &params, size_t chunk_size = 8192) {
  3653. return Result{cli.open_stream("GET", path, params), chunk_size};
  3654. }
  3655. template <typename ClientType>
  3656. inline Result Get(ClientType &cli, const std::string &path,
  3657. const Params &params, const Headers &headers,
  3658. size_t chunk_size = 8192) {
  3659. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  3660. }
  3661. // POST
  3662. template <typename ClientType>
  3663. inline Result Post(ClientType &cli, const std::string &path,
  3664. const std::string &body, const std::string &content_type,
  3665. size_t chunk_size = 8192) {
  3666. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  3667. chunk_size};
  3668. }
  3669. template <typename ClientType>
  3670. inline Result Post(ClientType &cli, const std::string &path,
  3671. const Headers &headers, const std::string &body,
  3672. const std::string &content_type, size_t chunk_size = 8192) {
  3673. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  3674. chunk_size};
  3675. }
  3676. template <typename ClientType>
  3677. inline Result Post(ClientType &cli, const std::string &path,
  3678. const Params &params, const std::string &body,
  3679. const std::string &content_type, size_t chunk_size = 8192) {
  3680. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  3681. chunk_size};
  3682. }
  3683. template <typename ClientType>
  3684. inline Result Post(ClientType &cli, const std::string &path,
  3685. const Params &params, const Headers &headers,
  3686. const std::string &body, const std::string &content_type,
  3687. size_t chunk_size = 8192) {
  3688. return Result{
  3689. cli.open_stream("POST", path, params, headers, body, content_type),
  3690. chunk_size};
  3691. }
  3692. // PUT
  3693. template <typename ClientType>
  3694. inline Result Put(ClientType &cli, const std::string &path,
  3695. const std::string &body, const std::string &content_type,
  3696. size_t chunk_size = 8192) {
  3697. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  3698. chunk_size};
  3699. }
  3700. template <typename ClientType>
  3701. inline Result Put(ClientType &cli, const std::string &path,
  3702. const Headers &headers, const std::string &body,
  3703. const std::string &content_type, size_t chunk_size = 8192) {
  3704. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  3705. chunk_size};
  3706. }
  3707. template <typename ClientType>
  3708. inline Result Put(ClientType &cli, const std::string &path,
  3709. const Params &params, const std::string &body,
  3710. const std::string &content_type, size_t chunk_size = 8192) {
  3711. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  3712. chunk_size};
  3713. }
  3714. template <typename ClientType>
  3715. inline Result Put(ClientType &cli, const std::string &path,
  3716. const Params &params, const Headers &headers,
  3717. const std::string &body, const std::string &content_type,
  3718. size_t chunk_size = 8192) {
  3719. return Result{
  3720. cli.open_stream("PUT", path, params, headers, body, content_type),
  3721. chunk_size};
  3722. }
  3723. // PATCH
  3724. template <typename ClientType>
  3725. inline Result Patch(ClientType &cli, const std::string &path,
  3726. const std::string &body, const std::string &content_type,
  3727. size_t chunk_size = 8192) {
  3728. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  3729. chunk_size};
  3730. }
  3731. template <typename ClientType>
  3732. inline Result Patch(ClientType &cli, const std::string &path,
  3733. const Headers &headers, const std::string &body,
  3734. const std::string &content_type, size_t chunk_size = 8192) {
  3735. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  3736. chunk_size};
  3737. }
  3738. template <typename ClientType>
  3739. inline Result Patch(ClientType &cli, const std::string &path,
  3740. const Params &params, const std::string &body,
  3741. const std::string &content_type, size_t chunk_size = 8192) {
  3742. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  3743. chunk_size};
  3744. }
  3745. template <typename ClientType>
  3746. inline Result Patch(ClientType &cli, const std::string &path,
  3747. const Params &params, const Headers &headers,
  3748. const std::string &body, const std::string &content_type,
  3749. size_t chunk_size = 8192) {
  3750. return Result{
  3751. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3752. chunk_size};
  3753. }
  3754. // DELETE
  3755. template <typename ClientType>
  3756. inline Result Delete(ClientType &cli, const std::string &path,
  3757. size_t chunk_size = 8192) {
  3758. return Result{cli.open_stream("DELETE", path), chunk_size};
  3759. }
  3760. template <typename ClientType>
  3761. inline Result Delete(ClientType &cli, const std::string &path,
  3762. const Headers &headers, size_t chunk_size = 8192) {
  3763. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3764. }
  3765. template <typename ClientType>
  3766. inline Result Delete(ClientType &cli, const std::string &path,
  3767. const std::string &body, const std::string &content_type,
  3768. size_t chunk_size = 8192) {
  3769. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3770. chunk_size};
  3771. }
  3772. template <typename ClientType>
  3773. inline Result Delete(ClientType &cli, const std::string &path,
  3774. const Headers &headers, const std::string &body,
  3775. const std::string &content_type,
  3776. size_t chunk_size = 8192) {
  3777. return Result{
  3778. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3779. chunk_size};
  3780. }
  3781. template <typename ClientType>
  3782. inline Result Delete(ClientType &cli, const std::string &path,
  3783. const Params &params, size_t chunk_size = 8192) {
  3784. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3785. }
  3786. template <typename ClientType>
  3787. inline Result Delete(ClientType &cli, const std::string &path,
  3788. const Params &params, const Headers &headers,
  3789. size_t chunk_size = 8192) {
  3790. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3791. }
  3792. template <typename ClientType>
  3793. inline Result Delete(ClientType &cli, const std::string &path,
  3794. const Params &params, const std::string &body,
  3795. const std::string &content_type,
  3796. size_t chunk_size = 8192) {
  3797. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3798. chunk_size};
  3799. }
  3800. template <typename ClientType>
  3801. inline Result Delete(ClientType &cli, const std::string &path,
  3802. const Params &params, const Headers &headers,
  3803. const std::string &body, const std::string &content_type,
  3804. size_t chunk_size = 8192) {
  3805. return Result{
  3806. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3807. chunk_size};
  3808. }
  3809. // HEAD
  3810. template <typename ClientType>
  3811. inline Result Head(ClientType &cli, const std::string &path,
  3812. size_t chunk_size = 8192) {
  3813. return Result{cli.open_stream("HEAD", path), chunk_size};
  3814. }
  3815. template <typename ClientType>
  3816. inline Result Head(ClientType &cli, const std::string &path,
  3817. const Headers &headers, size_t chunk_size = 8192) {
  3818. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3819. }
  3820. template <typename ClientType>
  3821. inline Result Head(ClientType &cli, const std::string &path,
  3822. const Params &params, size_t chunk_size = 8192) {
  3823. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3824. }
  3825. template <typename ClientType>
  3826. inline Result Head(ClientType &cli, const std::string &path,
  3827. const Params &params, const Headers &headers,
  3828. size_t chunk_size = 8192) {
  3829. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3830. }
  3831. // OPTIONS
  3832. template <typename ClientType>
  3833. inline Result Options(ClientType &cli, const std::string &path,
  3834. size_t chunk_size = 8192) {
  3835. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3836. }
  3837. template <typename ClientType>
  3838. inline Result Options(ClientType &cli, const std::string &path,
  3839. const Headers &headers, size_t chunk_size = 8192) {
  3840. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3841. }
  3842. template <typename ClientType>
  3843. inline Result Options(ClientType &cli, const std::string &path,
  3844. const Params &params, size_t chunk_size = 8192) {
  3845. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3846. }
  3847. template <typename ClientType>
  3848. inline Result Options(ClientType &cli, const std::string &path,
  3849. const Params &params, const Headers &headers,
  3850. size_t chunk_size = 8192) {
  3851. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3852. }
  3853. } // namespace stream
  3854. namespace sse {
  3855. struct SSEMessage {
  3856. std::string event; // Event type (default: "message")
  3857. std::string data; // Event payload
  3858. std::string id; // Event ID for Last-Event-ID header
  3859. SSEMessage();
  3860. void clear();
  3861. };
  3862. class SSEClient {
  3863. public:
  3864. using MessageHandler = std::function<void(const SSEMessage &)>;
  3865. using ErrorHandler = std::function<void(Error)>;
  3866. using OpenHandler = std::function<void()>;
  3867. SSEClient(Client &client, const std::string &path);
  3868. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3869. ~SSEClient();
  3870. SSEClient(const SSEClient &) = delete;
  3871. SSEClient &operator=(const SSEClient &) = delete;
  3872. // Event handlers
  3873. SSEClient &on_message(MessageHandler handler);
  3874. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3875. SSEClient &on_open(OpenHandler handler);
  3876. SSEClient &on_error(ErrorHandler handler);
  3877. SSEClient &set_reconnect_interval(int ms);
  3878. SSEClient &set_max_reconnect_attempts(int n);
  3879. // Update headers (thread-safe)
  3880. SSEClient &set_headers(const Headers &headers);
  3881. // State accessors
  3882. bool is_connected() const;
  3883. std::string last_event_id() const;
  3884. // Blocking start - runs event loop with auto-reconnect
  3885. void start();
  3886. // Non-blocking start - runs in background thread
  3887. void start_async();
  3888. // Stop the client (thread-safe)
  3889. void stop();
  3890. private:
  3891. void run_event_loop();
  3892. void dispatch_event(const SSEMessage &msg);
  3893. bool should_reconnect(int count) const;
  3894. void wait_for_reconnect();
  3895. // Client and path
  3896. Client &client_;
  3897. std::string path_;
  3898. Headers headers_;
  3899. mutable std::mutex headers_mutex_;
  3900. // Callbacks
  3901. MessageHandler on_message_;
  3902. std::map<std::string, MessageHandler> event_handlers_;
  3903. OpenHandler on_open_;
  3904. ErrorHandler on_error_;
  3905. // Configuration
  3906. int reconnect_interval_ms_ = 3000;
  3907. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3908. // State
  3909. std::atomic<bool> running_{false};
  3910. std::atomic<bool> connected_{false};
  3911. // Written by the event loop, which start_async() runs on its own thread
  3912. std::string last_event_id_;
  3913. mutable std::mutex last_event_id_mutex_;
  3914. // Async support
  3915. std::thread async_thread_;
  3916. };
  3917. } // namespace sse
  3918. namespace detail {
  3919. // Interprets an event stream fed in chunks of any size
  3920. class SSEParser {
  3921. public:
  3922. using EventHandler = std::function<void(const sse::SSEMessage &msg)>;
  3923. using IdHandler = std::function<void(const std::string &id)>;
  3924. using RetryHandler = std::function<void(int retry_ms)>;
  3925. SSEParser(EventHandler on_event, IdHandler on_id, RetryHandler on_retry,
  3926. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH);
  3927. // Returns false once the line and the event still waiting for their end
  3928. // exceed max_event_length. 0 means no limit.
  3929. bool parse(const char *buf, size_t n);
  3930. private:
  3931. void parse_line(const std::string &line);
  3932. EventHandler on_event_;
  3933. IdHandler on_id_;
  3934. RetryHandler on_retry_;
  3935. size_t max_event_length_;
  3936. std::string buffer_;
  3937. sse::SSEMessage msg_;
  3938. bool has_data_ = false;
  3939. bool has_id_ = false;
  3940. bool first_line_ = true;
  3941. bool after_cr_ = false;
  3942. };
  3943. } // namespace detail
  3944. namespace ws {
  3945. class WebSocketClient;
  3946. enum class Opcode : uint8_t {
  3947. Continuation = 0x0,
  3948. Text = 0x1,
  3949. Binary = 0x2,
  3950. Close = 0x8,
  3951. Ping = 0x9,
  3952. Pong = 0xA,
  3953. };
  3954. enum class CloseStatus : uint16_t {
  3955. Normal = 1000,
  3956. GoingAway = 1001,
  3957. ProtocolError = 1002,
  3958. UnsupportedData = 1003,
  3959. NoStatus = 1005,
  3960. Abnormal = 1006,
  3961. InvalidPayload = 1007,
  3962. PolicyViolation = 1008,
  3963. MessageTooBig = 1009,
  3964. MandatoryExtension = 1010,
  3965. InternalError = 1011,
  3966. };
  3967. // Timeout is returned only when a read timeout was set and it elapsed before
  3968. // any byte of a frame arrived: nothing was consumed and the connection is
  3969. // still open, so the caller can send on it and read again. `msg` is left
  3970. // untouched, so a `while (ws.read(msg))` loop must not treat it as a message.
  3971. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2, Timeout = 3 };
  3972. // Result of WebSocketClient::connect(). Truthy only when the WebSocket
  3973. // upgrade handshake fully succeeded. On failure error() identifies the
  3974. // failing layer; status()/headers() expose the server's upgrade response
  3975. // when one was received (status() is -1 otherwise), or the proxy's reply to
  3976. // CONNECT when error() is ProxyConnection.
  3977. class Result {
  3978. public:
  3979. Result() = default;
  3980. Result(Error err, int status, Headers &&headers)
  3981. : err_(err), status_(status), headers_(std::move(headers)) {}
  3982. explicit operator bool() const { return err_ == Error::Success; }
  3983. Error error() const { return err_; }
  3984. // Upgrade response info
  3985. int status() const { return status_; }
  3986. const Headers &headers() const { return headers_; }
  3987. std::string get_header_value(const std::string &key,
  3988. const char *def = "") const {
  3989. return detail::get_header_value(headers_, key, def, 0);
  3990. }
  3991. bool has_header(const std::string &key) const {
  3992. return headers_.find(key) != headers_.end();
  3993. }
  3994. #ifdef CPPHTTPLIB_SSL_ENABLED
  3995. Result(Error err, int status, Headers &&headers, int ssl_error,
  3996. uint64_t ssl_backend_error)
  3997. : err_(err), status_(status), headers_(std::move(headers)),
  3998. ssl_error_(ssl_error), ssl_backend_error_(ssl_backend_error) {}
  3999. int ssl_error() const { return ssl_error_; }
  4000. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  4001. #endif
  4002. private:
  4003. Error err_ = Error::Unknown; // a default-constructed Result is falsy
  4004. int status_ = -1;
  4005. Headers headers_;
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. int ssl_error_ = 0;
  4008. uint64_t ssl_backend_error_ = 0;
  4009. #endif
  4010. };
  4011. namespace impl {
  4012. bool is_valid_utf8(const std::string &s);
  4013. // A frame, a failure (the connection cannot be read on), a timeout with the
  4014. // stream still usable, or a frame the peer should not have sent: one that
  4015. // breaks the protocol, or one longer than the limit.
  4016. enum class FrameRead { Ok, Fail, Timeout, ProtocolError, TooBig };
  4017. // A frame read in as many calls as it takes. A timeout leaves what was read
  4018. // so far in place, and the next read() goes on from there, so the stream is
  4019. // usable after a timeout wherever in a frame it lands.
  4020. class FrameReader {
  4021. public:
  4022. FrameRead read(Stream &strm, Opcode &opcode, std::string &payload, bool &fin,
  4023. bool expect_masked, size_t max_len);
  4024. // Whether part of a frame has been read and the rest is still to come
  4025. bool begun() const { return have_ > 0; }
  4026. private:
  4027. void reset();
  4028. uint8_t head_[14] = {0}; // FIN + opcode, MASK + length, its extension, key
  4029. size_t have_ = 0; // bytes of the header read so far
  4030. size_t need_ = 2; // bytes of the header, once the second is read
  4031. bool sized_ = false; // the header is whole and its length checked
  4032. size_t len_ = 0; // the payload's length, once sized_
  4033. std::string payload_;
  4034. };
  4035. // A whole frame read in one go: a timeout before any of it came is reported,
  4036. // and one that cuts it short is a failure.
  4037. FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  4038. std::string &payload, bool &fin,
  4039. bool expect_masked, size_t max_len);
  4040. } // namespace impl
  4041. class WebSocket {
  4042. public:
  4043. WebSocket(const WebSocket &) = delete;
  4044. WebSocket &operator=(const WebSocket &) = delete;
  4045. ~WebSocket();
  4046. ReadResult read(std::string &msg);
  4047. bool send(const std::string &data);
  4048. bool send(const char *data, size_t len);
  4049. void close(CloseStatus status = CloseStatus::Normal,
  4050. const std::string &reason = "");
  4051. const Request &request() const;
  4052. bool is_open() const;
  4053. // Why the connection ended, once read() has returned Fail (RFC 6455 7.1.5,
  4054. // 7.1.6): the code and reason of the peer's Close, NoStatus when it had no
  4055. // code, ProtocolError when it was malformed, and Abnormal when none came.
  4056. // After a close() of our own, the peer's reply is what is reported.
  4057. CloseStatus close_status() const;
  4058. std::string close_reason() const;
  4059. // Bound how long read() waits before returning Timeout. 0 waits forever.
  4060. // A server handler owns its connection's timeout this way; a client sets it
  4061. // through WebSocketClient. Safe to call while another thread is in read().
  4062. // It lands anywhere, inside a message too: what was read of it is kept,
  4063. // and the next read() goes on from there.
  4064. //
  4065. // Only a timeout set here is reported as Timeout. The compile-time default
  4066. // (CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND) is a backstop rather
  4067. // than a request for control, so when it elapses read() returns Fail and
  4068. // closes the connection, and `while (ws.read(msg))` ends as it always has.
  4069. void set_read_timeout(time_t sec, time_t usec = 0);
  4070. template <class Rep, class Period>
  4071. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  4072. private:
  4073. friend class httplib::Server;
  4074. friend class httplib::ws::WebSocketClient;
  4075. WebSocket(
  4076. Stream &strm, const Request &req, bool is_server,
  4077. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  4078. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
  4079. std::function<bool()> server_stopping = nullptr)
  4080. : strm_(strm), req_(req), is_server_(is_server),
  4081. ping_interval_sec_(ping_interval_sec),
  4082. max_missed_pongs_(max_missed_pongs),
  4083. server_stopping_(std::move(server_stopping)) {
  4084. interrupt_reads();
  4085. start_heartbeat();
  4086. }
  4087. WebSocket(
  4088. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  4089. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  4090. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
  4091. std::function<bool()> server_stopping = nullptr)
  4092. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  4093. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  4094. max_missed_pongs_(max_missed_pongs),
  4095. server_stopping_(std::move(server_stopping)) {
  4096. interrupt_reads();
  4097. start_heartbeat();
  4098. }
  4099. void interrupt_reads();
  4100. bool server_stopping() const {
  4101. return server_stopping_ && server_stopping_();
  4102. }
  4103. void start_heartbeat();
  4104. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  4105. bool send_close(const std::string &payload);
  4106. void set_close_status(const std::string &payload);
  4107. Stream &strm_;
  4108. std::unique_ptr<Stream> owned_strm_;
  4109. Request req_;
  4110. bool is_server_;
  4111. time_t ping_interval_sec_;
  4112. int max_missed_pongs_;
  4113. int unacked_pings_ = 0;
  4114. std::atomic<bool> closed_{false};
  4115. // Set when the peer stopped answering pings, to end a read() waiting on it
  4116. std::atomic<bool> pong_timed_out_{false};
  4117. // A server connection's view of Server::stop(), which ends its read() too
  4118. std::function<bool()> server_stopping_;
  4119. // Set once the caller has bounded read() through set_read_timeout(). Until
  4120. // then the timeout in effect is the compile-time default, and elapsing it
  4121. // is a failure that closes the connection, not a Timeout.
  4122. std::atomic<bool> read_timeout_set_{false};
  4123. std::mutex write_mutex_;
  4124. // Owned by whichever thread is parsing frames off strm_. Only one thread
  4125. // may do so: a frame is read until it has the whole declared length,
  4126. // across several read() calls when a timeout lands inside it (frames_
  4127. // below), so a second parser stealing bytes silently corrupts the message
  4128. // the first one is assembling.
  4129. std::mutex read_mutex_;
  4130. // What read() has of the frame and the message it has not finished, kept
  4131. // across a timeout. Guarded by read_mutex_.
  4132. impl::FrameReader frames_;
  4133. std::string message_;
  4134. ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
  4135. // The peer's Close, set once under read_mutex_. close_reason_ is written
  4136. // before close_status_ leaves Abnormal and is not changed after.
  4137. std::atomic<CloseStatus> close_status_{CloseStatus::Abnormal};
  4138. std::string close_reason_;
  4139. std::thread ping_thread_;
  4140. std::mutex ping_mutex_;
  4141. std::condition_variable ping_cv_;
  4142. };
  4143. class WebSocketClient {
  4144. public:
  4145. explicit WebSocketClient(const std::string &scheme_host_port_path,
  4146. const Headers &headers = {});
  4147. ~WebSocketClient();
  4148. WebSocketClient(const WebSocketClient &) = delete;
  4149. WebSocketClient &operator=(const WebSocketClient &) = delete;
  4150. bool is_valid() const;
  4151. Result connect();
  4152. ReadResult read(std::string &msg);
  4153. bool send(const std::string &data);
  4154. bool send(const char *data, size_t len);
  4155. void close(CloseStatus status = CloseStatus::Normal,
  4156. const std::string &reason = "");
  4157. bool is_open() const;
  4158. CloseStatus close_status() const;
  4159. std::string close_reason() const;
  4160. const std::string &subprotocol() const;
  4161. void set_read_timeout(time_t sec, time_t usec = 0);
  4162. template <class Rep, class Period>
  4163. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  4164. void set_write_timeout(time_t sec, time_t usec = 0);
  4165. template <class Rep, class Period>
  4166. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  4167. void set_websocket_ping_interval(time_t sec);
  4168. void set_websocket_max_missed_pongs(int count);
  4169. void set_tcp_nodelay(bool on);
  4170. void set_address_family(int family);
  4171. void set_ipv6_v6only(bool on);
  4172. void set_socket_options(SocketOptions socket_options);
  4173. void set_connection_timeout(time_t sec, time_t usec = 0);
  4174. template <class Rep, class Period>
  4175. void
  4176. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  4177. void set_interface(const std::string &intf);
  4178. [[deprecated("Use set_direct_hostname_addr_map() instead.")]]
  4179. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  4180. void
  4181. set_direct_hostname_addr_map(std::map<std::string, std::string> addr_map);
  4182. void
  4183. set_tunnel_hostname_addr_map(std::map<std::string, std::string> addr_map);
  4184. void set_basic_auth(const std::string &username, const std::string &password);
  4185. void set_bearer_token_auth(const std::string &token);
  4186. void set_proxy(const std::string &host, int port);
  4187. void set_proxy_basic_auth(const std::string &username,
  4188. const std::string &password);
  4189. void set_proxy_bearer_token_auth(const std::string &token);
  4190. void set_no_proxy(const std::vector<std::string> &patterns);
  4191. #ifdef CPPHTTPLIB_SSL_ENABLED
  4192. struct PemMemory {
  4193. const char *cert_pem;
  4194. size_t cert_pem_len;
  4195. const char *key_pem;
  4196. size_t key_pem_len;
  4197. const char *private_key_password;
  4198. };
  4199. explicit WebSocketClient(const std::string &scheme_host_port_path,
  4200. const PemMemory &pem, const Headers &headers = {});
  4201. void set_ca_cert_path(const std::string &ca_cert_file_path,
  4202. const std::string &ca_cert_dir_path = std::string());
  4203. void set_ca_cert_store(tls::ca_store_t store);
  4204. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  4205. void enable_server_certificate_verification(bool enabled);
  4206. void enable_server_hostname_verification(bool enabled);
  4207. void enable_system_ca(bool enabled);
  4208. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  4209. void set_session_verifier(
  4210. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  4211. void set_proxy_digest_auth(const std::string &username,
  4212. const std::string &password);
  4213. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  4214. void enable_windows_certificate_verification(bool enabled);
  4215. #endif
  4216. #endif
  4217. private:
  4218. void shutdown_and_close();
  4219. std::pair<time_t, time_t> handshake_timeout() const;
  4220. bool create_stream(std::unique_ptr<Stream> &strm, Error &error,
  4221. int &ssl_error, uint64_t &ssl_backend_error);
  4222. void prepare_default_headers(Request &req);
  4223. bool is_proxy_enabled() const;
  4224. bool create_and_connect_socket(Error &error);
  4225. bool send_proxy_connect(Request &req, Response &proxy_res, Error &error);
  4226. bool connect_with_proxy(Response &proxy_res, Error &error);
  4227. std::string host_;
  4228. int port_;
  4229. std::string path_;
  4230. Headers headers_;
  4231. std::string subprotocol_;
  4232. bool is_valid_ = false;
  4233. socket_t sock_ = INVALID_SOCKET;
  4234. std::unique_ptr<WebSocket> ws_;
  4235. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND;
  4236. time_t read_timeout_usec_ = 0;
  4237. bool read_timeout_set_ = false; // see WebSocket::read_timeout_set_
  4238. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  4239. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  4240. time_t websocket_ping_interval_sec_ =
  4241. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  4242. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  4243. int address_family_ = AF_UNSPEC;
  4244. bool tcp_nodelay_ = CPPHTTPLIB_WEBSOCKET_TCP_NODELAY;
  4245. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  4246. SocketOptions socket_options_ = nullptr;
  4247. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  4248. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  4249. std::string interface_;
  4250. // Hostname to connection target map. The value is an IP literal or another
  4251. // hostname; only the connection target changes, never the identity.
  4252. std::map<std::string, std::string> addr_map_;
  4253. // Hostname to CONNECT target map, used only through a proxy.
  4254. std::map<std::string, std::string> tunnel_addr_map_;
  4255. std::string basic_auth_username_;
  4256. std::string basic_auth_password_;
  4257. std::string bearer_token_auth_token_;
  4258. std::string proxy_host_;
  4259. int proxy_port_ = -1;
  4260. std::string proxy_basic_auth_username_;
  4261. std::string proxy_basic_auth_password_;
  4262. std::string proxy_bearer_token_auth_token_;
  4263. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  4264. #ifdef CPPHTTPLIB_SSL_ENABLED
  4265. bool is_ssl_ = false;
  4266. tls::ctx_t tls_ctx_ = nullptr;
  4267. tls::session_t tls_session_ = nullptr;
  4268. std::string ca_cert_file_path_;
  4269. std::string ca_cert_dir_path_;
  4270. // Set by set_ca_cert_store() and load_ca_cert_store() even when they bring
  4271. // no certificate, so that a CA that failed to come through fails
  4272. // verification instead of letting the system CAs in.
  4273. bool custom_ca_loaded_ = false;
  4274. bool certs_loaded_ = false;
  4275. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  4276. bool server_certificate_verification_ = true;
  4277. bool server_hostname_verification_ = true;
  4278. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  4279. std::string proxy_digest_auth_username_;
  4280. std::string proxy_digest_auth_password_;
  4281. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  4282. bool enable_windows_cert_verification_ = true;
  4283. bool server_certificate_verifier_set_ = false;
  4284. #endif
  4285. #endif
  4286. };
  4287. template <class Rep, class Period>
  4288. inline void WebSocket::set_read_timeout(
  4289. const std::chrono::duration<Rep, Period> &duration) {
  4290. detail::duration_to_sec_and_usec(
  4291. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  4292. }
  4293. template <class Rep, class Period>
  4294. inline void WebSocketClient::set_read_timeout(
  4295. const std::chrono::duration<Rep, Period> &duration) {
  4296. detail::duration_to_sec_and_usec(
  4297. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  4298. }
  4299. template <class Rep, class Period>
  4300. inline void WebSocketClient::set_write_timeout(
  4301. const std::chrono::duration<Rep, Period> &duration) {
  4302. detail::duration_to_sec_and_usec(
  4303. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  4304. }
  4305. template <class Rep, class Period>
  4306. inline void WebSocketClient::set_connection_timeout(
  4307. const std::chrono::duration<Rep, Period> &duration) {
  4308. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  4309. set_connection_timeout(sec, usec);
  4310. });
  4311. }
  4312. } // namespace ws
  4313. namespace detail {
  4314. bool write_websocket_frame(Stream &strm, ws::Opcode opcode, const char *data,
  4315. size_t len, bool fin, bool mask);
  4316. } // namespace detail
  4317. // ----------------------------------------------------------------------------
  4318. /*
  4319. * Implementation that will be part of the .cc file if split into .h + .cc.
  4320. */
  4321. namespace stream {
  4322. // stream::Result implementations
  4323. inline Result::Result() : chunk_size_(8192) {}
  4324. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  4325. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  4326. inline Result::Result(Result &&other) noexcept
  4327. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  4328. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  4329. finished_(other.finished_) {
  4330. other.current_size_ = 0;
  4331. other.finished_ = true;
  4332. }
  4333. inline Result &Result::operator=(Result &&other) noexcept {
  4334. if (this != &other) {
  4335. handle_ = std::move(other.handle_);
  4336. buffer_ = std::move(other.buffer_);
  4337. current_size_ = other.current_size_;
  4338. chunk_size_ = other.chunk_size_;
  4339. finished_ = other.finished_;
  4340. other.current_size_ = 0;
  4341. other.finished_ = true;
  4342. }
  4343. return *this;
  4344. }
  4345. inline bool Result::is_valid() const { return handle_.is_valid(); }
  4346. inline Result::operator bool() const { return is_valid(); }
  4347. inline int Result::status() const {
  4348. return handle_.response ? handle_.response->status : -1;
  4349. }
  4350. inline const Headers &Result::headers() const {
  4351. static const Headers empty_headers;
  4352. return handle_.response ? handle_.response->headers : empty_headers;
  4353. }
  4354. inline std::string Result::get_header_value(const std::string &key,
  4355. const char *def) const {
  4356. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  4357. }
  4358. inline bool Result::has_header(const std::string &key) const {
  4359. return handle_.response ? handle_.response->has_header(key) : false;
  4360. }
  4361. inline Error Result::error() const { return handle_.error; }
  4362. inline Error Result::read_error() const { return handle_.get_read_error(); }
  4363. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  4364. inline bool Result::next() {
  4365. if (!handle_.is_valid() || finished_) { return false; }
  4366. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  4367. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  4368. if (n > 0) {
  4369. current_size_ = static_cast<size_t>(n);
  4370. return true;
  4371. }
  4372. current_size_ = 0;
  4373. finished_ = true;
  4374. return false;
  4375. }
  4376. inline const char *Result::data() const { return buffer_.data(); }
  4377. inline size_t Result::size() const { return current_size_; }
  4378. inline std::string Result::read_all() {
  4379. std::string result;
  4380. while (next()) {
  4381. result.append(data(), size());
  4382. }
  4383. return result;
  4384. }
  4385. } // namespace stream
  4386. namespace detail {
  4387. inline SSEParser::SSEParser(EventHandler on_event, IdHandler on_id,
  4388. RetryHandler on_retry, size_t max_event_length)
  4389. : on_event_(std::move(on_event)), on_id_(std::move(on_id)),
  4390. on_retry_(std::move(on_retry)), max_event_length_(max_event_length) {}
  4391. inline bool SSEParser::parse(const char *buf, size_t n) {
  4392. // What is left in the buffer has no line ending
  4393. auto search_pos = buffer_.size();
  4394. buffer_.append(buf, n);
  4395. // A line ends with \r\n, \n or \r per the SSE spec
  4396. size_t line_start = 0;
  4397. size_t eol_pos;
  4398. while ((eol_pos = buffer_.find_first_of("\r\n", search_pos)) !=
  4399. std::string::npos) {
  4400. auto line = buffer_.substr(line_start, eol_pos - line_start);
  4401. line_start = eol_pos + 1;
  4402. search_pos = line_start;
  4403. // The \n of a \r\n may arrive in a later chunk than its \r
  4404. auto is_lf_of_crlf = after_cr_ && line.empty() && buffer_[eol_pos] == '\n';
  4405. after_cr_ = buffer_[eol_pos] == '\r';
  4406. if (is_lf_of_crlf) { continue; }
  4407. // A UTF-8 BOM at the start of the stream is ignored per the SSE spec
  4408. if (first_line_) {
  4409. first_line_ = false;
  4410. if (line.compare(0, 3, "\xEF\xBB\xBF") == 0) { line.erase(0, 3); }
  4411. }
  4412. parse_line(line);
  4413. }
  4414. // Keep unprocessed data in buffer
  4415. buffer_.erase(0, line_start);
  4416. return max_event_length_ == 0 ||
  4417. buffer_.size() + msg_.data.size() <= max_event_length_;
  4418. }
  4419. inline void SSEParser::parse_line(const std::string &line) {
  4420. // Blank line signals end of event
  4421. if (line.empty()) {
  4422. // The id counts for Last-Event-ID even for an event that has no data. An
  4423. // empty id clears it.
  4424. if (has_id_ && on_id_) { on_id_(msg_.id); }
  4425. // An event without a data field is not dispatched
  4426. if (has_data_ && on_event_) { on_event_(msg_); }
  4427. msg_.clear();
  4428. has_data_ = false;
  4429. has_id_ = false;
  4430. return;
  4431. }
  4432. // Lines starting with ':' are comments (ignored)
  4433. if (line[0] == ':') { return; }
  4434. // Find the colon separator
  4435. auto colon_pos = line.find(':');
  4436. auto field = line.substr(0, colon_pos);
  4437. std::string value;
  4438. // Value starts after colon, skip optional single space
  4439. if (colon_pos != std::string::npos && colon_pos + 1 < line.size()) {
  4440. auto value_start = colon_pos + 1;
  4441. if (line[value_start] == ' ') { value_start++; }
  4442. value = line.substr(value_start);
  4443. }
  4444. // Handle known fields
  4445. if (field == "event") {
  4446. // An empty event type is dispatched as "message" per the SSE spec
  4447. msg_.event = value.empty() ? std::string("message") : std::move(value);
  4448. } else if (field == "data") {
  4449. // Multiple data lines are concatenated with newlines
  4450. if (has_data_) { msg_.data += "\n"; }
  4451. msg_.data += value;
  4452. has_data_ = true;
  4453. } else if (field == "id") {
  4454. // An id that cannot be sent back as Last-Event-ID is ignored. Empty id is
  4455. // valid (clears the last event ID)
  4456. if (fields::is_field_value(value)) {
  4457. msg_.id = value;
  4458. has_id_ = true;
  4459. }
  4460. } else if (field == "retry") {
  4461. // Parse retry interval in milliseconds
  4462. // Per the SSE spec, a value that is not all ASCII digits is ignored.
  4463. if (is_numeric(value)) {
  4464. int v = 0;
  4465. auto res = from_chars(value.data(), value.data() + value.size(), v);
  4466. if (res.ec == std::errc{} && on_retry_) { on_retry_(v); }
  4467. }
  4468. }
  4469. // Unknown fields are ignored per SSE spec
  4470. }
  4471. } // namespace detail
  4472. namespace sse {
  4473. // SSEMessage implementations
  4474. inline SSEMessage::SSEMessage() : event("message") {}
  4475. inline void SSEMessage::clear() {
  4476. event = "message";
  4477. data.clear();
  4478. id.clear();
  4479. }
  4480. // SSEClient implementations
  4481. inline SSEClient::SSEClient(Client &client, const std::string &path)
  4482. : client_(client), path_(path) {}
  4483. inline SSEClient::SSEClient(Client &client, const std::string &path,
  4484. const Headers &headers)
  4485. : client_(client), path_(path), headers_(headers) {}
  4486. inline SSEClient::~SSEClient() { stop(); }
  4487. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  4488. on_message_ = std::move(handler);
  4489. return *this;
  4490. }
  4491. inline SSEClient &SSEClient::on_event(const std::string &type,
  4492. MessageHandler handler) {
  4493. event_handlers_[type] = std::move(handler);
  4494. return *this;
  4495. }
  4496. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  4497. on_open_ = std::move(handler);
  4498. return *this;
  4499. }
  4500. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  4501. on_error_ = std::move(handler);
  4502. return *this;
  4503. }
  4504. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  4505. reconnect_interval_ms_ = ms;
  4506. return *this;
  4507. }
  4508. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  4509. max_reconnect_attempts_ = n;
  4510. return *this;
  4511. }
  4512. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  4513. std::lock_guard<std::mutex> lock(headers_mutex_);
  4514. headers_ = headers;
  4515. return *this;
  4516. }
  4517. inline bool SSEClient::is_connected() const { return connected_.load(); }
  4518. inline std::string SSEClient::last_event_id() const {
  4519. std::lock_guard<std::mutex> lock(last_event_id_mutex_);
  4520. return last_event_id_;
  4521. }
  4522. inline void SSEClient::start() {
  4523. running_.store(true);
  4524. run_event_loop();
  4525. }
  4526. inline void SSEClient::start_async() {
  4527. running_.store(true);
  4528. async_thread_ = std::thread([this]() { run_event_loop(); });
  4529. }
  4530. inline void SSEClient::stop() {
  4531. running_.store(false);
  4532. client_.stop(); // Cancel any pending operations
  4533. if (async_thread_.joinable()) { async_thread_.join(); }
  4534. }
  4535. inline void SSEClient::run_event_loop() {
  4536. auto reconnect_count = 0;
  4537. while (running_.load()) {
  4538. // Build headers, including Last-Event-ID if we have one
  4539. Headers request_headers;
  4540. {
  4541. std::lock_guard<std::mutex> lock(headers_mutex_);
  4542. request_headers = headers_;
  4543. }
  4544. if (!last_event_id_.empty()) {
  4545. request_headers.emplace("Last-Event-ID", last_event_id_);
  4546. }
  4547. // Open streaming connection. An event stream has no end, so each event is
  4548. // bounded instead of the whole body.
  4549. auto handle = client_.open_stream("GET", path_, {}, request_headers);
  4550. handle.body_reader_.payload_max_length = 0;
  4551. // stop() ends a read that is waiting for the next event
  4552. if (handle.stream_) {
  4553. handle.stream_->set_read_interrupt([this] { return !running_.load(); });
  4554. }
  4555. stream::Result result{std::move(handle)};
  4556. // Connection error handling
  4557. if (!result) {
  4558. connected_.store(false);
  4559. if (on_error_) { on_error_(result.error()); }
  4560. if (!should_reconnect(reconnect_count)) { break; }
  4561. wait_for_reconnect();
  4562. reconnect_count++;
  4563. continue;
  4564. }
  4565. if (result.status() != StatusCode::OK_200) {
  4566. connected_.store(false);
  4567. if (on_error_) { on_error_(Error::Connection); }
  4568. // For certain errors, don't reconnect.
  4569. // Note: 401 is intentionally absent so that handlers can refresh
  4570. // credentials via set_headers() and let the client reconnect.
  4571. if (result.status() == StatusCode::NoContent_204 ||
  4572. result.status() == StatusCode::NotFound_404 ||
  4573. result.status() == StatusCode::Forbidden_403) {
  4574. break;
  4575. }
  4576. if (!should_reconnect(reconnect_count)) { break; }
  4577. wait_for_reconnect();
  4578. reconnect_count++;
  4579. continue;
  4580. }
  4581. // Connection successful
  4582. connected_.store(true);
  4583. reconnect_count = 0;
  4584. if (on_open_) { on_open_(); }
  4585. // Event receiving loop
  4586. detail::SSEParser parser(
  4587. [this](const SSEMessage &msg) { dispatch_event(msg); },
  4588. [this](const std::string &id) {
  4589. std::lock_guard<std::mutex> lock(last_event_id_mutex_);
  4590. last_event_id_ = id;
  4591. },
  4592. [this](int retry_ms) { reconnect_interval_ms_ = retry_ms; });
  4593. auto event_too_long = false;
  4594. while (running_.load() && result.next()) {
  4595. if (!parser.parse(result.data(), result.size())) {
  4596. if (on_error_) { on_error_(Error::ExceedMaxPayloadSize); }
  4597. event_too_long = true;
  4598. break;
  4599. }
  4600. }
  4601. // Connection ended
  4602. connected_.store(false);
  4603. // Reconnecting would only get the same event again
  4604. if (!running_.load() || event_too_long) { break; }
  4605. // Check for read errors
  4606. if (result.has_read_error()) {
  4607. if (on_error_) { on_error_(result.read_error()); }
  4608. }
  4609. if (!should_reconnect(reconnect_count)) { break; }
  4610. wait_for_reconnect();
  4611. reconnect_count++;
  4612. }
  4613. connected_.store(false);
  4614. }
  4615. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  4616. // Check for specific event type handler first
  4617. auto it = event_handlers_.find(msg.event);
  4618. if (it != event_handlers_.end()) {
  4619. it->second(msg);
  4620. return;
  4621. }
  4622. // Fall back to generic message handler
  4623. if (on_message_) { on_message_(msg); }
  4624. }
  4625. inline bool SSEClient::should_reconnect(int count) const {
  4626. if (!running_.load()) { return false; }
  4627. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  4628. return count < max_reconnect_attempts_;
  4629. }
  4630. inline void SSEClient::wait_for_reconnect() {
  4631. // Use small increments to check running_ flag frequently.
  4632. // Always wait at least one increment, so that a zero interval (e.g.
  4633. // "retry: 0" from the server) cannot cause a busy reconnect loop.
  4634. const auto step_ms = 100;
  4635. auto interval_ms = (std::max)(reconnect_interval_ms_, step_ms);
  4636. auto waited = 0;
  4637. while (running_.load() && waited < interval_ms) {
  4638. std::this_thread::sleep_for(std::chrono::milliseconds(step_ms));
  4639. waited += step_ms;
  4640. }
  4641. }
  4642. } // namespace sse
  4643. #ifdef CPPHTTPLIB_SSL_ENABLED
  4644. /*
  4645. * TLS abstraction layer - internal function declarations
  4646. * These are implementation details and not part of the public API.
  4647. */
  4648. namespace tls {
  4649. // Client context
  4650. ctx_t create_client_context();
  4651. void free_context(ctx_t ctx);
  4652. bool set_min_version(ctx_t ctx, Version version);
  4653. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  4654. bool load_ca_file(ctx_t ctx, const char *file_path);
  4655. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  4656. bool load_system_certs(ctx_t ctx);
  4657. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4658. const char *password);
  4659. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  4660. const char *key_path, const char *password);
  4661. // Server context
  4662. ctx_t create_server_context();
  4663. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4664. const char *password);
  4665. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  4666. const char *key_path, const char *password);
  4667. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  4668. void set_verify_client(ctx_t ctx, bool require);
  4669. // Session management
  4670. session_t create_session(ctx_t ctx, socket_t sock);
  4671. void free_session(session_t session);
  4672. bool set_sni(session_t session, const char *hostname, bool verify_hostname);
  4673. // Handshake (non-blocking capable)
  4674. TlsError connect(session_t session);
  4675. TlsError accept(session_t session);
  4676. // Handshake with timeout (blocking until timeout, or until interrupted)
  4677. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4678. time_t timeout_usec, TlsError *err,
  4679. const std::function<bool()> &interrupted = nullptr);
  4680. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4681. time_t timeout_usec, TlsError *err,
  4682. const std::function<bool()> &interrupted = nullptr);
  4683. // I/O (non-blocking capable)
  4684. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  4685. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  4686. int pending(const_session_t session);
  4687. void shutdown(session_t session, bool graceful);
  4688. // Connection state
  4689. bool is_peer_closed(session_t session, socket_t sock);
  4690. // Certificate verification
  4691. cert_t get_peer_cert(const_session_t session);
  4692. // The certificates the peer sent, leaf first. Free each with free_cert(), and
  4693. // do not use them after free_session(), as with get_peer_cert().
  4694. size_t get_peer_certs(const_session_t session, std::vector<cert_t> &certs);
  4695. void free_cert(cert_t cert);
  4696. // Matches the host against the subjectAltName entries only, never the Common
  4697. // Name (RFC 9525).
  4698. bool verify_hostname(cert_t cert, const char *hostname);
  4699. uint64_t hostname_mismatch_code();
  4700. long get_verify_result(const_session_t session);
  4701. // Certificate introspection
  4702. std::string get_cert_subject_cn(cert_t cert);
  4703. std::string get_cert_issuer_name(cert_t cert);
  4704. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  4705. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  4706. std::string get_cert_serial(cert_t cert);
  4707. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  4708. const char *get_sni(const_session_t session);
  4709. // CA store management
  4710. ca_store_t create_ca_store(const char *pem, size_t len);
  4711. void free_ca_store(ca_store_t store);
  4712. bool set_ca_store(ctx_t ctx, ca_store_t store);
  4713. // Free each with free_cert(), and do not use them once the context's CA
  4714. // certificates change.
  4715. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  4716. std::vector<std::string> get_ca_names(ctx_t ctx);
  4717. // Dynamic certificate update (for servers)
  4718. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  4719. const char *password);
  4720. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  4721. // Certificate verification callback
  4722. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  4723. long get_verify_error(const_session_t session);
  4724. std::string verify_error_string(long error_code);
  4725. // TlsError information
  4726. uint64_t peek_error();
  4727. uint64_t get_error();
  4728. std::string error_string(uint64_t code);
  4729. } // namespace tls
  4730. #endif // CPPHTTPLIB_SSL_ENABLED
  4731. /*
  4732. * Group 1: detail namespace - Non-SSL utilities
  4733. */
  4734. namespace detail {
  4735. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  4736. const void *optval, socklen_t optlen) {
  4737. return setsockopt(sock, level, optname,
  4738. #ifdef _WIN32
  4739. reinterpret_cast<const char *>(optval),
  4740. #else
  4741. optval,
  4742. #endif
  4743. optlen) == 0;
  4744. }
  4745. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  4746. time_t sec, time_t usec) {
  4747. #ifdef _WIN32
  4748. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  4749. #else
  4750. timeval timeout;
  4751. timeout.tv_sec = static_cast<long>(sec);
  4752. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  4753. #endif
  4754. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  4755. }
  4756. inline bool is_hex(char c, int &v) {
  4757. if (is_ascii_digit(c)) {
  4758. v = c - '0';
  4759. return true;
  4760. } else if ('A' <= c && c <= 'F') {
  4761. v = c - 'A' + 10;
  4762. return true;
  4763. } else if ('a' <= c && c <= 'f') {
  4764. v = c - 'a' + 10;
  4765. return true;
  4766. }
  4767. return false;
  4768. }
  4769. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  4770. int &val) {
  4771. if (i >= s.size()) { return false; }
  4772. val = 0;
  4773. for (; cnt; i++, cnt--) {
  4774. if (!s[i]) { return false; }
  4775. auto v = 0;
  4776. if (is_hex(s[i], v)) {
  4777. val = val * 16 + v;
  4778. } else {
  4779. return false;
  4780. }
  4781. }
  4782. return true;
  4783. }
  4784. inline std::string from_i_to_hex(size_t n) {
  4785. static const auto charset = "0123456789abcdef";
  4786. std::string ret;
  4787. do {
  4788. ret = charset[n & 15] + ret;
  4789. n >>= 4;
  4790. } while (n > 0);
  4791. return ret;
  4792. }
  4793. // A round trip rather than `n <= SIZE_MAX`, which is always true on 64-bit
  4794. // builds and trips -Wtautological-type-limit-compare.
  4795. inline bool fits_in_size_t(uint64_t n) {
  4796. return static_cast<uint64_t>(static_cast<size_t>(n)) == n;
  4797. }
  4798. inline std::string compute_etag(const FileStat &fs,
  4799. const std::string &suffix = std::string()) {
  4800. if (!fs.is_file()) { return std::string(); }
  4801. // If mtime cannot be determined (negative value indicates an error
  4802. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  4803. // value like 0 could collide with a real file that legitimately has
  4804. // mtime == 0 (epoch) and lead to misleading validators.
  4805. auto mtime_raw = fs.mtime();
  4806. if (mtime_raw < 0) { return std::string(); }
  4807. auto mtime = static_cast<size_t>(mtime_raw);
  4808. auto size = fs.size();
  4809. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  4810. from_i_to_hex(size) + suffix + "\"";
  4811. }
  4812. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  4813. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  4814. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  4815. inline std::string file_mtime_to_http_date(time_t mtime) {
  4816. if (mtime < 0) { return std::string(); }
  4817. struct tm tm_buf;
  4818. #ifdef _WIN32
  4819. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  4820. #else
  4821. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  4822. #endif
  4823. char buf[64];
  4824. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  4825. return std::string();
  4826. }
  4827. return std::string(buf);
  4828. }
  4829. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  4830. inline time_t parse_http_date(const std::string &date_str) {
  4831. struct tm tm_buf;
  4832. // Create a classic locale object once for all parsing attempts
  4833. const std::locale classic_locale = std::locale::classic();
  4834. // Try to parse using std::get_time (C++11, cross-platform)
  4835. auto try_parse = [&](const char *fmt) -> bool {
  4836. std::istringstream ss(date_str);
  4837. ss.imbue(classic_locale);
  4838. memset(&tm_buf, 0, sizeof(tm_buf));
  4839. ss >> std::get_time(&tm_buf, fmt);
  4840. return !ss.fail();
  4841. };
  4842. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  4843. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  4844. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  4845. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  4846. // asctime format: "Sun Nov 6 08:49:37 1994"
  4847. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  4848. return static_cast<time_t>(-1);
  4849. }
  4850. }
  4851. }
  4852. #ifdef _WIN32
  4853. return _mkgmtime(&tm_buf);
  4854. #elif defined _AIX
  4855. return mktime(&tm_buf);
  4856. #else
  4857. return timegm(&tm_buf);
  4858. #endif
  4859. }
  4860. inline bool is_weak_etag(const std::string &s) {
  4861. // Check if the string is a weak ETag (starts with 'W/"')
  4862. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  4863. }
  4864. inline bool is_strong_etag(const std::string &s) {
  4865. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  4866. // chars)
  4867. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  4868. }
  4869. inline size_t to_utf8(int code, char *buff) {
  4870. if (code < 0x0080) {
  4871. buff[0] = static_cast<char>(code & 0x7F);
  4872. return 1;
  4873. } else if (code < 0x0800) {
  4874. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  4875. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  4876. return 2;
  4877. } else if (code < 0xD800) {
  4878. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4879. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4880. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4881. return 3;
  4882. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  4883. return 0;
  4884. } else if (code < 0x10000) {
  4885. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4886. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4887. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4888. return 3;
  4889. } else if (code < 0x110000) {
  4890. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  4891. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  4892. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4893. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  4894. return 4;
  4895. }
  4896. // NOTREACHED
  4897. return 0;
  4898. }
  4899. } // namespace detail
  4900. namespace ws {
  4901. namespace impl {
  4902. inline bool is_valid_utf8(const std::string &s) {
  4903. size_t i = 0;
  4904. auto n = s.size();
  4905. while (i < n) {
  4906. auto c = static_cast<unsigned char>(s[i]);
  4907. size_t len;
  4908. uint32_t cp;
  4909. if (c < 0x80) {
  4910. i++;
  4911. continue;
  4912. } else if ((c & 0xE0) == 0xC0) {
  4913. len = 2;
  4914. cp = c & 0x1F;
  4915. } else if ((c & 0xF0) == 0xE0) {
  4916. len = 3;
  4917. cp = c & 0x0F;
  4918. } else if ((c & 0xF8) == 0xF0) {
  4919. len = 4;
  4920. cp = c & 0x07;
  4921. } else {
  4922. return false;
  4923. }
  4924. if (i + len > n) { return false; }
  4925. for (size_t j = 1; j < len; j++) {
  4926. auto b = static_cast<unsigned char>(s[i + j]);
  4927. if ((b & 0xC0) != 0x80) { return false; }
  4928. cp = (cp << 6) | (b & 0x3F);
  4929. }
  4930. // Overlong encoding check
  4931. if (len == 2 && cp < 0x80) { return false; }
  4932. if (len == 3 && cp < 0x800) { return false; }
  4933. if (len == 4 && cp < 0x10000) { return false; }
  4934. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  4935. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  4936. if (cp > 0x10FFFF) { return false; }
  4937. i += len;
  4938. }
  4939. return true;
  4940. }
  4941. } // namespace impl
  4942. } // namespace ws
  4943. namespace detail {
  4944. // NOTE: This code came up with the following stackoverflow post:
  4945. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  4946. inline std::string base64_encode(const std::string &in) {
  4947. static const auto lookup =
  4948. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4949. std::string out;
  4950. out.reserve(in.size());
  4951. // Unsigned: the accumulator is never masked, so with a signed int the
  4952. // `val << 8` below overflows once enough bytes are folded in (undefined
  4953. // behaviour before C++20). Only the low bits are ever emitted, so the
  4954. // wrap-around of an unsigned accumulator does not affect the output.
  4955. uint32_t val = 0;
  4956. auto valb = -6;
  4957. for (auto c : in) {
  4958. val = (val << 8) + static_cast<uint8_t>(c);
  4959. valb += 8;
  4960. while (valb >= 0) {
  4961. out.push_back(lookup[(val >> valb) & 0x3F]);
  4962. valb -= 6;
  4963. }
  4964. }
  4965. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  4966. while (out.size() % 4) {
  4967. out.push_back('=');
  4968. }
  4969. return out;
  4970. }
  4971. inline std::string sha1(const std::string &input) {
  4972. // RFC 3174 SHA-1 implementation
  4973. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  4974. return (x << n) | (x >> (32 - n));
  4975. };
  4976. uint32_t h0 = 0x67452301;
  4977. uint32_t h1 = 0xEFCDAB89;
  4978. uint32_t h2 = 0x98BADCFE;
  4979. uint32_t h3 = 0x10325476;
  4980. uint32_t h4 = 0xC3D2E1F0;
  4981. // Pre-processing: adding padding bits
  4982. std::string msg = input;
  4983. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  4984. msg.push_back(static_cast<char>(0x80u));
  4985. while (msg.size() % 64 != 56) {
  4986. msg.push_back(0);
  4987. }
  4988. // Append original length in bits as 64-bit big-endian
  4989. for (int i = 56; i >= 0; i -= 8) {
  4990. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  4991. }
  4992. // Process each 512-bit chunk
  4993. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  4994. uint32_t w[80];
  4995. for (size_t i = 0; i < 16; i++) {
  4996. w[i] =
  4997. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  4998. << 24) |
  4999. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  5000. << 16) |
  5001. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  5002. << 8) |
  5003. (static_cast<uint32_t>(
  5004. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  5005. }
  5006. for (int i = 16; i < 80; i++) {
  5007. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  5008. }
  5009. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  5010. for (int i = 0; i < 80; i++) {
  5011. uint32_t f, k;
  5012. if (i < 20) {
  5013. f = (b & c) | ((~b) & d);
  5014. k = 0x5A827999;
  5015. } else if (i < 40) {
  5016. f = b ^ c ^ d;
  5017. k = 0x6ED9EBA1;
  5018. } else if (i < 60) {
  5019. f = (b & c) | (b & d) | (c & d);
  5020. k = 0x8F1BBCDC;
  5021. } else {
  5022. f = b ^ c ^ d;
  5023. k = 0xCA62C1D6;
  5024. }
  5025. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  5026. e = d;
  5027. d = c;
  5028. c = left_rotate(b, 30);
  5029. b = a;
  5030. a = temp;
  5031. }
  5032. h0 += a;
  5033. h1 += b;
  5034. h2 += c;
  5035. h3 += d;
  5036. h4 += e;
  5037. }
  5038. // Produce the final hash as a 20-byte binary string
  5039. std::string hash(20, '\0');
  5040. for (size_t i = 0; i < 4; i++) {
  5041. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  5042. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  5043. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  5044. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  5045. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  5046. }
  5047. return hash;
  5048. }
  5049. inline std::string websocket_accept_key(const std::string &client_key) {
  5050. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  5051. return base64_encode(sha1(client_key + magic));
  5052. }
  5053. inline bool is_websocket_upgrade(const Request &req) {
  5054. if (req.method != "GET") { return false; }
  5055. // Check Upgrade: websocket. RFC 9110 7.8 defines Upgrade as a comma-separated
  5056. // list of protocols and asks recipients to match each name
  5057. // case-insensitively, so look for the token rather than compare the whole
  5058. // field value.
  5059. if (!has_header_token(req.headers, "Upgrade", "websocket")) { return false; }
  5060. // Check Connection: Upgrade
  5061. if (!has_header_token(req.headers, "Connection", "upgrade")) { return false; }
  5062. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  5063. // RFC 6455 Section 4.2.1
  5064. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  5065. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  5066. return false;
  5067. }
  5068. static const std::string b64chars =
  5069. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5070. for (size_t i = 0; i < 22; i++) {
  5071. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  5072. }
  5073. // Check Sec-WebSocket-Version: 13
  5074. auto version = req.get_header_value("Sec-WebSocket-Version");
  5075. if (version != "13") { return false; }
  5076. return true;
  5077. }
  5078. // Unpredictable bytes for masking keys (RFC 6455 Section 5.3) and nonces
  5079. inline void fill_random_bytes(unsigned char *out, size_t n) {
  5080. thread_local std::random_device rd;
  5081. size_t filled = 0;
  5082. while (filled < n) {
  5083. auto v = rd();
  5084. for (size_t b = 0; b < sizeof(v) && filled < n; ++b, ++filled) {
  5085. out[filled] = static_cast<unsigned char>((v >> (b * 8)) & 0xFFu);
  5086. }
  5087. }
  5088. }
  5089. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  5090. const char *data, size_t len, bool fin,
  5091. bool mask) {
  5092. // The header (FIN + opcode, MASK + length, the extended length, the mask
  5093. // key: 14 bytes at most) goes out in one write with the payload's first
  5094. // chunk, so that under TCP_NODELAY a small frame is one segment, not three.
  5095. uint8_t header[14];
  5096. size_t header_len = 0;
  5097. header[header_len++] = static_cast<uint8_t>(
  5098. (fin ? 0x80 : 0x00) | (static_cast<uint8_t>(opcode) & 0x0F));
  5099. uint8_t mask_bit = mask ? 0x80 : 0x00;
  5100. if (len < 126) {
  5101. header[header_len++] = static_cast<uint8_t>(len) | mask_bit;
  5102. } else if (len <= 0xFFFF) {
  5103. header[header_len++] = 126 | mask_bit;
  5104. header[header_len++] = static_cast<uint8_t>((len >> 8) & 0xFF);
  5105. header[header_len++] = static_cast<uint8_t>(len & 0xFF);
  5106. } else {
  5107. header[header_len++] = 127 | mask_bit;
  5108. for (int i = 7; i >= 0; i--) {
  5109. header[header_len++] =
  5110. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  5111. }
  5112. }
  5113. uint8_t mask_key[4] = {0};
  5114. if (mask) {
  5115. fill_random_bytes(mask_key, sizeof(mask_key));
  5116. std::copy(mask_key, mask_key + 4, header + header_len);
  5117. header_len += 4;
  5118. }
  5119. // `n` bytes of the payload from `offset`, masked if they are to be, at `out`
  5120. auto put = [&](char *out, size_t offset, size_t n) {
  5121. for (size_t i = 0; i < n; i++) {
  5122. out[i] = mask ? data[offset + i] ^
  5123. static_cast<char>(mask_key[(offset + i) % 4])
  5124. : data[offset + i];
  5125. }
  5126. };
  5127. const size_t chunk_size = 4096;
  5128. size_t first = (std::min)(len, chunk_size);
  5129. std::vector<char> buf(header_len + first);
  5130. std::copy(header, header + header_len, buf.begin());
  5131. put(buf.data() + header_len, 0, first);
  5132. if (!write_data(strm, buf.data(), buf.size())) { return false; }
  5133. // The rest, masked a chunk at a time, or else as it is
  5134. if (!mask) {
  5135. return first == len || write_data(strm, data + first, len - first);
  5136. }
  5137. for (size_t offset = first; offset < len; offset += chunk_size) {
  5138. size_t n = (std::min)(chunk_size, len - offset);
  5139. put(buf.data(), offset, n);
  5140. if (!write_data(strm, buf.data(), n)) { return false; }
  5141. }
  5142. return true;
  5143. }
  5144. } // namespace detail
  5145. namespace ws {
  5146. namespace impl {
  5147. inline void FrameReader::reset() {
  5148. have_ = 0;
  5149. need_ = 2;
  5150. sized_ = false;
  5151. len_ = 0;
  5152. payload_.clear();
  5153. }
  5154. // Stream::read may return less than asked for -- it hands back whatever its
  5155. // buffer already holds -- so each part of the frame is read in a loop, a byte
  5156. // at a time if that is how it comes. (When read() fails it always records why,
  5157. // so the error belongs to this call and not to an earlier one.)
  5158. inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
  5159. std::string &payload, bool &fin,
  5160. bool expect_masked, size_t max_len) {
  5161. // A timeout keeps what was read; anything else ends the frame
  5162. auto stopped = [&]() {
  5163. if (strm.get_error() == Error::Timeout) { return FrameRead::Timeout; }
  5164. reset();
  5165. return FrameRead::Fail;
  5166. };
  5167. auto reject = [&](FrameRead r) {
  5168. reset();
  5169. return r;
  5170. };
  5171. while (have_ < need_) {
  5172. auto n = strm.read(reinterpret_cast<char *>(head_) + have_, need_ - have_);
  5173. if (n <= 0) { return stopped(); }
  5174. have_ += static_cast<size_t>(n);
  5175. if (have_ < 2 || need_ > 2) { continue; }
  5176. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  5177. if (head_[0] & 0x70) { return reject(FrameRead::ProtocolError); }
  5178. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  5179. // MUST have a payload length of 125 bytes or less
  5180. auto len7 = head_[1] & 0x7F;
  5181. if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
  5182. return reject(FrameRead::ProtocolError);
  5183. }
  5184. auto masked = (head_[1] & 0x80) != 0;
  5185. if (masked != expect_masked) { return reject(FrameRead::ProtocolError); }
  5186. // The extended length and the mask key follow
  5187. need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
  5188. }
  5189. if (!sized_) {
  5190. uint64_t len = head_[1] & 0x7F;
  5191. if (len == 126) {
  5192. len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
  5193. } else if (len == 127) {
  5194. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  5195. if (head_[2] & 0x80) { return reject(FrameRead::ProtocolError); }
  5196. len = 0;
  5197. for (size_t i = 2; i < 10; i++) {
  5198. len = (len << 8) | head_[i];
  5199. }
  5200. }
  5201. // A max_len of 0 means no limit, as payload_max_length does, and a length
  5202. // size_t cannot hold (32-bit builds) is refused either way.
  5203. if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) {
  5204. return reject(FrameRead::TooBig);
  5205. }
  5206. len_ = static_cast<size_t>(len);
  5207. sized_ = true;
  5208. }
  5209. // Grow the payload only as it arrives, since a header alone can announce
  5210. // max_len bytes that never come.
  5211. while (payload_.size() < len_) {
  5212. auto offset = payload_.size();
  5213. auto n = (std::min)(len_ - offset, CPPHTTPLIB_RECV_BUFSIZ);
  5214. payload_.resize(offset + n);
  5215. auto got = strm.read(&payload_[offset], n);
  5216. if (got <= 0) {
  5217. payload_.resize(offset);
  5218. return stopped();
  5219. }
  5220. payload_.resize(offset + static_cast<size_t>(got));
  5221. }
  5222. if (head_[1] & 0x80) {
  5223. const auto *mask_key = head_ + need_ - 4;
  5224. for (size_t i = 0; i < payload_.size(); i++) {
  5225. payload_[i] ^= static_cast<char>(mask_key[i % 4]);
  5226. }
  5227. }
  5228. fin = (head_[0] & 0x80) != 0;
  5229. opcode = static_cast<Opcode>(head_[0] & 0x0F);
  5230. payload = std::move(payload_);
  5231. reset();
  5232. return FrameRead::Ok;
  5233. }
  5234. inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  5235. std::string &payload, bool &fin,
  5236. bool expect_masked, size_t max_len) {
  5237. FrameReader reader;
  5238. auto r = reader.read(strm, opcode, payload, fin, expect_masked, max_len);
  5239. return r == FrameRead::Timeout && reader.begun() ? FrameRead::Fail : r;
  5240. }
  5241. // RFC 6455 §5.5.1, §7.4: a Close payload is empty, or a status code that may
  5242. // be sent followed by a UTF-8 reason.
  5243. // The status code a Close payload of at least 2 bytes starts with
  5244. inline uint16_t close_code(const std::string &payload) {
  5245. return static_cast<uint16_t>((static_cast<uint8_t>(payload[0]) << 8) |
  5246. static_cast<uint8_t>(payload[1]));
  5247. }
  5248. inline bool is_valid_close_payload(const std::string &payload) {
  5249. if (payload.empty()) { return true; }
  5250. if (payload.size() < 2) { return false; }
  5251. auto code = close_code(payload);
  5252. auto may_be_sent = (1000 <= code && code <= 1003) ||
  5253. (1007 <= code && code <= 1014) ||
  5254. (3000 <= code && code <= 4999);
  5255. return may_be_sent && is_valid_utf8(payload.substr(2));
  5256. }
  5257. // The payload of a Close with this status and reason. The reason is cut to fit
  5258. // a control frame (RFC 6455 Section 5.5), back to a whole UTF-8 character, and
  5259. // a code that may not be sent, such as NoStatus, goes without a payload.
  5260. inline std::string close_payload(CloseStatus status,
  5261. const std::string &reason = std::string()) {
  5262. auto code = static_cast<uint16_t>(status);
  5263. std::string payload{static_cast<char>(code >> 8),
  5264. static_cast<char>(code & 0xff)};
  5265. auto short_reason = reason.substr(0, 123);
  5266. while (!short_reason.empty() && !is_valid_utf8(short_reason)) {
  5267. short_reason.pop_back();
  5268. }
  5269. payload += short_reason;
  5270. if (!is_valid_close_payload(payload)) { payload.clear(); }
  5271. return payload;
  5272. }
  5273. } // namespace impl
  5274. } // namespace ws
  5275. namespace detail {
  5276. // A path a mount point serves: absolute, with no empty segment except a
  5277. // trailing '/', no segment ending in '.' or a space (which covers "." and
  5278. // ".." and names Windows trims into another file's name) and, on Windows, no
  5279. // ':' (which names an NTFS stream, so "a.txt::$DATA" is a.txt), so the file
  5280. // served is the one that req.path names to the handlers that ran before it.
  5281. inline bool is_valid_path(const std::string &path) {
  5282. if (path.empty() || path[0] != '/') { return false; }
  5283. auto beg = size_t{1};
  5284. for (auto i = beg; i <= path.size(); i++) {
  5285. if (i < path.size() && path[i] != '/') {
  5286. if (path[i] == '\0' || path[i] == '\\') { return false; }
  5287. #ifdef _WIN32
  5288. if (path[i] == ':') { return false; }
  5289. #endif
  5290. continue;
  5291. }
  5292. auto len = i - beg;
  5293. if ((len == 0 && i < path.size()) ||
  5294. (len > 0 && (path[i - 1] == '.' || path[i - 1] == ' '))) {
  5295. return false;
  5296. }
  5297. beg = i + 1;
  5298. }
  5299. return true;
  5300. }
  5301. inline bool canonicalize_path(const char *path, std::string &resolved) {
  5302. #if defined(_WIN32)
  5303. // Resolve junctions and symlinks, as realpath() does
  5304. auto wpath = u8string_to_wstring(path);
  5305. if (wpath.empty()) { return false; }
  5306. CREATEFILE2_EXTENDED_PARAMETERS params{};
  5307. params.dwSize = sizeof(params);
  5308. params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS; // Needed to open a directory
  5309. auto h = ::CreateFile2(wpath.c_str(), 0,
  5310. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  5311. OPEN_EXISTING, &params);
  5312. if (h == INVALID_HANDLE_VALUE) { return false; }
  5313. auto guard = scope_exit([&]() { ::CloseHandle(h); });
  5314. std::wstring wbuf(MAX_PATH, L'\0');
  5315. auto len = ::GetFinalPathNameByHandleW(
  5316. h, &wbuf[0], static_cast<DWORD>(wbuf.size()), FILE_NAME_NORMALIZED);
  5317. if (len >= wbuf.size()) {
  5318. wbuf.resize(len);
  5319. len = ::GetFinalPathNameByHandleW(
  5320. h, &wbuf[0], static_cast<DWORD>(wbuf.size()), FILE_NAME_NORMALIZED);
  5321. }
  5322. if (len == 0 || len >= wbuf.size()) { return false; }
  5323. auto n = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), static_cast<int>(len),
  5324. nullptr, 0, nullptr, nullptr);
  5325. if (n <= 0) { return false; }
  5326. resolved.assign(static_cast<size_t>(n), '\0');
  5327. ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), static_cast<int>(len),
  5328. &resolved[0], n, nullptr, nullptr);
  5329. #elif defined(PATH_MAX)
  5330. char buf[PATH_MAX];
  5331. if (realpath(path, buf) == nullptr) { return false; }
  5332. resolved = buf;
  5333. #else
  5334. auto buf = realpath(path, nullptr);
  5335. auto guard = scope_exit([&]() { std::free(buf); });
  5336. if (buf == nullptr) { return false; }
  5337. resolved = buf;
  5338. #endif
  5339. return true;
  5340. }
  5341. inline bool is_path_within_base(const std::string &resolved_path,
  5342. const std::string &resolved_base) {
  5343. #if defined(_WIN32)
  5344. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  5345. resolved_base.size()) == 0;
  5346. #else
  5347. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  5348. resolved_base.size()) == 0;
  5349. #endif
  5350. }
  5351. inline FileStat::FileStat(const std::string &path) {
  5352. #if defined(_WIN32)
  5353. auto wpath = u8string_to_wstring(path.c_str());
  5354. ret_ = _wstat(wpath.c_str(), &st_);
  5355. #else
  5356. ret_ = stat(path.c_str(), &st_);
  5357. #endif
  5358. }
  5359. inline bool FileStat::is_file() const {
  5360. return ret_ >= 0 && S_ISREG(st_.st_mode);
  5361. }
  5362. inline bool FileStat::is_dir() const {
  5363. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  5364. }
  5365. inline time_t FileStat::mtime() const {
  5366. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  5367. : static_cast<time_t>(-1);
  5368. }
  5369. inline size_t FileStat::size() const {
  5370. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  5371. }
  5372. inline std::string encode_path(const std::string &s) {
  5373. std::string result;
  5374. result.reserve(s.size());
  5375. for (size_t i = 0; s[i]; i++) {
  5376. switch (s[i]) {
  5377. case ' ': result += "%20"; break;
  5378. case '+': result += "%2B"; break;
  5379. case '\'': result += "%27"; break;
  5380. case ',': result += "%2C"; break;
  5381. // case ':': result += "%3A"; break; // ok? probably...
  5382. case ';': result += "%3B"; break;
  5383. default:
  5384. auto c = static_cast<uint8_t>(s[i]);
  5385. // Control characters (incl. CR/LF) and non-ASCII bytes are not allowed
  5386. // in a request-target as-is.
  5387. if (c < 0x20 || c == 0x7f || c >= 0x80) {
  5388. result += '%';
  5389. char hex[4];
  5390. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  5391. assert(len == 2);
  5392. result.append(hex, static_cast<size_t>(len));
  5393. } else {
  5394. result += s[i];
  5395. }
  5396. break;
  5397. }
  5398. }
  5399. return result;
  5400. }
  5401. inline std::string file_extension(const std::string &path) {
  5402. auto i = path.size();
  5403. while (i > 0 && is_ascii_alnum(path[i - 1])) {
  5404. i--;
  5405. }
  5406. if (i == path.size() || i == 0 || path[i - 1] != '.') {
  5407. return std::string();
  5408. }
  5409. return path.substr(i);
  5410. }
  5411. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  5412. template <typename T>
  5413. inline bool parse_header(const char *beg, const char *end, T fn);
  5414. template <typename T>
  5415. inline bool parse_header(const char *beg, const char *end, T fn) {
  5416. // Skip trailing spaces and tabs.
  5417. while (beg < end && is_space_or_tab(end[-1])) {
  5418. end--;
  5419. }
  5420. auto p = beg;
  5421. while (p < end && *p != ':') {
  5422. p++;
  5423. }
  5424. auto name = std::string(beg, p);
  5425. if (!detail::fields::is_field_name(name)) { return false; }
  5426. if (p == end) { return false; }
  5427. auto key_end = p;
  5428. if (*p++ != ':') { return false; }
  5429. while (p < end && is_space_or_tab(*p)) {
  5430. p++;
  5431. }
  5432. if (p <= end) {
  5433. auto key_len = key_end - beg;
  5434. if (!key_len) { return false; }
  5435. auto key = std::string(beg, key_end);
  5436. auto val = std::string(p, end);
  5437. if (!detail::fields::is_field_value(val)) { return false; }
  5438. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  5439. // percent-decoded by the recipient. Applications that need to interpret a
  5440. // value as a URI component should call httplib::decode_uri_component()
  5441. // (or decode_path_component()) explicitly.
  5442. fn(key, val);
  5443. return true;
  5444. }
  5445. return false;
  5446. }
  5447. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  5448. const Headers &src_headers) {
  5449. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  5450. // transfer coding is complete when a chunk with a chunk-size of zero is
  5451. // received, possibly followed by a trailer section, and finally terminated by
  5452. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  5453. //
  5454. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  5455. // doesn't care for the existence of the final CRLF. In other words, it seems
  5456. // to be ok whether the final CRLF exists or not in the chunked data.
  5457. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  5458. //
  5459. // According to the reference code in RFC 9112, cpp-httplib now allows
  5460. // chunked transfer coding data without the final CRLF.
  5461. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  5462. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  5463. "transfer-encoding",
  5464. "content-length",
  5465. "host",
  5466. "authorization",
  5467. "www-authenticate",
  5468. "proxy-authenticate",
  5469. "proxy-authorization",
  5470. "cookie",
  5471. "set-cookie",
  5472. "cache-control",
  5473. "expect",
  5474. "max-forwards",
  5475. "pragma",
  5476. "range",
  5477. "te",
  5478. "age",
  5479. "expires",
  5480. "date",
  5481. "location",
  5482. "retry-after",
  5483. "vary",
  5484. "warning",
  5485. "content-encoding",
  5486. "content-type",
  5487. "content-range",
  5488. "trailer"};
  5489. case_ignore::unordered_set<std::string> declared_trailers;
  5490. auto trailer_header = get_combined_header_value(src_headers, "Trailer");
  5491. if (!trailer_header.empty()) {
  5492. // split() trims each token and skips empty ones, so the name arrives ready
  5493. // to look up.
  5494. split(trailer_header.data(), trailer_header.data() + trailer_header.size(),
  5495. ',', [&](const char *b, const char *e) {
  5496. // A legitimate message declares only a handful of trailers. Cap the
  5497. // set so a peer cannot grow it without bound: an oversized set only
  5498. // arises from an attempt to force many colliding names into
  5499. // quadratic lookups (case_ignore::hash is unkeyed).
  5500. if (declared_trailers.size() >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  5501. return;
  5502. }
  5503. std::string key(b, e);
  5504. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  5505. declared_trailers.insert(key);
  5506. }
  5507. });
  5508. }
  5509. size_t trailer_header_count = 0;
  5510. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  5511. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5512. // Count every received trailer field, not only the declared ones stored in
  5513. // dest, so undeclared fields cannot keep this loop running past the limit.
  5514. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5515. constexpr auto line_terminator_len = 2;
  5516. auto line_beg = line_reader.ptr();
  5517. auto line_end =
  5518. line_reader.ptr() + line_reader.size() - line_terminator_len;
  5519. if (!parse_header(line_beg, line_end,
  5520. [&](const std::string &key, const std::string &val) {
  5521. if (declared_trailers.find(key) !=
  5522. declared_trailers.end()) {
  5523. dest.emplace(key, val);
  5524. }
  5525. })) {
  5526. return false;
  5527. }
  5528. trailer_header_count++;
  5529. if (!line_reader.getline()) { return false; }
  5530. }
  5531. return true;
  5532. }
  5533. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  5534. size_t right) {
  5535. while (b + left < e && is_space_or_tab(b[left])) {
  5536. left++;
  5537. }
  5538. while (right > 0 && is_space_or_tab(b[right - 1])) {
  5539. right--;
  5540. }
  5541. return std::make_pair(left, right);
  5542. }
  5543. inline std::string trim_copy(const std::string &s) {
  5544. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  5545. return s.substr(r.first, r.second - r.first);
  5546. }
  5547. inline std::string trim_double_quotes_copy(const std::string &s) {
  5548. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  5549. return s.substr(1, s.size() - 2);
  5550. }
  5551. return s;
  5552. }
  5553. // Takes the quotes off a parameter value. Only \" and \\ are quoted-pairs
  5554. // here, as browsers send any other backslash, such as one in a Windows path,
  5555. // as it is.
  5556. inline std::string unquote_param(const std::string &s) {
  5557. if (s.size() < 2 || s.front() != '"' || s.back() != '"') { return s; }
  5558. std::string out;
  5559. for (size_t i = 1; i + 1 < s.size(); i++) {
  5560. if (s[i] == '\\' && i + 2 < s.size() &&
  5561. (s[i + 1] == '"' || s[i + 1] == '\\')) {
  5562. i++;
  5563. }
  5564. out += s[i];
  5565. }
  5566. return out;
  5567. }
  5568. inline void
  5569. divide(const char *data, std::size_t size, char d,
  5570. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5571. fn) {
  5572. const auto it = std::find(data, data + size, d);
  5573. const auto found = static_cast<std::size_t>(it != data + size);
  5574. const auto lhs_data = data;
  5575. const auto lhs_size = static_cast<std::size_t>(it - data);
  5576. const auto rhs_data = it + found;
  5577. const auto rhs_size = size - lhs_size - found;
  5578. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  5579. }
  5580. inline void
  5581. divide(const std::string &str, char d,
  5582. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5583. fn) {
  5584. divide(str.data(), str.size(), d, std::move(fn));
  5585. }
  5586. inline void split(const char *b, const char *e, char d,
  5587. std::function<void(const char *, const char *)> fn) {
  5588. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  5589. }
  5590. inline void split(const char *b, const char *e, char d, size_t m,
  5591. std::function<void(const char *, const char *)> fn) {
  5592. size_t i = 0;
  5593. size_t beg = 0;
  5594. size_t count = 1;
  5595. while (e ? (b + i < e) : (b[i] != '\0')) {
  5596. if (b[i] == d && count < m) {
  5597. auto r = trim(b, e, beg, i);
  5598. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5599. beg = i + 1;
  5600. count++;
  5601. }
  5602. i++;
  5603. }
  5604. if (i) {
  5605. auto r = trim(b, e, beg, i);
  5606. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5607. }
  5608. }
  5609. // Same contract as split(), except that a delimiter inside a quoted-string is
  5610. // not a delimiter. RFC 9110 Section 5.6.6 lets a parameter value be a
  5611. // quoted-string, and ';' and '=' are legal characters inside one.
  5612. inline void split_unquoted(const char *b, const char *e, char d, size_t m,
  5613. std::function<void(const char *, const char *)> fn) {
  5614. size_t i = 0;
  5615. size_t beg = 0;
  5616. size_t count = 1;
  5617. auto in_quotes = false;
  5618. auto has = [&](size_t j) { return e ? (b + j < e) : (b[j] != '\0'); };
  5619. while (has(i)) {
  5620. if (in_quotes && b[i] == '\\' && has(i + 1)) {
  5621. // A quoted-pair, whose second character does not end the string.
  5622. i++;
  5623. } else if (b[i] == '"') {
  5624. in_quotes = !in_quotes;
  5625. } else if (b[i] == d && !in_quotes && count < m) {
  5626. auto r = trim(b, e, beg, i);
  5627. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5628. beg = i + 1;
  5629. count++;
  5630. }
  5631. i++;
  5632. }
  5633. if (i) {
  5634. auto r = trim(b, e, beg, i);
  5635. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5636. }
  5637. }
  5638. inline void split_unquoted(const char *b, const char *e, char d,
  5639. std::function<void(const char *, const char *)> fn) {
  5640. return split_unquoted(b, e, d, (std::numeric_limits<size_t>::max)(),
  5641. std::move(fn));
  5642. }
  5643. // Divide a header parameter at its first '='. RFC 9110 Section 5.6.6 makes the
  5644. // key a token, so the first '=' is the separator even when the value is a
  5645. // quoted-string carrying more of them.
  5646. inline void divide_param_pair(const char *b, const char *e, std::string &key,
  5647. std::string &val) {
  5648. divide(
  5649. b, static_cast<std::size_t>(e - b), '=',
  5650. [&](const char *kb, std::size_t klen, const char *vb, std::size_t vlen) {
  5651. const auto kr = trim(kb, kb + klen, 0, klen);
  5652. key.assign(kb + kr.first, kb + kr.second);
  5653. const auto vr = trim(vb, vb + vlen, 0, vlen);
  5654. val.assign(vb + vr.first, vb + vr.second);
  5655. });
  5656. }
  5657. inline bool split_find(const char *b, const char *e, char d, size_t m,
  5658. std::function<bool(const char *, const char *)> fn) {
  5659. size_t i = 0;
  5660. size_t beg = 0;
  5661. size_t count = 1;
  5662. while (e ? (b + i < e) : (b[i] != '\0')) {
  5663. if (b[i] == d && count < m) {
  5664. auto r = trim(b, e, beg, i);
  5665. if (r.first < r.second) {
  5666. auto found = fn(&b[r.first], &b[r.second]);
  5667. if (found) { return true; }
  5668. }
  5669. beg = i + 1;
  5670. count++;
  5671. }
  5672. i++;
  5673. }
  5674. if (i) {
  5675. auto r = trim(b, e, beg, i);
  5676. if (r.first < r.second) {
  5677. auto found = fn(&b[r.first], &b[r.second]);
  5678. if (found) { return true; }
  5679. }
  5680. }
  5681. return false;
  5682. }
  5683. inline bool split_find(const char *b, const char *e, char d,
  5684. std::function<bool(const char *, const char *)> fn) {
  5685. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  5686. std::move(fn));
  5687. }
  5688. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  5689. size_t fixed_buffer_size)
  5690. : strm_(strm), fixed_buffer_(fixed_buffer),
  5691. fixed_buffer_size_(fixed_buffer_size) {}
  5692. inline const char *stream_line_reader::ptr() const {
  5693. if (growable_buffer_.empty()) {
  5694. return fixed_buffer_;
  5695. } else {
  5696. return growable_buffer_.data();
  5697. }
  5698. }
  5699. inline size_t stream_line_reader::size() const {
  5700. if (growable_buffer_.empty()) {
  5701. return fixed_buffer_used_size_;
  5702. } else {
  5703. return growable_buffer_.size();
  5704. }
  5705. }
  5706. inline bool stream_line_reader::end_with_crlf() const {
  5707. auto end = ptr() + size();
  5708. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  5709. }
  5710. inline bool stream_line_reader::getline() {
  5711. fixed_buffer_used_size_ = 0;
  5712. growable_buffer_.clear();
  5713. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5714. char prev_byte = 0;
  5715. #endif
  5716. for (size_t i = 0;; i++) {
  5717. // Fast path: whatever the stream has already buffered can be scanned for
  5718. // the terminator in one pass. Asking for a byte at a time costs a virtual
  5719. // call, a bounds check and a one-byte copy per character of the request.
  5720. size_t buffered_size = 0;
  5721. if (auto buffered = strm_.buffered_data(buffered_size)) {
  5722. auto take = buffered_size;
  5723. auto terminated = false;
  5724. for (size_t at = 0; at < buffered_size;) {
  5725. auto nl = static_cast<const char *>(
  5726. memchr(buffered + at, '\n', buffered_size - at));
  5727. if (!nl) { break; }
  5728. auto pos = static_cast<size_t>(nl - buffered);
  5729. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5730. take = pos + 1;
  5731. terminated = true;
  5732. break;
  5733. #else
  5734. // A bare LF does not end the line; keep looking for CRLF. The CR may
  5735. // be the last byte of an earlier chunk, hence prev_byte.
  5736. if ((pos > 0 ? buffered[pos - 1] : prev_byte) == '\r') {
  5737. take = pos + 1;
  5738. terminated = true;
  5739. break;
  5740. }
  5741. at = pos + 1;
  5742. #endif
  5743. }
  5744. if (size() + take > CPPHTTPLIB_MAX_LINE_LENGTH) { return false; }
  5745. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5746. prev_byte = buffered[take - 1];
  5747. #endif
  5748. append(buffered, take);
  5749. strm_.consume_buffered(take);
  5750. i += take;
  5751. if (terminated) { return true; }
  5752. continue;
  5753. }
  5754. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  5755. // Treat exceptionally long lines as an error to
  5756. // prevent infinite loops/memory exhaustion
  5757. return false;
  5758. }
  5759. char byte;
  5760. auto n = strm_.read(&byte, 1);
  5761. if (n < 0) {
  5762. return false;
  5763. } else if (n == 0) {
  5764. if (i == 0) {
  5765. return false;
  5766. } else {
  5767. break;
  5768. }
  5769. }
  5770. append(byte);
  5771. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5772. if (byte == '\n') { break; }
  5773. #else
  5774. if (prev_byte == '\r' && byte == '\n') { break; }
  5775. prev_byte = byte;
  5776. #endif
  5777. }
  5778. return true;
  5779. }
  5780. inline void stream_line_reader::append(char c) { append(&c, 1); }
  5781. inline void stream_line_reader::append(const char *data, size_t size) {
  5782. // Once the line has outgrown the fixed buffer everything must keep going to
  5783. // the growable one, even if a later chunk would have fit. Without the
  5784. // emptiness check a short append after a long one would land in the fixed
  5785. // buffer, which ptr() and size() no longer look at, and be lost.
  5786. if (growable_buffer_.empty() &&
  5787. fixed_buffer_used_size_ + size < fixed_buffer_size_) {
  5788. memcpy(fixed_buffer_ + fixed_buffer_used_size_, data, size);
  5789. fixed_buffer_used_size_ += size;
  5790. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  5791. } else {
  5792. // Unlike the per-character overload, this can be the very first append of
  5793. // the line, so the fixed buffer may hold nothing and carry no terminator
  5794. // yet. assign() takes an explicit length and does not need one.
  5795. if (growable_buffer_.empty()) {
  5796. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  5797. }
  5798. growable_buffer_.append(data, size);
  5799. }
  5800. }
  5801. inline mmap::mmap(const char *path) { open(path); }
  5802. inline mmap::~mmap() { close(); }
  5803. inline bool mmap::open(const char *path) {
  5804. close();
  5805. #if defined(_WIN32)
  5806. auto wpath = u8string_to_wstring(path);
  5807. if (wpath.empty()) { return false; }
  5808. hFile_ =
  5809. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  5810. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  5811. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  5812. LARGE_INTEGER size{};
  5813. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  5814. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  5815. // See:
  5816. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  5817. if (!fits_in_size_t(static_cast<uint64_t>(size.QuadPart))) { return false; }
  5818. size_ = static_cast<size_t>(size.QuadPart);
  5819. hMapping_ =
  5820. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  5821. // Special treatment for an empty file...
  5822. if (hMapping_ == NULL && size_ == 0) {
  5823. close();
  5824. is_open_empty_file = true;
  5825. return true;
  5826. }
  5827. if (hMapping_ == NULL) {
  5828. close();
  5829. return false;
  5830. }
  5831. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  5832. if (addr_ == nullptr) {
  5833. close();
  5834. return false;
  5835. }
  5836. #else
  5837. // O_NONBLOCK so that opening a FIFO does not wait for a writer.
  5838. fd_ = ::open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
  5839. if (fd_ == -1) { return false; }
  5840. // Only a regular file has a size to serve, unlike a directory or a device.
  5841. struct stat sb;
  5842. if (fstat(fd_, &sb) == -1 || !S_ISREG(sb.st_mode) ||
  5843. !fits_in_size_t(static_cast<uint64_t>(sb.st_size))) {
  5844. close();
  5845. return false;
  5846. }
  5847. size_ = static_cast<size_t>(sb.st_size);
  5848. #endif
  5849. return true;
  5850. }
  5851. inline bool mmap::is_open() const {
  5852. #if defined(_WIN32)
  5853. return is_open_empty_file ? true : addr_ != nullptr;
  5854. #else
  5855. return fd_ != -1;
  5856. #endif
  5857. }
  5858. inline size_t mmap::size() const { return size_; }
  5859. inline void mmap::close() {
  5860. #if defined(_WIN32)
  5861. if (addr_) {
  5862. ::UnmapViewOfFile(addr_);
  5863. addr_ = nullptr;
  5864. }
  5865. if (hMapping_) {
  5866. ::CloseHandle(hMapping_);
  5867. hMapping_ = NULL;
  5868. }
  5869. if (hFile_ != INVALID_HANDLE_VALUE) {
  5870. ::CloseHandle(hFile_);
  5871. hFile_ = INVALID_HANDLE_VALUE;
  5872. }
  5873. is_open_empty_file = false;
  5874. #else
  5875. if (fd_ != -1) {
  5876. ::close(fd_);
  5877. fd_ = -1;
  5878. }
  5879. #endif
  5880. size_ = 0;
  5881. }
  5882. inline int close_socket(socket_t sock) noexcept {
  5883. #ifdef _WIN32
  5884. return closesocket(sock);
  5885. #else
  5886. return close(sock);
  5887. #endif
  5888. }
  5889. template <typename T> inline ssize_t handle_EINTR(T fn) {
  5890. ssize_t res = 0;
  5891. while (true) {
  5892. res = fn();
  5893. if (res < 0 && errno == EINTR) {
  5894. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5895. continue;
  5896. }
  5897. break;
  5898. }
  5899. return res;
  5900. }
  5901. inline size_t mmap::read(size_t offset, char *buf, size_t len) const {
  5902. if (offset >= size_) { return 0; }
  5903. len = (std::min)(len, size_ - offset);
  5904. #if defined(_WIN32)
  5905. // Windows does not let a mapped file be truncated.
  5906. std::memcpy(buf, static_cast<const char *>(addr_) + offset, len);
  5907. return len;
  5908. #else
  5909. auto n = handle_EINTR(
  5910. [&]() { return ::pread(fd_, buf, len, static_cast<off_t>(offset)); });
  5911. return n > 0 ? static_cast<size_t>(n) : 0;
  5912. #endif
  5913. }
  5914. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  5915. return handle_EINTR([&]() {
  5916. return recv(sock,
  5917. #ifdef _WIN32
  5918. static_cast<char *>(ptr), static_cast<int>(size),
  5919. #else
  5920. ptr, size,
  5921. #endif
  5922. flags);
  5923. });
  5924. }
  5925. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  5926. int flags) {
  5927. return handle_EINTR([&]() {
  5928. return send(sock,
  5929. #ifdef _WIN32
  5930. static_cast<const char *>(ptr), static_cast<int>(size),
  5931. #else
  5932. ptr, size,
  5933. #endif
  5934. flags);
  5935. });
  5936. }
  5937. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  5938. #ifdef _WIN32
  5939. return ::WSAPoll(fds, nfds, timeout);
  5940. #else
  5941. return ::poll(fds, nfds, timeout);
  5942. #endif
  5943. }
  5944. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  5945. time_t usec) {
  5946. struct pollfd pfd;
  5947. pfd.fd = sock;
  5948. pfd.events = events;
  5949. pfd.revents = 0;
  5950. // A negative timeout waits forever, poll's own convention. 0 keeps meaning
  5951. // "return immediately", which callers here rely on to probe a socket.
  5952. auto timeout = sec < 0 ? -1 : static_cast<int>(sec * 1000 + usec / 1000);
  5953. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  5954. }
  5955. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  5956. return select_impl(sock, POLLIN, sec, usec);
  5957. }
  5958. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  5959. return select_impl(sock, POLLOUT, sec, usec);
  5960. }
  5961. // The point sec and usec from now, for select_until(). A negative sec, or one
  5962. // past what the clock reaches, never comes.
  5963. inline std::chrono::steady_clock::time_point deadline_after(time_t sec,
  5964. time_t usec) {
  5965. auto now = std::chrono::steady_clock::now();
  5966. auto never = (std::chrono::steady_clock::time_point::max)();
  5967. if (sec < 0 ||
  5968. sec >= std::chrono::duration_cast<std::chrono::seconds>(never - now)
  5969. .count()) {
  5970. return never;
  5971. }
  5972. return now + std::chrono::seconds(sec) + std::chrono::microseconds(usec);
  5973. }
  5974. // Waits only for the time left until deadline, so that all the waits of one
  5975. // TLS handshake come out of a single timeout. With interrupted, it waits in
  5976. // slices and gives up once interrupted() returns true, as a local shutdown()
  5977. // would not wake the wait on Windows.
  5978. inline ssize_t
  5979. select_until(socket_t sock, short events,
  5980. std::chrono::steady_clock::time_point deadline,
  5981. const std::function<bool()> &interrupted = nullptr) {
  5982. if (!interrupted) {
  5983. if (deadline == (std::chrono::steady_clock::time_point::max)()) {
  5984. return select_impl(sock, events, -1, 0);
  5985. }
  5986. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  5987. deadline - std::chrono::steady_clock::now())
  5988. .count();
  5989. if (left <= 0) { return 0; }
  5990. return select_impl(sock, events, static_cast<time_t>(left / 1000000),
  5991. static_cast<time_t>(left % 1000000));
  5992. }
  5993. const auto slice = std::chrono::microseconds(100000);
  5994. while (!interrupted()) {
  5995. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  5996. deadline - std::chrono::steady_clock::now());
  5997. auto last = left < slice;
  5998. // poll() takes whole milliseconds, so round the last wait up to keep it
  5999. // from ending before the deadline.
  6000. auto wait_usec = last ? (std::max)((left.count() + 999) / 1000 * 1000,
  6001. static_cast<decltype(left.count())>(0))
  6002. : slice.count();
  6003. auto ret = select_impl(sock, events, 0, static_cast<time_t>(wait_usec));
  6004. if (ret != 0 || last) { return ret; }
  6005. }
  6006. return 0;
  6007. }
  6008. // select_impl(), but waits in slices and gives up once interrupted() returns
  6009. // true
  6010. inline ssize_t select_interruptible(socket_t sock, short events, time_t sec,
  6011. time_t usec,
  6012. const std::function<bool()> &interrupted) {
  6013. if (!interrupted) { return select_impl(sock, events, sec, usec); }
  6014. return select_until(sock, events, deadline_after(sec, usec), interrupted);
  6015. }
  6016. inline ssize_t
  6017. select_read_interruptible(socket_t sock, time_t sec, time_t usec,
  6018. const std::function<bool()> &interrupted) {
  6019. return select_interruptible(sock, POLLIN, sec, usec, interrupted);
  6020. }
  6021. // Waits for a connect in progress, which ends as Error::Canceled once
  6022. // interrupted() returns true
  6023. inline Error
  6024. wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec,
  6025. const std::function<bool()> &interrupted = nullptr) {
  6026. auto ret =
  6027. select_interruptible(sock, POLLIN | POLLOUT, sec, usec, interrupted);
  6028. if (ret == 0) {
  6029. return interrupted && interrupted() ? Error::Canceled
  6030. : Error::ConnectionTimeout;
  6031. }
  6032. if (ret < 0) { return Error::Connection; }
  6033. // A failed connect reports its error here, whatever events poll() returned
  6034. auto error = 0;
  6035. socklen_t len = sizeof(error);
  6036. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  6037. reinterpret_cast<char *>(&error), &len);
  6038. return res >= 0 && !error ? Error::Success : Error::Connection;
  6039. }
  6040. inline bool is_socket_alive(socket_t sock) {
  6041. const auto val = detail::select_read(sock, 0, 0);
  6042. if (val == 0) {
  6043. return true;
  6044. } else if (val < 0 && errno == EBADF) {
  6045. return false;
  6046. }
  6047. char buf[1];
  6048. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  6049. }
  6050. class SocketStream final : public Stream {
  6051. public:
  6052. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6053. time_t write_timeout_sec, time_t write_timeout_usec,
  6054. time_t max_timeout_msec = 0,
  6055. std::chrono::time_point<std::chrono::steady_clock> start_time =
  6056. (std::chrono::steady_clock::time_point::min)());
  6057. ~SocketStream() override;
  6058. bool is_readable() const override;
  6059. bool wait_readable() const override;
  6060. bool wait_writable() const override;
  6061. bool is_peer_alive() const override;
  6062. ssize_t read(char *ptr, size_t size) override;
  6063. ssize_t write(const char *ptr, size_t size) override;
  6064. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  6065. void get_local_ip_and_port(std::string &ip, int &port) const override;
  6066. socket_t socket() const override;
  6067. time_t duration() const override;
  6068. void set_read_timeout(time_t sec, time_t usec = 0) override;
  6069. void set_max_timeout(time_t msec) override;
  6070. void set_read_interrupt(std::function<bool()> interrupted) override;
  6071. const char *buffered_data(size_t &size) const override;
  6072. void consume_buffered(size_t size) override;
  6073. // The caller has just seen this socket become readable. Lets the next read
  6074. // skip its own readiness wait, which would otherwise ask the kernel a
  6075. // question that was answered a moment ago. Consumed by that read.
  6076. void set_readable_hint() { readable_hint_ = true; }
  6077. // Frees the read buffer of an idle stream until its next read. Nothing may
  6078. // be buffered.
  6079. void release_buffer();
  6080. private:
  6081. bool ensure_readable();
  6082. socket_t sock_;
  6083. // Atomic because ws::WebSocket::set_read_timeout() reaches this from another
  6084. // thread while a read is in flight -- that is the point of it, for a caller
  6085. // holding one connection and wanting control back to send on it.
  6086. std::atomic<time_t> read_timeout_sec_;
  6087. std::atomic<time_t> read_timeout_usec_;
  6088. time_t write_timeout_sec_;
  6089. time_t write_timeout_usec_;
  6090. time_t max_timeout_msec_;
  6091. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  6092. std::function<bool()> read_interrupted_;
  6093. std::vector<char> read_buff_;
  6094. size_t read_buff_off_ = 0;
  6095. size_t read_buff_content_size_ = 0;
  6096. bool readable_hint_ = false;
  6097. static const size_t read_buff_size_ = 1024l * 4;
  6098. };
  6099. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  6100. time_t keep_alive_timeout_sec) {
  6101. using namespace std::chrono;
  6102. const auto interval_usec =
  6103. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  6104. // Avoid expensive `steady_clock::now()` call for the first time
  6105. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  6106. const auto start = steady_clock::now() - microseconds{interval_usec};
  6107. const auto timeout = seconds{keep_alive_timeout_sec};
  6108. while (true) {
  6109. if (svr_sock == INVALID_SOCKET) {
  6110. break; // Server socket is closed
  6111. }
  6112. auto val = select_read(sock, 0, interval_usec);
  6113. if (val < 0) {
  6114. break; // Ssocket error
  6115. } else if (val == 0) {
  6116. if (steady_clock::now() - start > timeout) {
  6117. break; // Timeout
  6118. }
  6119. } else {
  6120. return true; // Ready for read
  6121. }
  6122. }
  6123. return false;
  6124. }
  6125. // Serves the requests of one connection while they come. A client may
  6126. // pipeline its requests (RFC 9112 9.3.2), so reading one request can pull the
  6127. // start of the next one into the stream's buffer; that request must be served
  6128. // without waiting for the socket to become readable again, since its bytes are
  6129. // no longer on the socket. Otherwise `wait_for_next_request` waits for the
  6130. // socket, and returning false ends the loop. `served` counts the requests
  6131. // served on this connection so far.
  6132. template <typename S, typename W, typename T>
  6133. inline bool process_server_socket_core(S &strm, size_t &served,
  6134. size_t keep_alive_max_count,
  6135. W wait_for_next_request, T callback) {
  6136. auto ret = false;
  6137. // A keep_alive_max_count of 0 sets no limit.
  6138. for (; keep_alive_max_count == 0 || served < keep_alive_max_count; served++) {
  6139. if (!strm.is_readable()) {
  6140. if (!wait_for_next_request()) { break; }
  6141. strm.set_readable_hint();
  6142. }
  6143. auto close_connection = served + 1 == keep_alive_max_count;
  6144. auto connection_closed = false;
  6145. ret = callback(strm, close_connection, connection_closed);
  6146. if (!ret || connection_closed) { break; }
  6147. }
  6148. return ret;
  6149. }
  6150. template <typename T>
  6151. inline bool
  6152. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  6153. size_t keep_alive_max_count,
  6154. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  6155. time_t read_timeout_usec, time_t write_timeout_sec,
  6156. time_t write_timeout_usec, T callback) {
  6157. // One stream per connection: its read buffer can already hold the start of
  6158. // the next, pipelined request.
  6159. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  6160. write_timeout_sec, write_timeout_usec);
  6161. size_t served = 0;
  6162. return process_server_socket_core(
  6163. strm, served, keep_alive_max_count,
  6164. [&]() { return keep_alive(svr_sock, sock, keep_alive_timeout_sec); },
  6165. callback);
  6166. }
  6167. inline bool process_client_socket(
  6168. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6169. time_t write_timeout_sec, time_t write_timeout_usec,
  6170. time_t max_timeout_msec,
  6171. std::chrono::time_point<std::chrono::steady_clock> start_time,
  6172. std::function<bool(Stream &)> callback) {
  6173. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  6174. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  6175. start_time);
  6176. return callback(strm);
  6177. }
  6178. inline int shutdown_socket(socket_t sock) noexcept {
  6179. #ifdef _WIN32
  6180. return shutdown(sock, SD_BOTH);
  6181. #else
  6182. return shutdown(sock, SHUT_RDWR);
  6183. #endif
  6184. }
  6185. // Half-closes the write side and drains any in-flight/queued bytes before
  6186. // the final shutdown+close. Closing with unread data in the receive queue
  6187. // (or bytes arriving after the receive side is closed) makes the stack send
  6188. // an abortive RST instead of a graceful FIN, which can make the peer see the
  6189. // response as a failed read even though it was fully written. With a
  6190. // `wait_msec` of 0, it reads once, without waiting.
  6191. inline void drain_and_close_socket(socket_t sock,
  6192. time_t wait_msec = 100) noexcept {
  6193. #ifdef _WIN32
  6194. shutdown(sock, SD_SEND);
  6195. #else
  6196. shutdown(sock, SHUT_WR);
  6197. #endif
  6198. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6199. size_t total = 0;
  6200. const auto deadline = std::chrono::steady_clock::now() +
  6201. std::chrono::milliseconds(wait_msec); // bound #1
  6202. auto usec_left = [&]() {
  6203. const auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  6204. deadline - std::chrono::steady_clock::now())
  6205. .count();
  6206. return static_cast<time_t>(
  6207. (std::max)(left, std::chrono::microseconds::rep(0)));
  6208. };
  6209. do {
  6210. if (select_read(sock, 0, usec_left()) <= 0) { break; }
  6211. const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  6212. if (n <= 0) { break; }
  6213. total += static_cast<size_t>(n);
  6214. } while (usec_left() > 0 && total < size_t(1024u * 1024u)); // bound #2
  6215. shutdown_socket(sock);
  6216. close_socket(sock);
  6217. }
  6218. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  6219. if (s.size() > 1 && s[0] == '\0') {
  6220. auto ret = s;
  6221. ret[0] = '@';
  6222. return ret;
  6223. }
  6224. return s;
  6225. }
  6226. inline std::string
  6227. unescape_abstract_namespace_unix_domain(const std::string &s) {
  6228. if (s.size() > 1 && s[0] == '@') {
  6229. auto ret = s;
  6230. ret[0] = '\0';
  6231. return ret;
  6232. }
  6233. return s;
  6234. }
  6235. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  6236. const struct addrinfo *hints,
  6237. struct addrinfo **res, time_t timeout_sec) {
  6238. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  6239. if (timeout_sec <= 0) {
  6240. // No timeout specified, use standard getaddrinfo
  6241. return getaddrinfo(node, service, hints, res);
  6242. }
  6243. #ifdef _WIN32
  6244. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  6245. OVERLAPPED overlapped = {};
  6246. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  6247. if (!event) { return EAI_FAIL; }
  6248. overlapped.hEvent = event;
  6249. PADDRINFOEXW result_addrinfo = nullptr;
  6250. HANDLE cancel_handle = nullptr;
  6251. ADDRINFOEXW hints_ex = {};
  6252. if (hints) {
  6253. hints_ex.ai_flags = hints->ai_flags;
  6254. hints_ex.ai_family = hints->ai_family;
  6255. hints_ex.ai_socktype = hints->ai_socktype;
  6256. hints_ex.ai_protocol = hints->ai_protocol;
  6257. }
  6258. auto wnode = u8string_to_wstring(node);
  6259. auto wservice = u8string_to_wstring(service);
  6260. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  6261. hints ? &hints_ex : nullptr, &result_addrinfo,
  6262. nullptr, &overlapped, nullptr, &cancel_handle);
  6263. if (ret == WSA_IO_PENDING) {
  6264. auto wait_result =
  6265. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  6266. if (wait_result == WAIT_TIMEOUT) {
  6267. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  6268. ::CloseHandle(event);
  6269. return EAI_AGAIN;
  6270. }
  6271. DWORD bytes_returned;
  6272. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  6273. &bytes_returned, FALSE)) {
  6274. ::CloseHandle(event);
  6275. return ::WSAGetLastError();
  6276. }
  6277. }
  6278. ::CloseHandle(event);
  6279. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  6280. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  6281. return 0;
  6282. }
  6283. return ret;
  6284. #elif TARGET_OS_MAC && defined(__clang__)
  6285. if (!node) { return EAI_NONAME; }
  6286. // macOS implementation using CFHost API for asynchronous DNS resolution
  6287. CFStringRef hostname_ref = CFStringCreateWithCString(
  6288. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  6289. if (!hostname_ref) { return EAI_MEMORY; }
  6290. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  6291. CFRelease(hostname_ref);
  6292. if (!host_ref) { return EAI_MEMORY; }
  6293. // Set up context for callback
  6294. struct CFHostContext {
  6295. bool completed = false;
  6296. bool success = false;
  6297. CFArrayRef addresses = nullptr;
  6298. std::mutex mutex;
  6299. std::condition_variable cv;
  6300. } context;
  6301. CFHostClientContext client_context;
  6302. memset(&client_context, 0, sizeof(client_context));
  6303. client_context.info = &context;
  6304. // Set callback
  6305. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  6306. const CFStreamError *error, void *info) {
  6307. auto ctx = static_cast<CFHostContext *>(info);
  6308. std::lock_guard<std::mutex> lock(ctx->mutex);
  6309. if (error && error->error != 0) {
  6310. ctx->success = false;
  6311. } else {
  6312. Boolean hasBeenResolved;
  6313. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  6314. if (ctx->addresses && hasBeenResolved) {
  6315. CFRetain(ctx->addresses);
  6316. ctx->success = true;
  6317. } else {
  6318. ctx->success = false;
  6319. }
  6320. }
  6321. ctx->completed = true;
  6322. ctx->cv.notify_one();
  6323. };
  6324. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  6325. CFRelease(host_ref);
  6326. return EAI_SYSTEM;
  6327. }
  6328. // Schedule on run loop
  6329. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  6330. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  6331. // Start resolution
  6332. CFStreamError stream_error;
  6333. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  6334. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  6335. CFRelease(host_ref);
  6336. return EAI_FAIL;
  6337. }
  6338. // Wait for completion with timeout
  6339. auto timeout_time =
  6340. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  6341. bool timed_out = false;
  6342. {
  6343. std::unique_lock<std::mutex> lock(context.mutex);
  6344. while (!context.completed) {
  6345. auto now = std::chrono::steady_clock::now();
  6346. if (now >= timeout_time) {
  6347. timed_out = true;
  6348. break;
  6349. }
  6350. // Run the runloop for a short time
  6351. lock.unlock();
  6352. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  6353. lock.lock();
  6354. }
  6355. }
  6356. // Clean up
  6357. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  6358. CFHostSetClient(host_ref, nullptr, nullptr);
  6359. if (timed_out || !context.completed) {
  6360. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  6361. CFRelease(host_ref);
  6362. return EAI_AGAIN;
  6363. }
  6364. if (!context.success || !context.addresses) {
  6365. CFRelease(host_ref);
  6366. return EAI_NODATA;
  6367. }
  6368. // Convert CFArray to addrinfo
  6369. CFIndex count = CFArrayGetCount(context.addresses);
  6370. if (count == 0) {
  6371. CFRelease(context.addresses);
  6372. CFRelease(host_ref);
  6373. return EAI_NODATA;
  6374. }
  6375. struct addrinfo *result_addrinfo = nullptr;
  6376. struct addrinfo **current = &result_addrinfo;
  6377. for (CFIndex i = 0; i < count; i++) {
  6378. CFDataRef addr_data =
  6379. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  6380. if (!addr_data) continue;
  6381. const struct sockaddr *sockaddr_ptr =
  6382. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  6383. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  6384. // Allocate addrinfo structure
  6385. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  6386. if (!*current) {
  6387. freeaddrinfo(result_addrinfo);
  6388. CFRelease(context.addresses);
  6389. CFRelease(host_ref);
  6390. return EAI_MEMORY;
  6391. }
  6392. memset(*current, 0, sizeof(struct addrinfo));
  6393. // Set up addrinfo fields
  6394. (*current)->ai_family = sockaddr_ptr->sa_family;
  6395. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  6396. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  6397. (*current)->ai_addrlen = sockaddr_len;
  6398. // Copy sockaddr
  6399. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  6400. if (!(*current)->ai_addr) {
  6401. freeaddrinfo(result_addrinfo);
  6402. CFRelease(context.addresses);
  6403. CFRelease(host_ref);
  6404. return EAI_MEMORY;
  6405. }
  6406. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  6407. // Set port if service is specified
  6408. if (service && *service) {
  6409. int port = 0;
  6410. if (parse_port(service, strlen(service), port)) {
  6411. if (sockaddr_ptr->sa_family == AF_INET) {
  6412. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  6413. ->sin_port = htons(static_cast<uint16_t>(port));
  6414. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  6415. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  6416. ->sin6_port = htons(static_cast<uint16_t>(port));
  6417. }
  6418. }
  6419. }
  6420. current = &((*current)->ai_next);
  6421. }
  6422. CFRelease(context.addresses);
  6423. CFRelease(host_ref);
  6424. *res = result_addrinfo;
  6425. return 0;
  6426. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  6427. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) && \
  6428. !defined(CPPHTTPLIB_THREAD_SANITIZER)
  6429. // Skipped under TSan: glibc's internal resolver thread is invisible to it.
  6430. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  6431. // the resolver worker still references the stack-local gaicb. The cancel
  6432. // path therefore waits (gai_suspend with no timeout) for the worker to
  6433. // actually finish before letting the stack frame go. The trade-off is that
  6434. // a wedged DNS server can hold this thread for the system resolver timeout
  6435. // (~30s by default) past the caller's connection timeout.
  6436. struct gaicb request{};
  6437. struct gaicb *requests[1] = {&request};
  6438. struct sigevent sevp{};
  6439. struct timespec timeout{timeout_sec, 0};
  6440. request.ar_name = node;
  6441. request.ar_service = service;
  6442. request.ar_request = hints;
  6443. sevp.sigev_notify = SIGEV_NONE;
  6444. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  6445. if (rc != 0) { return rc; }
  6446. auto cleanup = scope_exit([&] {
  6447. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  6448. });
  6449. int wait_result = gai_suspend(requests, 1, &timeout);
  6450. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  6451. int gai_result = gai_error(&request);
  6452. if (gai_result == 0) {
  6453. *res = request.ar_result;
  6454. request.ar_result = nullptr;
  6455. return 0;
  6456. }
  6457. return gai_result;
  6458. }
  6459. gai_cancel(&request);
  6460. while (gai_error(&request) == EAI_INPROGRESS) {
  6461. gai_suspend(requests, 1, nullptr);
  6462. }
  6463. return wait_result;
  6464. #else
  6465. // Fallback implementation using thread-based timeout for other Unix systems.
  6466. struct GetAddrInfoState {
  6467. ~GetAddrInfoState() {
  6468. if (info) { freeaddrinfo(info); }
  6469. }
  6470. std::mutex mutex;
  6471. std::condition_variable result_cv;
  6472. bool completed = false;
  6473. int result = EAI_SYSTEM;
  6474. std::string node;
  6475. std::string service;
  6476. struct addrinfo hints;
  6477. struct addrinfo *info = nullptr;
  6478. };
  6479. // Allocate on the heap, so the resolver thread can keep using the data.
  6480. auto state = std::make_shared<GetAddrInfoState>();
  6481. if (node) { state->node = node; }
  6482. state->service = service;
  6483. state->hints = *hints;
  6484. std::thread resolve_thread([state]() {
  6485. auto thread_result =
  6486. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  6487. &state->info);
  6488. std::lock_guard<std::mutex> lock(state->mutex);
  6489. state->result = thread_result;
  6490. state->completed = true;
  6491. state->result_cv.notify_one();
  6492. });
  6493. // Wait for completion or timeout
  6494. std::unique_lock<std::mutex> lock(state->mutex);
  6495. auto finished =
  6496. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  6497. [&] { return state->completed; });
  6498. if (finished) {
  6499. // Operation completed within timeout
  6500. resolve_thread.join();
  6501. *res = state->info;
  6502. state->info = nullptr; // Pass ownership to caller
  6503. return state->result;
  6504. } else {
  6505. // Timeout occurred
  6506. resolve_thread.detach(); // Let the thread finish in background
  6507. return EAI_AGAIN; // Return timeout error
  6508. }
  6509. #endif
  6510. #else
  6511. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  6512. return getaddrinfo(node, service, hints, res);
  6513. #endif
  6514. }
  6515. template <typename BindOrConnect>
  6516. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  6517. int address_family, int socket_flags, bool tcp_nodelay,
  6518. bool ipv6_v6only, SocketOptions socket_options,
  6519. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  6520. // Get address info
  6521. const char *node = nullptr;
  6522. struct addrinfo hints;
  6523. struct addrinfo *result;
  6524. memset(&hints, 0, sizeof(struct addrinfo));
  6525. hints.ai_socktype = SOCK_STREAM;
  6526. hints.ai_protocol = IPPROTO_IP;
  6527. if (!ip.empty()) {
  6528. node = ip.c_str();
  6529. // Ask getaddrinfo to convert IP in c-string to address
  6530. hints.ai_family = AF_UNSPEC;
  6531. hints.ai_flags = AI_NUMERICHOST;
  6532. } else {
  6533. if (!host.empty()) { node = host.c_str(); }
  6534. hints.ai_family = address_family;
  6535. hints.ai_flags = socket_flags;
  6536. }
  6537. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  6538. if (hints.ai_family == AF_UNIX) {
  6539. const auto addrlen = host.length();
  6540. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  6541. #ifdef SOCK_CLOEXEC
  6542. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  6543. hints.ai_protocol);
  6544. #else
  6545. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  6546. #endif
  6547. if (sock != INVALID_SOCKET) {
  6548. sockaddr_un addr{};
  6549. addr.sun_family = AF_UNIX;
  6550. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  6551. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  6552. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  6553. hints.ai_addrlen = static_cast<socklen_t>(
  6554. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  6555. #ifndef SOCK_CLOEXEC
  6556. #ifndef _WIN32
  6557. fcntl(sock, F_SETFD, FD_CLOEXEC);
  6558. #endif
  6559. #endif
  6560. if (socket_options) { socket_options(sock); }
  6561. #ifdef _WIN32
  6562. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  6563. // remove the option.
  6564. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  6565. #endif
  6566. bool dummy;
  6567. if (!bind_or_connect(sock, hints, dummy)) {
  6568. close_socket(sock);
  6569. sock = INVALID_SOCKET;
  6570. }
  6571. }
  6572. return sock;
  6573. }
  6574. #endif
  6575. auto service = std::to_string(port);
  6576. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  6577. timeout_sec)) {
  6578. #if defined __linux__ && !defined __ANDROID__
  6579. res_init();
  6580. #endif
  6581. return INVALID_SOCKET;
  6582. }
  6583. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6584. for (auto rp = result; rp; rp = rp->ai_next) {
  6585. // Create a socket
  6586. #ifdef _WIN32
  6587. auto sock =
  6588. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  6589. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  6590. /**
  6591. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  6592. * and above the socket creation fails on older Windows Systems.
  6593. *
  6594. * Let's try to create a socket the old way in this case.
  6595. *
  6596. * Reference:
  6597. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  6598. *
  6599. * WSA_FLAG_NO_HANDLE_INHERIT:
  6600. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  6601. * SP1, and later
  6602. *
  6603. */
  6604. if (sock == INVALID_SOCKET) {
  6605. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  6606. }
  6607. #else
  6608. #ifdef SOCK_CLOEXEC
  6609. auto sock =
  6610. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  6611. #else
  6612. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  6613. #endif
  6614. #endif
  6615. if (sock == INVALID_SOCKET) { continue; }
  6616. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  6617. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  6618. close_socket(sock);
  6619. continue;
  6620. }
  6621. #endif
  6622. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  6623. if (rp->ai_family == AF_INET6) {
  6624. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  6625. }
  6626. if (socket_options) { socket_options(sock); }
  6627. // bind or connect
  6628. auto quit = false;
  6629. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  6630. close_socket(sock);
  6631. if (quit) { break; }
  6632. }
  6633. return INVALID_SOCKET;
  6634. }
  6635. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  6636. #ifdef _WIN32
  6637. auto flags = nonblocking ? 1UL : 0UL;
  6638. ioctlsocket(sock, FIONBIO, &flags);
  6639. #else
  6640. auto flags = fcntl(sock, F_GETFL, 0);
  6641. fcntl(sock, F_SETFL,
  6642. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  6643. #endif
  6644. }
  6645. inline bool is_connection_error() {
  6646. #ifdef _WIN32
  6647. return WSAGetLastError() != WSAEWOULDBLOCK;
  6648. #else
  6649. return errno != EINPROGRESS;
  6650. #endif
  6651. }
  6652. // accept() failed because the process or the network stack is temporarily out
  6653. // of resources. The listening socket is still usable, so back off briefly and
  6654. // try again.
  6655. inline bool is_accept_resource_error() {
  6656. #ifdef _WIN32
  6657. auto err = WSAGetLastError();
  6658. return err == WSAEMFILE || err == WSAENOBUFS;
  6659. #else
  6660. auto err = errno;
  6661. return err == EMFILE || err == ENFILE || err == ENOBUFS || err == ENOMEM;
  6662. #endif
  6663. }
  6664. // accept() failed for a reason that says nothing about the listening socket:
  6665. // the pending connection went away before it could be accepted, or the call
  6666. // was interrupted. Retry immediately. WSAAccept()'s own documentation omits
  6667. // WSAECONNRESET, but the accept() it wraps reports an aborted pending
  6668. // connection that way.
  6669. inline bool is_accept_transient_error() {
  6670. #ifdef _WIN32
  6671. auto err = WSAGetLastError();
  6672. return err == WSAEINTR || err == WSAEWOULDBLOCK || err == WSAECONNRESET ||
  6673. err == WSAECONNABORTED;
  6674. #else
  6675. auto err = errno;
  6676. return err == EINTR || err == EAGAIN || err == EWOULDBLOCK ||
  6677. err == ECONNABORTED;
  6678. #endif
  6679. }
  6680. inline socket_t accept_socket(socket_t svr_sock) {
  6681. #if defined _WIN32
  6682. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  6683. // OVERLAPPED
  6684. return WSAAccept(svr_sock, nullptr, nullptr, nullptr, 0);
  6685. #elif defined SOCK_CLOEXEC
  6686. return accept4(svr_sock, nullptr, nullptr, SOCK_CLOEXEC);
  6687. #else
  6688. return accept(svr_sock, nullptr, nullptr);
  6689. #endif
  6690. }
  6691. inline bool is_would_block_error() {
  6692. #ifdef _WIN32
  6693. return WSAGetLastError() == WSAEWOULDBLOCK;
  6694. #else
  6695. return errno == EAGAIN || errno == EWOULDBLOCK;
  6696. #endif
  6697. }
  6698. inline bool create_socket_pair(socket_t sv[2]) {
  6699. #ifdef _WIN32
  6700. auto listener = create_socket(
  6701. std::string(), "127.0.0.1", 0, AF_INET, 0, false, false, nullptr,
  6702. [](socket_t sock, struct addrinfo &ai, bool &) {
  6703. return ::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen)) == 0 &&
  6704. ::listen(sock, 1) == 0;
  6705. });
  6706. if (listener == INVALID_SOCKET) { return false; }
  6707. socket_t a = INVALID_SOCKET;
  6708. socket_t b = INVALID_SOCKET;
  6709. sockaddr_in addr{};
  6710. auto addr_len = static_cast<int>(sizeof(addr));
  6711. if (::getsockname(listener, reinterpret_cast<sockaddr *>(&addr), &addr_len) ==
  6712. 0) {
  6713. a = create_socket(std::string(), "127.0.0.1", ntohs(addr.sin_port), AF_INET,
  6714. 0, true, false, nullptr,
  6715. [](socket_t sock, struct addrinfo &ai, bool &) {
  6716. return ::connect(sock, ai.ai_addr,
  6717. static_cast<int>(ai.ai_addrlen)) == 0;
  6718. });
  6719. // Unlike accept(), this keeps the listener's no-inherit flag.
  6720. if (a != INVALID_SOCKET) {
  6721. b = WSAAccept(listener, nullptr, nullptr, nullptr, 0);
  6722. }
  6723. }
  6724. close_socket(listener);
  6725. // Any local process could connect while the listener was open, so make sure
  6726. // that the connection we accepted is the one we made.
  6727. if (b != INVALID_SOCKET) {
  6728. sockaddr_in local{}, peer{};
  6729. auto local_len = static_cast<int>(sizeof(local));
  6730. auto peer_len = static_cast<int>(sizeof(peer));
  6731. if (::getsockname(a, reinterpret_cast<sockaddr *>(&local), &local_len) !=
  6732. 0 ||
  6733. ::getpeername(b, reinterpret_cast<sockaddr *>(&peer), &peer_len) != 0 ||
  6734. local.sin_port != peer.sin_port ||
  6735. local.sin_addr.s_addr != peer.sin_addr.s_addr) {
  6736. close_socket(b);
  6737. b = INVALID_SOCKET;
  6738. }
  6739. }
  6740. if (b == INVALID_SOCKET) {
  6741. if (a != INVALID_SOCKET) { close_socket(a); }
  6742. return false;
  6743. }
  6744. sv[0] = a;
  6745. sv[1] = b;
  6746. return true;
  6747. #else
  6748. #ifdef SOCK_CLOEXEC
  6749. return ::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) == 0;
  6750. #else
  6751. if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) { return false; }
  6752. fcntl(sv[0], F_SETFD, FD_CLOEXEC);
  6753. fcntl(sv[1], F_SETFD, FD_CLOEXEC);
  6754. return true;
  6755. #endif
  6756. #endif
  6757. }
  6758. inline PollerWaker::~PollerWaker() {
  6759. if (pair_fd_ != INVALID_SOCKET) { close_socket(pair_fd_); }
  6760. if (fd_ != INVALID_SOCKET) { close_socket(fd_); }
  6761. }
  6762. inline bool PollerWaker::open() {
  6763. // wake() must not block its caller, and drain() must not block the poller.
  6764. #ifdef __linux__
  6765. fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  6766. return fd_ != INVALID_SOCKET;
  6767. #else
  6768. socket_t sv[2];
  6769. if (!create_socket_pair(sv)) { return false; }
  6770. fd_ = sv[0];
  6771. pair_fd_ = sv[1];
  6772. set_nonblocking(fd_, true);
  6773. set_nonblocking(pair_fd_, true);
  6774. return true;
  6775. #endif
  6776. }
  6777. inline void PollerWaker::wake() noexcept {
  6778. if (pending_.exchange(true)) { return; }
  6779. #ifdef __linux__
  6780. const uint64_t one = 1;
  6781. auto r = write(fd_, &one, sizeof(one));
  6782. (void)r;
  6783. #else
  6784. const char c = 1;
  6785. send_socket(pair_fd_, &c, 1, CPPHTTPLIB_SEND_FLAGS);
  6786. #endif
  6787. }
  6788. inline void PollerWaker::drain() noexcept {
  6789. // While pending_ is set, at most one wake is unread, and one read takes it.
  6790. #ifdef __linux__
  6791. uint64_t count;
  6792. auto r = read(fd_, &count, sizeof(count));
  6793. (void)r;
  6794. #else
  6795. char buf[64];
  6796. read_socket(fd_, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  6797. #endif
  6798. // Only after the read: cleared before it, a wake() in between would be read
  6799. // here and leave pending_ set with nothing to read. One skipped during the
  6800. // read is fine, as the caller checks what it was woken for afterwards.
  6801. pending_ = false;
  6802. }
  6803. inline std::unique_ptr<Poller> PollPoller::create() {
  6804. std::unique_ptr<PollPoller> poller(new PollPoller());
  6805. if (!poller->waker_.open()) { return nullptr; }
  6806. struct pollfd pfd;
  6807. pfd.fd = poller->waker_.fd();
  6808. pfd.events = POLLIN;
  6809. pfd.revents = 0;
  6810. poller->fds_.push_back(pfd);
  6811. poller->tokens_.push_back(0);
  6812. return std::unique_ptr<Poller>(poller.release());
  6813. }
  6814. inline bool PollPoller::arm(socket_t fd, Token token) {
  6815. assert(index_.find(fd) == index_.end());
  6816. struct pollfd pfd;
  6817. pfd.fd = fd;
  6818. pfd.events = POLLIN;
  6819. pfd.revents = 0;
  6820. index_[fd] = fds_.size();
  6821. fds_.push_back(pfd);
  6822. tokens_.push_back(token);
  6823. return true;
  6824. }
  6825. inline void PollPoller::disarm(socket_t fd) {
  6826. auto it = index_.find(fd);
  6827. if (it != index_.end()) { remove_at(it->second); }
  6828. }
  6829. // Fills the hole with the last entry, so that arm() and disarm() are O(1).
  6830. inline void PollPoller::remove_at(size_t index) {
  6831. assert(index > 0 && index < fds_.size());
  6832. auto last = fds_.size() - 1;
  6833. index_.erase(fds_[index].fd);
  6834. if (index != last) {
  6835. fds_[index] = fds_[last];
  6836. tokens_[index] = tokens_[last];
  6837. index_[fds_[index].fd] = index;
  6838. }
  6839. fds_.pop_back();
  6840. tokens_.pop_back();
  6841. }
  6842. inline bool PollPoller::wait(int timeout_ms, std::vector<Token> &ready) {
  6843. ready.clear();
  6844. auto n = handle_EINTR([&]() {
  6845. return poll_wrapper(fds_.data(), static_cast<nfds_t>(fds_.size()),
  6846. timeout_ms);
  6847. });
  6848. if (n <= 0) { return false; }
  6849. auto woken = fds_[0].revents != 0;
  6850. if (woken) {
  6851. n--;
  6852. waker_.drain();
  6853. }
  6854. // Walk backwards: remove_at() moves the last entry, already seen, into the
  6855. // freed slot.
  6856. for (auto i = fds_.size(); n > 0 && i-- > 1;) {
  6857. auto revents = fds_[i].revents;
  6858. if (revents == 0) { continue; }
  6859. n--;
  6860. assert(!(revents & POLLNVAL)); // closed while armed
  6861. if (!(revents & POLLNVAL)) { ready.push_back(tokens_[i]); }
  6862. remove_at(i);
  6863. }
  6864. return woken;
  6865. }
  6866. #ifdef __linux__
  6867. inline std::unique_ptr<Poller> EpollPoller::create() {
  6868. std::unique_ptr<EpollPoller> poller(new EpollPoller());
  6869. poller->epfd_ = epoll_create1(EPOLL_CLOEXEC);
  6870. if (poller->epfd_ < 0 || !poller->waker_.open()) { return nullptr; }
  6871. epoll_event ev{};
  6872. ev.events = EPOLLIN; // level-triggered: it stays readable until drained
  6873. ev.data.u64 = poller->waker_.token();
  6874. if (epoll_ctl(poller->epfd_, EPOLL_CTL_ADD, poller->waker_.fd(), &ev) != 0) {
  6875. return nullptr;
  6876. }
  6877. poller->events_.resize(256);
  6878. return std::unique_ptr<Poller>(poller.release());
  6879. }
  6880. inline EpollPoller::~EpollPoller() {
  6881. if (epfd_ >= 0) { close(epfd_); }
  6882. }
  6883. inline bool EpollPoller::arm(socket_t fd, Token token) {
  6884. epoll_event ev{};
  6885. ev.events = EPOLLIN | EPOLLONESHOT;
  6886. ev.data.u64 = token;
  6887. // A delivered descriptor stays registered, only disabled, so modify it.
  6888. // One that was closed in between, or never armed, has to be added.
  6889. return epoll_ctl(epfd_, EPOLL_CTL_MOD, fd, &ev) == 0 ||
  6890. (errno == ENOENT && epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) == 0);
  6891. }
  6892. inline void EpollPoller::disarm(socket_t fd) {
  6893. epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, nullptr);
  6894. }
  6895. inline bool EpollPoller::wait(int timeout_ms, std::vector<Token> &ready) {
  6896. ready.clear();
  6897. auto n = handle_EINTR([&]() {
  6898. return epoll_wait(epfd_, events_.data(), static_cast<int>(events_.size()),
  6899. timeout_ms);
  6900. });
  6901. auto woken = false;
  6902. for (auto i = 0; i < n; i++) {
  6903. auto token = static_cast<Token>(events_[static_cast<size_t>(i)].data.u64);
  6904. if (token == waker_.token()) {
  6905. woken = true;
  6906. waker_.drain();
  6907. } else {
  6908. ready.push_back(token);
  6909. }
  6910. }
  6911. return woken;
  6912. }
  6913. #endif
  6914. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  6915. inline std::unique_ptr<Poller> KqueuePoller::create() {
  6916. std::unique_ptr<KqueuePoller> poller(new KqueuePoller());
  6917. poller->kq_ = kqueue();
  6918. if (poller->kq_ < 0) { return nullptr; }
  6919. fcntl(poller->kq_, F_SETFD, FD_CLOEXEC);
  6920. if (!poller->waker_.open()) { return nullptr; }
  6921. // Level-triggered: it stays readable until drained.
  6922. struct kevent ev;
  6923. EV_SET(&ev, poller->waker_.fd(), EVFILT_READ, EV_ADD, 0, 0,
  6924. reinterpret_cast<void *>(poller->waker_.token()));
  6925. if (kevent(poller->kq_, &ev, 1, nullptr, 0, nullptr) != 0) { return nullptr; }
  6926. poller->events_.resize(256);
  6927. return std::unique_ptr<Poller>(poller.release());
  6928. }
  6929. inline KqueuePoller::~KqueuePoller() {
  6930. if (kq_ >= 0) { close(kq_); }
  6931. }
  6932. inline bool KqueuePoller::arm(socket_t fd, Token token) {
  6933. // EV_ONESHOT deletes the event once it is delivered.
  6934. struct kevent ev;
  6935. EV_SET(&ev, fd, EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0,
  6936. reinterpret_cast<void *>(token));
  6937. return kevent(kq_, &ev, 1, nullptr, 0, nullptr) == 0;
  6938. }
  6939. inline void KqueuePoller::disarm(socket_t fd) {
  6940. struct kevent ev;
  6941. EV_SET(&ev, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr);
  6942. kevent(kq_, &ev, 1, nullptr, 0, nullptr);
  6943. }
  6944. inline bool KqueuePoller::wait(int timeout_ms, std::vector<Token> &ready) {
  6945. ready.clear();
  6946. struct timespec ts;
  6947. ts.tv_sec = timeout_ms / 1000;
  6948. ts.tv_nsec = static_cast<long>(timeout_ms % 1000) * 1000000;
  6949. auto n = handle_EINTR([&]() {
  6950. return kevent(kq_, nullptr, 0, events_.data(),
  6951. static_cast<int>(events_.size()),
  6952. timeout_ms < 0 ? nullptr : &ts);
  6953. });
  6954. auto woken = false;
  6955. for (auto i = 0; i < n; i++) {
  6956. auto token = reinterpret_cast<Token>(events_[static_cast<size_t>(i)].udata);
  6957. if (token == waker_.token()) {
  6958. woken = true;
  6959. waker_.drain();
  6960. } else {
  6961. ready.push_back(token);
  6962. }
  6963. }
  6964. return woken;
  6965. }
  6966. #endif
  6967. inline std::unique_ptr<Poller> make_poller() {
  6968. #if defined(__linux__)
  6969. auto poller = EpollPoller::create();
  6970. if (poller) { return poller; }
  6971. #elif defined(CPPHTTPLIB_KQUEUE_POLLER)
  6972. auto poller = KqueuePoller::create();
  6973. if (poller) { return poller; }
  6974. #endif
  6975. return PollPoller::create();
  6976. }
  6977. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  6978. struct addrinfo hints;
  6979. struct addrinfo *result;
  6980. memset(&hints, 0, sizeof(struct addrinfo));
  6981. hints.ai_family = AF_UNSPEC;
  6982. hints.ai_socktype = SOCK_STREAM;
  6983. hints.ai_protocol = 0;
  6984. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  6985. return false;
  6986. }
  6987. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6988. auto ret = false;
  6989. for (auto rp = result; rp; rp = rp->ai_next) {
  6990. const auto &ai = *rp;
  6991. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6992. ret = true;
  6993. break;
  6994. }
  6995. }
  6996. return ret;
  6997. }
  6998. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  6999. #define USE_IF2IP
  7000. #endif
  7001. #ifdef USE_IF2IP
  7002. inline std::string if2ip(int address_family, const std::string &ifn) {
  7003. struct ifaddrs *ifap;
  7004. getifaddrs(&ifap);
  7005. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  7006. std::string addr_candidate;
  7007. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  7008. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  7009. (AF_UNSPEC == address_family ||
  7010. ifa->ifa_addr->sa_family == address_family)) {
  7011. if (ifa->ifa_addr->sa_family == AF_INET) {
  7012. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  7013. char buf[INET_ADDRSTRLEN];
  7014. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  7015. return std::string(buf, INET_ADDRSTRLEN);
  7016. }
  7017. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  7018. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  7019. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  7020. char buf[INET6_ADDRSTRLEN] = {};
  7021. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  7022. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  7023. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  7024. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  7025. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  7026. } else {
  7027. return std::string(buf, INET6_ADDRSTRLEN);
  7028. }
  7029. }
  7030. }
  7031. }
  7032. }
  7033. }
  7034. return addr_candidate;
  7035. }
  7036. #endif
  7037. inline socket_t
  7038. create_client_socket(const std::string &host, const std::string &ip, int port,
  7039. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  7040. SocketOptions socket_options,
  7041. time_t connection_timeout_sec,
  7042. time_t connection_timeout_usec, time_t read_timeout_sec,
  7043. time_t read_timeout_usec, time_t write_timeout_sec,
  7044. time_t write_timeout_usec, const std::string &intf,
  7045. Error &error, const std::function<bool()> &interrupted) {
  7046. auto sock = create_socket(
  7047. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  7048. std::move(socket_options),
  7049. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  7050. if (!intf.empty()) {
  7051. #ifdef USE_IF2IP
  7052. auto ip_from_if = if2ip(address_family, intf);
  7053. if (ip_from_if.empty()) { ip_from_if = intf; }
  7054. if (!bind_ip_address(sock2, ip_from_if)) {
  7055. error = Error::BindIPAddress;
  7056. return false;
  7057. }
  7058. #endif
  7059. }
  7060. set_nonblocking(sock2, true);
  7061. auto ret =
  7062. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  7063. if (ret < 0) {
  7064. if (is_connection_error()) {
  7065. error = Error::Connection;
  7066. return false;
  7067. }
  7068. error =
  7069. wait_until_socket_is_ready(sock2, connection_timeout_sec,
  7070. connection_timeout_usec, interrupted);
  7071. if (error != Error::Success) {
  7072. if (error == Error::ConnectionTimeout || error == Error::Canceled) {
  7073. quit = true;
  7074. }
  7075. return false;
  7076. }
  7077. }
  7078. set_nonblocking(sock2, false);
  7079. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  7080. read_timeout_usec);
  7081. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  7082. write_timeout_usec);
  7083. error = Error::Success;
  7084. return true;
  7085. },
  7086. connection_timeout_sec); // Pass DNS timeout
  7087. if (sock != INVALID_SOCKET) {
  7088. error = Error::Success;
  7089. } else {
  7090. if (error == Error::Success) { error = Error::Connection; }
  7091. }
  7092. return sock;
  7093. }
  7094. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  7095. socklen_t addr_len, std::string &ip, int &port) {
  7096. if (addr.ss_family == AF_INET) {
  7097. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  7098. } else if (addr.ss_family == AF_INET6) {
  7099. port =
  7100. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  7101. } else {
  7102. return false;
  7103. }
  7104. std::array<char, NI_MAXHOST> ipstr{};
  7105. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  7106. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  7107. 0, NI_NUMERICHOST)) {
  7108. return false;
  7109. }
  7110. ip = ipstr.data();
  7111. return true;
  7112. }
  7113. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  7114. struct sockaddr_storage addr;
  7115. socklen_t addr_len = sizeof(addr);
  7116. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  7117. &addr_len)) {
  7118. get_ip_and_port(addr, addr_len, ip, port);
  7119. }
  7120. }
  7121. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  7122. struct sockaddr_storage addr;
  7123. socklen_t addr_len = sizeof(addr);
  7124. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  7125. &addr_len)) {
  7126. #ifndef _WIN32
  7127. if (addr.ss_family == AF_UNIX) {
  7128. #if defined(__linux__)
  7129. struct ucred ucred;
  7130. socklen_t len = sizeof(ucred);
  7131. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  7132. port = ucred.pid;
  7133. }
  7134. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  7135. pid_t pid;
  7136. socklen_t len = sizeof(pid);
  7137. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  7138. port = pid;
  7139. }
  7140. #endif
  7141. return;
  7142. }
  7143. #endif
  7144. get_ip_and_port(addr, addr_len, ip, port);
  7145. }
  7146. }
  7147. inline std::string
  7148. find_content_type(const std::string &path,
  7149. const std::map<std::string, std::string> &user_data,
  7150. const std::string &default_content_type) {
  7151. // Extensions are matched regardless of case, as web servers do
  7152. auto ext = case_ignore::to_lower(file_extension(path));
  7153. auto it = user_data.find(ext);
  7154. if (it != user_data.end()) { return it->second; }
  7155. static const struct {
  7156. const char *ext;
  7157. const char *type;
  7158. } types[] = {
  7159. {"css", "text/css"},
  7160. {"csv", "text/csv"},
  7161. {"htm", "text/html"},
  7162. {"html", "text/html"},
  7163. {"js", "text/javascript"},
  7164. {"mjs", "text/javascript"},
  7165. {"txt", "text/plain"},
  7166. {"vtt", "text/vtt"},
  7167. {"apng", "image/apng"},
  7168. {"avif", "image/avif"},
  7169. {"bmp", "image/bmp"},
  7170. {"gif", "image/gif"},
  7171. {"png", "image/png"},
  7172. {"svg", "image/svg+xml"},
  7173. {"webp", "image/webp"},
  7174. {"ico", "image/x-icon"},
  7175. {"tif", "image/tiff"},
  7176. {"tiff", "image/tiff"},
  7177. {"jpg", "image/jpeg"},
  7178. {"jpeg", "image/jpeg"},
  7179. {"mp4", "video/mp4"},
  7180. {"mpeg", "video/mpeg"},
  7181. {"webm", "video/webm"},
  7182. {"mp3", "audio/mp3"},
  7183. {"mpga", "audio/mpeg"},
  7184. {"weba", "audio/webm"},
  7185. {"wav", "audio/wave"},
  7186. {"otf", "font/otf"},
  7187. {"ttf", "font/ttf"},
  7188. {"woff", "font/woff"},
  7189. {"woff2", "font/woff2"},
  7190. {"7z", "application/x-7z-compressed"},
  7191. {"atom", "application/atom+xml"},
  7192. {"pdf", "application/pdf"},
  7193. {"json", "application/json"},
  7194. {"rss", "application/rss+xml"},
  7195. {"tar", "application/x-tar"},
  7196. {"xht", "application/xhtml+xml"},
  7197. {"xhtml", "application/xhtml+xml"},
  7198. {"xslt", "application/xslt+xml"},
  7199. {"xml", "application/xml"},
  7200. {"gz", "application/gzip"},
  7201. {"zip", "application/zip"},
  7202. {"wasm", "application/wasm"},
  7203. };
  7204. for (const auto &t : types) {
  7205. if (ext == t.ext) { return t.type; }
  7206. }
  7207. return default_content_type;
  7208. }
  7209. inline std::string
  7210. extract_media_type(const std::string &content_type,
  7211. std::map<std::string, std::string> *params = nullptr) {
  7212. // Extract type/subtype from Content-Type value (RFC 2045)
  7213. // e.g. "application/json; charset=utf-8" -> "application/json"
  7214. auto media_type = content_type;
  7215. auto semicolon_pos = media_type.find(';');
  7216. if (semicolon_pos != std::string::npos) {
  7217. auto param_str = media_type.substr(semicolon_pos + 1);
  7218. media_type = media_type.substr(0, semicolon_pos);
  7219. if (params) {
  7220. // Parse parameters: key=value pairs separated by ';'
  7221. split_unquoted(param_str.data(), param_str.data() + param_str.size(), ';',
  7222. [&](const char *b, const char *e) {
  7223. std::string key;
  7224. std::string val;
  7225. divide_param_pair(b, e, key, val);
  7226. // Parameter names are case-insensitive (RFC 9110
  7227. // §5.6.6)
  7228. if (!key.empty()) {
  7229. params->emplace(case_ignore::to_lower(trim_copy(key)),
  7230. unquote_param(val));
  7231. }
  7232. });
  7233. }
  7234. }
  7235. // Trim whitespace from media type
  7236. return trim_copy(media_type);
  7237. }
  7238. inline bool can_compress_content_type(const std::string &content_type) {
  7239. // Media types are case-insensitive (RFC 9110 §8.3.1)
  7240. auto mime_type = case_ignore::to_lower(extract_media_type(content_type));
  7241. static const char *const compressible[] = {
  7242. "image/svg+xml",
  7243. "application/javascript",
  7244. "application/x-javascript",
  7245. "application/json",
  7246. "application/ld+json",
  7247. "application/xml",
  7248. "application/xhtml+xml",
  7249. "application/rss+xml",
  7250. "application/atom+xml",
  7251. "application/xslt+xml",
  7252. "application/protobuf",
  7253. };
  7254. for (auto type : compressible) {
  7255. if (mime_type == type) { return true; }
  7256. }
  7257. return mime_type != "text/event-stream" && !mime_type.rfind("text/", 0);
  7258. }
  7259. inline bool parse_quality(const char *b, const char *e, std::string &token,
  7260. double &quality) {
  7261. quality = 1.0;
  7262. token.clear();
  7263. // Split on first ';': left = token name, right = parameters
  7264. const char *params_b = nullptr;
  7265. std::size_t params_len = 0;
  7266. divide(
  7267. b, static_cast<std::size_t>(e - b), ';',
  7268. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  7269. auto r = trim(lb, lb + llen, 0, llen);
  7270. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  7271. params_b = rb;
  7272. params_len = rlen;
  7273. });
  7274. if (token.empty()) { return false; }
  7275. if (params_len == 0) { return true; }
  7276. // Scan parameters for q= (stops on first match)
  7277. bool invalid = false;
  7278. split_find(params_b, params_b + params_len, ';',
  7279. (std::numeric_limits<size_t>::max)(),
  7280. [&](const char *pb, const char *pe) -> bool {
  7281. // Match exactly "q=" or "Q=" (not "query=" etc.)
  7282. auto len = static_cast<size_t>(pe - pb);
  7283. if (len < 2) { return false; }
  7284. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  7285. return false;
  7286. }
  7287. // Trim the value portion
  7288. auto r = trim(pb, pe, 2, len);
  7289. if (r.first >= r.second) {
  7290. invalid = true;
  7291. return true;
  7292. }
  7293. double v = 0.0;
  7294. auto res = from_chars(pb + r.first, pb + r.second, v);
  7295. if (res.ec != std::errc{} || res.ptr != pb + r.second ||
  7296. v < 0.0 || v > 1.0) {
  7297. invalid = true;
  7298. return true;
  7299. }
  7300. quality = v;
  7301. return true;
  7302. });
  7303. return !invalid;
  7304. }
  7305. inline EncodingType encoding_type(const Request &req,
  7306. const std::string &content_type) {
  7307. if (!can_compress_content_type(content_type)) { return EncodingType::None; }
  7308. auto s = get_combined_header_value(req.headers, "Accept-Encoding");
  7309. if (s.empty()) { return EncodingType::None; }
  7310. // Single-pass: iterate tokens and track the best supported encoding.
  7311. // Server preference breaks ties (br > gzip > zstd).
  7312. EncodingType best = EncodingType::None;
  7313. double best_q = 0.0; // q=0 means "not acceptable"
  7314. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  7315. auto priority = [](EncodingType t) -> int {
  7316. switch (t) {
  7317. case EncodingType::Brotli: return 0;
  7318. case EncodingType::Gzip: return 1;
  7319. case EncodingType::Zstd: return 2;
  7320. default: return 3;
  7321. }
  7322. };
  7323. std::string name;
  7324. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  7325. double quality = 1.0;
  7326. if (!parse_quality(b, e, name, quality)) { return; }
  7327. if (quality <= 0.0) { return; }
  7328. EncodingType type = EncodingType::None;
  7329. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7330. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  7331. #endif
  7332. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7333. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  7334. type = EncodingType::Gzip;
  7335. }
  7336. #endif
  7337. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7338. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  7339. type = EncodingType::Zstd;
  7340. }
  7341. #endif
  7342. if (type == EncodingType::None) { return; }
  7343. // Higher q-value wins; for equal q, server preference breaks ties
  7344. if (quality > best_q ||
  7345. (quality == best_q && priority(type) < priority(best))) {
  7346. best_q = quality;
  7347. best = type;
  7348. }
  7349. });
  7350. return best;
  7351. }
  7352. // `content_type` is taken separately because a file-backed response has not
  7353. // been given one yet when its coding has to be decided.
  7354. inline EncodingType encoding_type(const Request &req, const Response &res,
  7355. const std::string &content_type) {
  7356. // The response already names a content coding of its own: a handler serving
  7357. // a body it encoded itself (pre-compressed static assets, say), or a mount
  7358. // point whose headers name the coding its files are stored in. Applying one
  7359. // on top of that would double-encode the body and append a second
  7360. // `Content-Encoding` field line.
  7361. if (res.has_header("Content-Encoding")) { return EncodingType::None; }
  7362. return encoding_type(req, content_type);
  7363. }
  7364. inline EncodingType encoding_type(const Request &req, const Response &res) {
  7365. return encoding_type(req, res, res.get_header_value("Content-Type"));
  7366. }
  7367. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  7368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7369. if (type == EncodingType::Gzip) {
  7370. return detail::make_unique<gzip_compressor>();
  7371. }
  7372. #endif
  7373. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7374. if (type == EncodingType::Brotli) {
  7375. return detail::make_unique<brotli_compressor>();
  7376. }
  7377. #endif
  7378. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7379. if (type == EncodingType::Zstd) {
  7380. return detail::make_unique<zstd_compressor>();
  7381. }
  7382. #endif
  7383. (void)type;
  7384. return nullptr;
  7385. }
  7386. inline const char *encoding_name(EncodingType type) {
  7387. switch (type) {
  7388. case EncodingType::Gzip: return "gzip";
  7389. case EncodingType::Brotli: return "br";
  7390. case EncodingType::Zstd: return "zstd";
  7391. default: return "";
  7392. }
  7393. }
  7394. inline bool nocompressor::compress(const char *data, size_t data_length,
  7395. bool /*last*/, Callback callback) {
  7396. if (!data_length) { return true; }
  7397. return callback(data, data_length);
  7398. }
  7399. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7400. inline gzip_compressor::gzip_compressor() {
  7401. std::memset(&strm_, 0, sizeof(strm_));
  7402. strm_.zalloc = Z_NULL;
  7403. strm_.zfree = Z_NULL;
  7404. strm_.opaque = Z_NULL;
  7405. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  7406. Z_DEFAULT_STRATEGY) == Z_OK;
  7407. }
  7408. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  7409. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  7410. bool last, Callback callback) {
  7411. assert(is_valid_);
  7412. do {
  7413. constexpr size_t max_avail_in =
  7414. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  7415. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  7416. (std::min)(data_length, max_avail_in));
  7417. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  7418. data_length -= strm_.avail_in;
  7419. data += strm_.avail_in;
  7420. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  7421. auto ret = Z_OK;
  7422. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7423. do {
  7424. strm_.avail_out = static_cast<uInt>(buff.size());
  7425. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  7426. ret = deflate(&strm_, flush);
  7427. if (ret == Z_STREAM_ERROR) { return false; }
  7428. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  7429. return false;
  7430. }
  7431. } while (strm_.avail_out == 0);
  7432. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  7433. (flush == Z_NO_FLUSH && ret == Z_OK));
  7434. assert(strm_.avail_in == 0);
  7435. } while (data_length > 0);
  7436. return true;
  7437. }
  7438. inline gzip_decompressor::gzip_decompressor() {
  7439. std::memset(&strm_, 0, sizeof(strm_));
  7440. strm_.zalloc = Z_NULL;
  7441. strm_.zfree = Z_NULL;
  7442. strm_.opaque = Z_NULL;
  7443. // 15 is the value of wbits, which should be at the maximum possible value
  7444. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  7445. // that the stream type should be automatically detected either gzip or
  7446. // deflate.
  7447. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  7448. }
  7449. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  7450. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  7451. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  7452. Callback callback) {
  7453. assert(is_valid_);
  7454. auto ret = Z_OK;
  7455. do {
  7456. constexpr size_t max_avail_in =
  7457. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  7458. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  7459. (std::min)(data_length, max_avail_in));
  7460. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  7461. data_length -= strm_.avail_in;
  7462. data += strm_.avail_in;
  7463. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7464. while (strm_.avail_in > 0 && ret == Z_OK) {
  7465. strm_.avail_out = static_cast<uInt>(buff.size());
  7466. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  7467. ret = inflate(&strm_, Z_NO_FLUSH);
  7468. assert(ret != Z_STREAM_ERROR);
  7469. switch (ret) {
  7470. case Z_NEED_DICT:
  7471. case Z_DATA_ERROR:
  7472. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  7473. }
  7474. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  7475. return false;
  7476. }
  7477. }
  7478. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  7479. } while (data_length > 0);
  7480. return true;
  7481. }
  7482. #endif
  7483. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7484. inline brotli_compressor::brotli_compressor() {
  7485. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  7486. }
  7487. inline brotli_compressor::~brotli_compressor() {
  7488. BrotliEncoderDestroyInstance(state_);
  7489. }
  7490. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  7491. bool last, Callback callback) {
  7492. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7493. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  7494. auto available_in = data_length;
  7495. auto next_in = reinterpret_cast<const uint8_t *>(data);
  7496. for (;;) {
  7497. if (last) {
  7498. if (BrotliEncoderIsFinished(state_)) { break; }
  7499. } else {
  7500. if (!available_in) { break; }
  7501. }
  7502. auto available_out = buff.size();
  7503. auto next_out = buff.data();
  7504. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  7505. &available_out, &next_out, nullptr)) {
  7506. return false;
  7507. }
  7508. auto output_bytes = buff.size() - available_out;
  7509. if (output_bytes) {
  7510. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  7511. }
  7512. }
  7513. return true;
  7514. }
  7515. inline brotli_decompressor::brotli_decompressor() {
  7516. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  7517. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  7518. : BROTLI_DECODER_RESULT_ERROR;
  7519. }
  7520. inline brotli_decompressor::~brotli_decompressor() {
  7521. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  7522. }
  7523. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  7524. inline bool brotli_decompressor::decompress(const char *data,
  7525. size_t data_length,
  7526. Callback callback) {
  7527. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  7528. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  7529. return 0;
  7530. }
  7531. auto next_in = reinterpret_cast<const uint8_t *>(data);
  7532. size_t avail_in = data_length;
  7533. size_t total_out;
  7534. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  7535. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7536. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  7537. char *next_out = buff.data();
  7538. size_t avail_out = buff.size();
  7539. decoder_r = BrotliDecoderDecompressStream(
  7540. decoder_s, &avail_in, &next_in, &avail_out,
  7541. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  7542. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  7543. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  7544. }
  7545. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  7546. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  7547. }
  7548. #endif
  7549. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7550. inline zstd_compressor::zstd_compressor() {
  7551. ctx_ = ZSTD_createCCtx();
  7552. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  7553. }
  7554. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  7555. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  7556. bool last, Callback callback) {
  7557. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7558. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  7559. ZSTD_inBuffer input = {data, data_length, 0};
  7560. bool finished;
  7561. do {
  7562. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  7563. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  7564. if (ZSTD_isError(remaining)) { return false; }
  7565. if (!callback(buff.data(), output.pos)) { return false; }
  7566. finished = last ? (remaining == 0) : (input.pos == input.size);
  7567. } while (!finished);
  7568. return true;
  7569. }
  7570. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  7571. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  7572. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  7573. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  7574. Callback callback) {
  7575. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7576. ZSTD_inBuffer input = {data, data_length, 0};
  7577. while (input.pos < input.size) {
  7578. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  7579. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  7580. if (ZSTD_isError(remaining)) { return false; }
  7581. if (!callback(buff.data(), output.pos)) { return false; }
  7582. }
  7583. return true;
  7584. }
  7585. #endif
  7586. // Content codings are case-insensitive (RFC 9110 8.4.1). Matching them
  7587. // case-sensitively would make a response labeled e.g. "GZIP" look like an
  7588. // unknown coding, and its payload would be handed back still compressed.
  7589. inline bool is_zlib_encoding(const std::string &encoding) {
  7590. return case_ignore::equal(encoding, "gzip") ||
  7591. case_ignore::equal(encoding, "deflate");
  7592. }
  7593. inline bool is_brotli_encoding(const std::string &encoding) {
  7594. return case_ignore::equal(encoding, "br");
  7595. }
  7596. inline bool is_zstd_encoding(const std::string &encoding) {
  7597. return case_ignore::equal(encoding, "zstd");
  7598. }
  7599. // Returns true if the content coding is one cpp-httplib is able to decompress
  7600. // when the corresponding support is compiled in.
  7601. inline bool is_known_content_encoding(const std::string &encoding) {
  7602. return is_zlib_encoding(encoding) || is_brotli_encoding(encoding) ||
  7603. is_zstd_encoding(encoding);
  7604. }
  7605. inline std::unique_ptr<decompressor>
  7606. create_decompressor(const std::string &encoding) {
  7607. std::unique_ptr<decompressor> decompressor;
  7608. if (is_zlib_encoding(encoding)) {
  7609. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7610. decompressor = detail::make_unique<gzip_decompressor>();
  7611. #endif
  7612. } else if (is_brotli_encoding(encoding)) {
  7613. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7614. decompressor = detail::make_unique<brotli_decompressor>();
  7615. #endif
  7616. } else if (is_zstd_encoding(encoding)) {
  7617. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7618. decompressor = detail::make_unique<zstd_decompressor>();
  7619. #endif
  7620. }
  7621. return decompressor;
  7622. }
  7623. // Returns the best available compressor and its Content-Encoding name.
  7624. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  7625. inline std::pair<std::unique_ptr<compressor>, const char *>
  7626. create_compressor() {
  7627. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7628. return {detail::make_unique<brotli_compressor>(), "br"};
  7629. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7630. return {detail::make_unique<gzip_compressor>(), "gzip"};
  7631. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7632. return {detail::make_unique<zstd_compressor>(), "zstd"};
  7633. #else
  7634. return {nullptr, nullptr};
  7635. #endif
  7636. }
  7637. inline bool is_prohibited_header_name(const std::string &name) {
  7638. // Field names are case-insensitive (RFC 9110 §5.1)
  7639. return case_ignore::equal(name, "REMOTE_ADDR") ||
  7640. case_ignore::equal(name, "REMOTE_PORT") ||
  7641. case_ignore::equal(name, "LOCAL_ADDR") ||
  7642. case_ignore::equal(name, "LOCAL_PORT");
  7643. }
  7644. inline bool has_header(const Headers &headers, const std::string &key) {
  7645. if (is_prohibited_header_name(key)) { return false; }
  7646. return headers.find(key) != headers.end();
  7647. }
  7648. inline const char *get_header_value(const Headers &headers,
  7649. const std::string &key, const char *def,
  7650. size_t id) {
  7651. if (is_prohibited_header_name(key)) {
  7652. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7653. std::string msg = "Prohibited header name '" + key + "' is specified.";
  7654. throw std::invalid_argument(msg);
  7655. #else
  7656. return "";
  7657. #endif
  7658. }
  7659. auto rng = headers.equal_range(key);
  7660. auto it = bounded_next(rng.first, id, rng.second);
  7661. if (it != rng.second) { return it->second.c_str(); }
  7662. return def;
  7663. }
  7664. inline size_t get_header_value_count(const Headers &headers,
  7665. const std::string &key) {
  7666. return headers.count(key);
  7667. }
  7668. // RFC 9110 Section 5.2 and 5.3: a field that is defined as a comma-separated
  7669. // list may be sent as several field lines, and the combined field value is
  7670. // those values joined by commas in the order they were received. Callers that
  7671. // parse such a list must work on the combined value; reading only the first
  7672. // occurrence silently drops whatever the later field lines carry.
  7673. inline std::string get_combined_header_value(const Headers &headers,
  7674. const std::string &key) {
  7675. std::string combined;
  7676. auto rng = headers.equal_range(key);
  7677. for (auto it = rng.first; it != rng.second; ++it) {
  7678. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  7679. // elements, so an empty field line must not contribute a bare comma to the
  7680. // combined value.
  7681. if (it->second.empty()) { continue; }
  7682. if (!combined.empty()) { combined += ", "; }
  7683. combined += it->second;
  7684. }
  7685. return combined;
  7686. }
  7687. inline bool has_header_token(const Headers &headers, const std::string &key,
  7688. const std::string &token) {
  7689. // RFC 9110 7.6.1: a comma-separated token list field such as Connection may
  7690. // carry several tokens, and RFC 9110 5.3 lets that list be split across
  7691. // several lines. Match complete tokens rather than searching the raw value,
  7692. // so that a value such as "notupgrade" is not read as the token "upgrade".
  7693. auto rng = headers.equal_range(key);
  7694. for (auto it = rng.first; it != rng.second; ++it) {
  7695. const auto &value = it->second;
  7696. if (split_find(value.data(), value.data() + value.size(), ',',
  7697. [&](const char *b, const char *e) {
  7698. return case_ignore::equal(std::string(b, e), token);
  7699. })) {
  7700. return true;
  7701. }
  7702. }
  7703. return false;
  7704. }
  7705. template <typename Map>
  7706. inline typename Map::mapped_type
  7707. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  7708. auto rng = m.equal_range(key);
  7709. auto it = bounded_next(rng.first, id, rng.second);
  7710. if (it != rng.second) { return it->second; }
  7711. return typename Map::mapped_type();
  7712. }
  7713. inline void set_header(Headers &headers, const std::string &key,
  7714. const std::string &val) {
  7715. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  7716. }
  7717. // Drops the fields set_header() would refuse, from headers an application can
  7718. // fill directly: CR/LF in one would split the message.
  7719. inline void erase_invalid_fields(Headers &headers) {
  7720. for (auto it = headers.begin(); it != headers.end();) {
  7721. if (fields::is_field_valid(it->first, it->second)) {
  7722. ++it;
  7723. } else {
  7724. it = headers.erase(it);
  7725. }
  7726. }
  7727. }
  7728. inline bool read_headers(Stream &strm, Headers &headers) {
  7729. const auto bufsiz = 2048;
  7730. char buf[bufsiz];
  7731. stream_line_reader line_reader(strm, buf, bufsiz);
  7732. size_t header_count = 0;
  7733. for (;;) {
  7734. if (!line_reader.getline()) { return false; }
  7735. // Check if the line ends with CRLF.
  7736. auto line_terminator_len = 2;
  7737. if (line_reader.end_with_crlf()) {
  7738. // Blank line indicates end of headers.
  7739. if (line_reader.size() == 2) { break; }
  7740. } else {
  7741. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  7742. // Blank line indicates end of headers.
  7743. if (line_reader.size() == 1) { break; }
  7744. line_terminator_len = 1;
  7745. #else
  7746. continue; // Skip invalid line.
  7747. #endif
  7748. }
  7749. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  7750. // Check header count limit
  7751. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  7752. // Exclude line terminator
  7753. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  7754. if (!parse_header(line_reader.ptr(), end,
  7755. [&](const std::string &key, const std::string &val) {
  7756. headers.emplace(key, val);
  7757. })) {
  7758. return false;
  7759. }
  7760. header_count++;
  7761. }
  7762. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  7763. // headers that have different values to prevent request smuggling.
  7764. auto cl_range = headers.equal_range("Content-Length");
  7765. if (cl_range.first != cl_range.second) {
  7766. const auto &first_val = cl_range.first->second;
  7767. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  7768. if (it->second != first_val) { return false; }
  7769. }
  7770. }
  7771. return true;
  7772. }
  7773. // Parsed by hand: std::regex_match recurses once per character of the reason
  7774. // phrase, which a server can make as long as a whole line.
  7775. inline bool parse_status_line(const char *line, std::string &version,
  7776. int &status, std::string &reason) {
  7777. if (std::strncmp(line, "HTTP/1.", 7) != 0 ||
  7778. (line[7] != '0' && line[7] != '1') || line[8] != ' ' ||
  7779. !is_ascii_digit(line[9]) || !is_ascii_digit(line[10]) ||
  7780. !is_ascii_digit(line[11])) {
  7781. return false;
  7782. }
  7783. auto p = line + 12;
  7784. auto reason_begin = p;
  7785. if (*p == ' ') {
  7786. reason_begin = ++p;
  7787. p += std::strcspn(p, "\r\n");
  7788. }
  7789. auto reason_end = p;
  7790. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  7791. if (*p == '\r') { p++; }
  7792. #else
  7793. if (*p++ != '\r') { return false; }
  7794. #endif
  7795. if (*p++ != '\n' || *p != '\0') { return false; }
  7796. version.assign(line, 8);
  7797. status = (line[9] - '0') * 100 + (line[10] - '0') * 10 + (line[11] - '0');
  7798. reason.assign(reason_begin, reason_end);
  7799. return true;
  7800. }
  7801. // Everything WebSocketClient::connect() reports about the upgrade exchange.
  7802. // status stays -1 until a status line is parsed, mirroring stream::Result.
  7803. struct WebSocketUpgradeResponse {
  7804. Error error = Error::Success;
  7805. int status = -1;
  7806. Headers headers;
  7807. std::string selected_subprotocol;
  7808. };
  7809. // Reads a response's status line and headers, leaving any body unread. An
  7810. // unparsable status line is no stream error; it just leaves `status` as is.
  7811. inline bool read_response_head(Stream &strm, int &status, Headers &headers) {
  7812. const auto bufsiz = 2048;
  7813. char buf[bufsiz];
  7814. stream_line_reader line_reader(strm, buf, bufsiz);
  7815. if (!line_reader.getline()) { return false; }
  7816. std::string version;
  7817. std::string reason;
  7818. if (!parse_status_line(line_reader.ptr(), version, status, reason)) {
  7819. return true;
  7820. }
  7821. return read_headers(strm, headers);
  7822. }
  7823. inline bool
  7824. read_websocket_upgrade_response(Stream &strm,
  7825. const std::string &expected_accept,
  7826. const std::string &offered_subprotocols,
  7827. WebSocketUpgradeResponse &upgrade) {
  7828. // The headers of a rejection are kept so the caller can see why the server
  7829. // refused the upgrade.
  7830. if (!read_response_head(strm, upgrade.status, upgrade.headers)) {
  7831. upgrade.error = Error::Read;
  7832. return false;
  7833. }
  7834. const auto &headers = upgrade.headers;
  7835. if (upgrade.status != StatusCode::SwitchingProtocol_101) {
  7836. upgrade.error = Error::WebSocketHandshake;
  7837. return false;
  7838. }
  7839. // Verify Upgrade: websocket (a comma-separated list, matched per token)
  7840. if (!has_header_token(headers, "Upgrade", "websocket")) {
  7841. upgrade.error = Error::WebSocketHandshake;
  7842. return false;
  7843. }
  7844. // Verify Connection: Upgrade
  7845. if (!has_header_token(headers, "Connection", "upgrade")) {
  7846. upgrade.error = Error::WebSocketHandshake;
  7847. return false;
  7848. }
  7849. // Verify Sec-WebSocket-Accept header value
  7850. auto it = headers.find("Sec-WebSocket-Accept");
  7851. if (it == headers.end() || it->second != expected_accept) {
  7852. upgrade.error = Error::WebSocketHandshake;
  7853. return false;
  7854. }
  7855. // Extract negotiated subprotocol
  7856. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  7857. if (proto_it != headers.end()) {
  7858. upgrade.selected_subprotocol = proto_it->second;
  7859. }
  7860. // Verify the subprotocol is one the client offered (RFC 6455 4.1)
  7861. if (!upgrade.selected_subprotocol.empty()) {
  7862. auto was_offered = false;
  7863. split(offered_subprotocols.data(),
  7864. offered_subprotocols.data() + offered_subprotocols.size(), ',',
  7865. [&](const char *b, const char *e) {
  7866. if (std::string(b, e) == upgrade.selected_subprotocol) {
  7867. was_offered = true;
  7868. }
  7869. });
  7870. if (!was_offered) {
  7871. upgrade.error = Error::WebSocketHandshake;
  7872. return false;
  7873. }
  7874. }
  7875. return true;
  7876. }
  7877. enum class ReadContentResult {
  7878. Success, // Successfully read the content
  7879. PayloadTooLarge, // The content exceeds the specified payload limit
  7880. Error // An error occurred while reading the content
  7881. };
  7882. inline ReadContentResult read_content_with_length(
  7883. Stream &strm, size_t len, DownloadProgress progress,
  7884. ContentReceiverWithProgress out,
  7885. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  7886. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7887. detail::BodyReader br;
  7888. br.stream = &strm;
  7889. br.has_content_length = true;
  7890. br.content_length = len;
  7891. br.payload_max_length = payload_max_length;
  7892. br.chunked = false;
  7893. br.bytes_read = 0;
  7894. br.last_error = Error::Success;
  7895. size_t r = 0;
  7896. while (r < len) {
  7897. auto read_len = static_cast<size_t>(len - r);
  7898. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  7899. auto n = detail::read_body_content(&strm, br, buf, to_read);
  7900. if (n <= 0) {
  7901. // Check if it was a payload size error
  7902. if (br.last_error == Error::ExceedMaxPayloadSize) {
  7903. return ReadContentResult::PayloadTooLarge;
  7904. }
  7905. return ReadContentResult::Error;
  7906. }
  7907. if (!out(buf, static_cast<size_t>(n), r, len)) {
  7908. return ReadContentResult::Error;
  7909. }
  7910. r += static_cast<size_t>(n);
  7911. if (progress) {
  7912. if (!progress(r, len)) { return ReadContentResult::Error; }
  7913. }
  7914. }
  7915. return ReadContentResult::Success;
  7916. }
  7917. inline ReadContentResult
  7918. read_content_without_length(Stream &strm, size_t payload_max_length,
  7919. ContentReceiverWithProgress out) {
  7920. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7921. size_t r = 0;
  7922. for (;;) {
  7923. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  7924. if (n == 0) { return ReadContentResult::Success; }
  7925. if (n < 0) { return ReadContentResult::Error; }
  7926. // Check if adding this data would exceed the payload limit
  7927. if (payload_max_length > 0 &&
  7928. (r > payload_max_length ||
  7929. payload_max_length - r < static_cast<size_t>(n))) {
  7930. return ReadContentResult::PayloadTooLarge;
  7931. }
  7932. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  7933. return ReadContentResult::Error;
  7934. }
  7935. r += static_cast<size_t>(n);
  7936. }
  7937. return ReadContentResult::Success;
  7938. }
  7939. template <typename T>
  7940. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  7941. size_t payload_max_length,
  7942. ContentReceiverWithProgress out) {
  7943. detail::ChunkedDecoder dec(strm);
  7944. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7945. size_t total_len = 0;
  7946. for (;;) {
  7947. size_t chunk_offset = 0;
  7948. size_t chunk_total = 0;
  7949. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  7950. if (n < 0) { return ReadContentResult::Error; }
  7951. if (n == 0) {
  7952. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  7953. return ReadContentResult::Error;
  7954. }
  7955. return ReadContentResult::Success;
  7956. }
  7957. if (payload_max_length > 0 &&
  7958. (total_len > payload_max_length ||
  7959. payload_max_length - total_len < static_cast<size_t>(n))) {
  7960. return ReadContentResult::PayloadTooLarge;
  7961. }
  7962. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  7963. return ReadContentResult::Error;
  7964. }
  7965. total_len += static_cast<size_t>(n);
  7966. }
  7967. }
  7968. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  7969. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  7970. // is the final transfer coding. A single field value may list several
  7971. // codings ("gzip, chunked"), and RFC 9110 5.3 lets that list be split across
  7972. // several Transfer-Encoding lines, which combine into one comma-separated
  7973. // list in the order the lines were received. Headers preserves that order,
  7974. // so the final coding is the last token of the last line. Match it
  7975. // case-insensitively rather than comparing the whole value against
  7976. // "chunked".
  7977. //
  7978. // Security: reading a chunked message as unframed leaves its body in the
  7979. // socket, where a keep-alive connection parses it as a smuggled request.
  7980. // Server::process_request() answers 400 and closes when the final coding is
  7981. // not chunked, so a request whose framing cannot be determined never
  7982. // reaches the "no body" path.
  7983. auto rng = headers.equal_range("Transfer-Encoding");
  7984. if (rng.first == rng.second) { return false; }
  7985. // Cleared per line, so a trailing line carrying no coding at all leaves the
  7986. // combined list ending in nothing rather than inheriting the line before it.
  7987. std::string last_coding;
  7988. for (auto it = rng.first; it != rng.second; ++it) {
  7989. const auto &value = it->second;
  7990. last_coding.clear();
  7991. split(value.data(), value.data() + value.size(), ',',
  7992. [&](const char *b, const char *e) { last_coding.assign(b, e); });
  7993. }
  7994. return case_ignore::equal(last_coding, "chunked");
  7995. }
  7996. // RFC 9112 6.1: a message framed by Transfer-Encoding next to a Content-Length,
  7997. // or in HTTP/1.0, leaves the connection unfit to carry another one.
  7998. template <typename T> inline bool has_faulty_transfer_encoding(const T &msg) {
  7999. return msg.has_header("Transfer-Encoding") &&
  8000. (msg.has_header("Content-Length") || msg.version == "HTTP/1.0");
  8001. }
  8002. inline bool has_conflicting_content_length(const Headers &headers) {
  8003. // RFC 9112 §6.3: a message carrying both Transfer-Encoding and a non-zero
  8004. // Content-Length is framed ambiguously. The body readers here delimit it by
  8005. // the transfer coding and drop Content-Length, while an intermediary may do
  8006. // the reverse, so the two disagree on where the body ends and a reused
  8007. // connection is desynchronised (request/response smuggling). Content-Length:
  8008. // 0 is tolerated for compatibility with existing peers.
  8009. return has_header(headers, "Transfer-Encoding") &&
  8010. get_header_value_u64(headers, "Content-Length", 0, 0) > 0;
  8011. }
  8012. template <typename T, typename U>
  8013. bool prepare_content_receiver(T &x, int &status,
  8014. ContentReceiverWithProgress receiver,
  8015. bool decompress, size_t payload_max_length,
  8016. bool &exceed_payload_max_length, U callback) {
  8017. if (decompress) {
  8018. auto encoding = get_combined_header_value(x.headers, "Content-Encoding");
  8019. std::unique_ptr<decompressor> decompressor;
  8020. if (!encoding.empty()) {
  8021. // A coding we know about but were not built with is an error. An
  8022. // unrecognized coding (including "identity") is left alone and the
  8023. // payload is passed through as-is, since some servers misuse the header,
  8024. // e.g. by sending a character set such as "Content-Encoding: UTF-8".
  8025. decompressor = detail::create_decompressor(encoding);
  8026. if (!decompressor && detail::is_known_content_encoding(encoding)) {
  8027. status = StatusCode::UnsupportedMediaType_415;
  8028. return false;
  8029. }
  8030. }
  8031. if (decompressor) {
  8032. if (decompressor->is_valid()) {
  8033. size_t decompressed_size = 0;
  8034. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  8035. size_t off, size_t len) {
  8036. return decompressor->decompress(
  8037. buf, n, [&](const char *buf2, size_t n2) {
  8038. // Guard against zip-bomb: check
  8039. // decompressed size against limit.
  8040. if (payload_max_length > 0 &&
  8041. (decompressed_size >= payload_max_length ||
  8042. n2 > payload_max_length - decompressed_size)) {
  8043. exceed_payload_max_length = true;
  8044. return false;
  8045. }
  8046. decompressed_size += n2;
  8047. return receiver(buf2, n2, off, len);
  8048. });
  8049. };
  8050. return callback(std::move(out));
  8051. } else {
  8052. status = StatusCode::InternalServerError_500;
  8053. return false;
  8054. }
  8055. }
  8056. }
  8057. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  8058. size_t len) {
  8059. return receiver(buf, n, off, len);
  8060. };
  8061. return callback(std::move(out));
  8062. }
  8063. template <typename T>
  8064. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  8065. DownloadProgress progress,
  8066. ContentReceiverWithProgress receiver, bool decompress) {
  8067. bool exceed_payload_max_length = false;
  8068. return prepare_content_receiver(
  8069. x, status, std::move(receiver), decompress, payload_max_length,
  8070. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  8071. auto ret = true;
  8072. // Note: exceed_payload_max_length may also be set by the decompressor
  8073. // wrapper in prepare_content_receiver when the decompressed payload
  8074. // size exceeds the limit.
  8075. if (is_chunked_transfer_encoding(x.headers)) {
  8076. auto result = read_content_chunked(strm, x, payload_max_length, out);
  8077. if (result == ReadContentResult::Success) {
  8078. ret = true;
  8079. } else if (result == ReadContentResult::PayloadTooLarge) {
  8080. exceed_payload_max_length = true;
  8081. ret = false;
  8082. } else {
  8083. ret = false;
  8084. }
  8085. } else if (!has_header(x.headers, "Content-Length")) {
  8086. auto result =
  8087. read_content_without_length(strm, payload_max_length, out);
  8088. if (result == ReadContentResult::Success) {
  8089. ret = true;
  8090. } else if (result == ReadContentResult::PayloadTooLarge) {
  8091. exceed_payload_max_length = true;
  8092. ret = false;
  8093. } else {
  8094. ret = false;
  8095. }
  8096. } else {
  8097. auto is_invalid_value = false;
  8098. auto len = get_header_value_u64(x.headers, "Content-Length",
  8099. (std::numeric_limits<size_t>::max)(),
  8100. 0, is_invalid_value);
  8101. if (is_invalid_value) {
  8102. ret = false;
  8103. } else if (len > 0) {
  8104. auto result = read_content_with_length(
  8105. strm, len, std::move(progress), out, payload_max_length);
  8106. ret = (result == ReadContentResult::Success);
  8107. if (result == ReadContentResult::PayloadTooLarge) {
  8108. exceed_payload_max_length = true;
  8109. }
  8110. }
  8111. }
  8112. if (!ret) {
  8113. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  8114. : StatusCode::BadRequest_400;
  8115. }
  8116. return ret;
  8117. });
  8118. }
  8119. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  8120. const std::string &path) {
  8121. // Neither the method nor the request target may carry CR/LF, SP or other
  8122. // control octets; otherwise a value smuggled into either splits the request
  8123. // line and injects headers or a whole request.
  8124. if (!fields::is_token(method)) { return -1; }
  8125. if (!fields::is_request_target(path)) { return -1; }
  8126. std::string s = method;
  8127. s += ' ';
  8128. s += path;
  8129. s += " HTTP/1.1\r\n";
  8130. return strm.write(s.data(), s.size());
  8131. }
  8132. inline ssize_t write_response_line(Stream &strm, int status) {
  8133. std::string s = "HTTP/1.1 ";
  8134. s += std::to_string(status);
  8135. s += ' ';
  8136. s += httplib::status_message(status);
  8137. s += "\r\n";
  8138. return strm.write(s.data(), s.size());
  8139. }
  8140. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  8141. ssize_t write_len = 0;
  8142. for (const auto &x : headers) {
  8143. std::string s;
  8144. s = x.first;
  8145. s += ": ";
  8146. s += x.second;
  8147. s += "\r\n";
  8148. auto len = strm.write(s.data(), s.size());
  8149. if (len < 0) { return len; }
  8150. write_len += len;
  8151. }
  8152. auto len = strm.write("\r\n");
  8153. if (len < 0) { return len; }
  8154. write_len += len;
  8155. return write_len;
  8156. }
  8157. inline bool write_data(Stream &strm, const char *d, size_t l) {
  8158. size_t offset = 0;
  8159. while (offset < l) {
  8160. auto length = strm.write(d + offset, l - offset);
  8161. if (length < 0) { return false; }
  8162. offset += static_cast<size_t>(length);
  8163. }
  8164. return true;
  8165. }
  8166. template <typename T>
  8167. inline bool write_content_with_progress(Stream &strm,
  8168. const ContentProvider &content_provider,
  8169. size_t offset, size_t length,
  8170. T is_shutting_down,
  8171. const UploadProgress &upload_progress,
  8172. Error &error) {
  8173. size_t end_offset = offset + length;
  8174. size_t start_offset = offset;
  8175. auto ok = true;
  8176. auto finished = false;
  8177. DataSink data_sink;
  8178. data_sink.write = [&](const char *d, size_t l) -> bool {
  8179. if (ok) {
  8180. // Bytes past `length` would follow the framed body, where the peer reads
  8181. // them as the next message. Write only what fits and fail the rest.
  8182. if (l > end_offset - offset) {
  8183. l = end_offset - offset;
  8184. ok = false;
  8185. }
  8186. if (write_data(strm, d, l)) {
  8187. offset += l;
  8188. if (upload_progress && length > 0) {
  8189. size_t current_written = offset - start_offset;
  8190. if (!upload_progress(current_written, length)) {
  8191. ok = false;
  8192. return false;
  8193. }
  8194. }
  8195. } else {
  8196. ok = false;
  8197. }
  8198. }
  8199. return ok;
  8200. };
  8201. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  8202. // The body is framed by `length`, so a provider that reports itself done
  8203. // early has truncated it. Record that and let the short-body check below
  8204. // fail the write, rather than calling the provider again forever.
  8205. data_sink.done = [&]() { finished = true; };
  8206. while (offset < end_offset && !finished && !is_shutting_down()) {
  8207. auto last_offset = offset;
  8208. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  8209. error = Error::Write;
  8210. return false;
  8211. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  8212. error = Error::Canceled;
  8213. return false;
  8214. } else if (!ok) {
  8215. error = Error::Write;
  8216. return false;
  8217. }
  8218. // A provider that reports success without writing anything and without
  8219. // reporting itself done gets handed the same offset and length again on
  8220. // the next pass, so it would spin here for as long as the peer stays
  8221. // connected. Treat making no progress as a short body, like done() early.
  8222. if (!finished && offset == last_offset) {
  8223. error = Error::Write;
  8224. return false;
  8225. }
  8226. }
  8227. if (offset < end_offset) { // done() called early, or is_shutting_down()
  8228. error = Error::Write;
  8229. return false;
  8230. }
  8231. error = Error::Success;
  8232. return true;
  8233. }
  8234. template <typename T>
  8235. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  8236. size_t offset, size_t length, T is_shutting_down,
  8237. Error &error) {
  8238. return write_content_with_progress<T>(strm, content_provider, offset, length,
  8239. is_shutting_down, nullptr, error);
  8240. }
  8241. template <typename T>
  8242. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  8243. size_t offset, size_t length,
  8244. const T &is_shutting_down) {
  8245. auto error = Error::Success;
  8246. return write_content(strm, content_provider, offset, length, is_shutting_down,
  8247. error);
  8248. }
  8249. template <typename T>
  8250. inline bool
  8251. write_content_without_length(Stream &strm,
  8252. const ContentProvider &content_provider,
  8253. const T &is_shutting_down) {
  8254. size_t offset = 0;
  8255. auto data_available = true;
  8256. auto ok = true;
  8257. DataSink data_sink;
  8258. data_sink.write = [&](const char *d, size_t l) -> bool {
  8259. if (ok) {
  8260. offset += l;
  8261. if (!write_data(strm, d, l)) { ok = false; }
  8262. }
  8263. return ok;
  8264. };
  8265. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  8266. data_sink.done = [&](void) { data_available = false; };
  8267. while (data_available && !is_shutting_down()) {
  8268. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  8269. return false;
  8270. } else if (!content_provider(offset, 0, data_sink)) {
  8271. return false;
  8272. } else if (!ok) {
  8273. return false;
  8274. }
  8275. }
  8276. return !data_available; // true only if done() was called, false if shutting
  8277. // down
  8278. }
  8279. // Runs a known-length content provider to completion and compresses what it
  8280. // writes into `out`, chunk by chunk, without holding the identity form.
  8281. inline bool compress_content_provider(const ContentProvider &content_provider,
  8282. size_t length, compressor &cmp,
  8283. std::string &out) {
  8284. size_t offset = 0;
  8285. auto ok = true;
  8286. auto finished = false;
  8287. DataSink data_sink;
  8288. auto append = [&](const char *data, size_t data_len) {
  8289. out.append(data, data_len);
  8290. return true;
  8291. };
  8292. data_sink.write = [&](const char *d, size_t l) -> bool {
  8293. if (!ok) { return false; }
  8294. offset += l;
  8295. if (l > 0 && !cmp.compress(d, l, false, append)) { ok = false; }
  8296. return ok;
  8297. };
  8298. // The body is framed by `length`, so a provider that reports itself done
  8299. // early has truncated it; the short-body check below turns that into a
  8300. // failure rather than calling the provider again forever.
  8301. data_sink.done = [&]() { finished = true; };
  8302. while (offset < length && !finished) {
  8303. auto prev_offset = offset;
  8304. if (!content_provider(offset, length - offset, data_sink) || !ok) {
  8305. return false;
  8306. }
  8307. // No Stream to block on here, so a provider that keeps returning true
  8308. // without writing would spin. Treat a pass that made no progress as a
  8309. // failure.
  8310. if (offset == prev_offset) { return false; }
  8311. }
  8312. if (offset != length) { return false; }
  8313. return cmp.compress(nullptr, 0, true, append);
  8314. }
  8315. // Serves `m` as the response body. `set_content_provider()` clears the coding
  8316. // and the file flag, so recording them has to come after; keeping all of it
  8317. // here means a third file-serving path cannot get that order wrong.
  8318. inline void set_file_content_provider(Response &res,
  8319. const std::shared_ptr<mmap> &m,
  8320. const std::string &content_type,
  8321. EncodingType encoding) {
  8322. // One read and one write move up to this much of the file at a time.
  8323. auto buf = std::make_shared<std::vector<char>>(
  8324. (std::min)(m->size(), size_t(256 * 1024)));
  8325. res.set_content_provider(
  8326. m->size(), content_type,
  8327. [m, buf](size_t offset, size_t length, DataSink &sink) -> bool {
  8328. // Never read past the file, which ends the response early if it has
  8329. // shrunk since it was opened.
  8330. auto n = m->read(offset, buf->data(), (std::min)(length, buf->size()));
  8331. if (n == 0) { return false; }
  8332. sink.write(buf->data(), n);
  8333. return true;
  8334. });
  8335. res.is_file_content_provider_ = true;
  8336. res.content_coding_ = encoding;
  8337. }
  8338. template <typename T, typename U>
  8339. inline bool
  8340. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  8341. const T &is_shutting_down, U &compressor, Error &error) {
  8342. size_t offset = 0;
  8343. auto data_available = true;
  8344. auto ok = true;
  8345. DataSink data_sink;
  8346. data_sink.write = [&](const char *d, size_t l) -> bool {
  8347. // Only done()/done_with_trailer() end a chunked body. A pass with nothing
  8348. // to hand over is ordinary (an empty buffer popped off a queue), and a
  8349. // zero-length chunk is the terminator, so it must not be emitted here.
  8350. if (ok && l > 0) {
  8351. offset += l;
  8352. std::string payload;
  8353. if (compressor.compress(d, l, false,
  8354. [&](const char *data, size_t data_len) {
  8355. payload.append(data, data_len);
  8356. return true;
  8357. })) {
  8358. if (!payload.empty()) {
  8359. // Emit chunked response header and footer for each chunk
  8360. auto chunk =
  8361. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  8362. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  8363. }
  8364. } else {
  8365. ok = false;
  8366. }
  8367. }
  8368. return ok;
  8369. };
  8370. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  8371. auto done_with_trailer = [&](const Headers *trailer) {
  8372. if (!ok) { return; }
  8373. data_available = false;
  8374. std::string payload;
  8375. if (!compressor.compress(nullptr, 0, true,
  8376. [&](const char *data, size_t data_len) {
  8377. payload.append(data, data_len);
  8378. return true;
  8379. })) {
  8380. ok = false;
  8381. return;
  8382. }
  8383. if (!payload.empty()) {
  8384. // Emit chunked response header and footer for each chunk
  8385. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  8386. if (!write_data(strm, chunk.data(), chunk.size())) {
  8387. ok = false;
  8388. return;
  8389. }
  8390. }
  8391. constexpr const char done_marker[] = "0\r\n";
  8392. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  8393. // Trailer
  8394. if (trailer) {
  8395. for (const auto &kv : *trailer) {
  8396. // Skip fields with invalid names or values to prevent response
  8397. // splitting via CR/LF injection, matching set_header().
  8398. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  8399. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  8400. if (!write_data(strm, field_line.data(), field_line.size())) {
  8401. ok = false;
  8402. }
  8403. }
  8404. }
  8405. constexpr const char crlf[] = "\r\n";
  8406. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  8407. };
  8408. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  8409. data_sink.done_with_trailer = [&](const Headers &trailer) {
  8410. done_with_trailer(&trailer);
  8411. };
  8412. while (data_available && !is_shutting_down()) {
  8413. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  8414. error = Error::Write;
  8415. return false;
  8416. } else if (!content_provider(offset, 0, data_sink)) {
  8417. error = Error::Canceled;
  8418. return false;
  8419. } else if (!ok) {
  8420. error = Error::Write;
  8421. return false;
  8422. }
  8423. }
  8424. if (data_available) { // exited due to is_shutting_down(), not done()
  8425. error = Error::Write;
  8426. return false;
  8427. }
  8428. error = Error::Success;
  8429. return true;
  8430. }
  8431. template <typename T, typename U>
  8432. inline bool write_content_chunked(Stream &strm,
  8433. const ContentProvider &content_provider,
  8434. const T &is_shutting_down, U &compressor) {
  8435. auto error = Error::Success;
  8436. return write_content_chunked(strm, content_provider, is_shutting_down,
  8437. compressor, error);
  8438. }
  8439. template <typename T>
  8440. inline bool redirect(T &cli, Request &req, Response &res,
  8441. const std::string &path, const std::string &location,
  8442. Error &error) {
  8443. Request new_req = req;
  8444. new_req.path = path;
  8445. new_req.params.clear();
  8446. new_req.redirect_count_ -= 1;
  8447. if (res.status == StatusCode::SeeOther_303 &&
  8448. (req.method != "GET" && req.method != "HEAD")) {
  8449. new_req.method = "GET";
  8450. new_req.body.clear();
  8451. new_req.headers.clear();
  8452. new_req.content_length_ = 0;
  8453. new_req.content_provider_ = nullptr;
  8454. new_req.is_chunked_content_provider_ = false;
  8455. }
  8456. Response new_res;
  8457. auto ret = cli.send(new_req, new_res, error);
  8458. if (ret) {
  8459. req = std::move(new_req);
  8460. res = std::move(new_res);
  8461. if (res.location.empty()) { res.location = location; }
  8462. }
  8463. return ret;
  8464. }
  8465. inline std::string params_to_query_str(const Params &params) {
  8466. std::string query;
  8467. for (auto it = params.begin(); it != params.end(); ++it) {
  8468. if (it != params.begin()) { query += '&'; }
  8469. query += encode_query_component(it->first);
  8470. query += '=';
  8471. query += encode_query_component(it->second);
  8472. }
  8473. return query;
  8474. }
  8475. // Splits one "key=value" span of a query string at its first '='. A span with
  8476. // no '=' at all lands entirely in key, leaving val empty, which is how a bare
  8477. // "?flag" keeps its name.
  8478. inline void divide_query_pair(const char *b, const char *e, std::string &key,
  8479. std::string &val) {
  8480. divide(b, static_cast<std::size_t>(e - b), '=',
  8481. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  8482. std::size_t rhs_size) {
  8483. key.assign(lhs_data, lhs_size);
  8484. val.assign(rhs_data, rhs_size);
  8485. });
  8486. }
  8487. inline void parse_query_text(const char *data, std::size_t size,
  8488. Params &params) {
  8489. std::set<std::string> cache;
  8490. split(data, data + size, '&', [&](const char *b, const char *e) {
  8491. std::string kv(b, e);
  8492. if (cache.find(kv) != cache.end()) { return; }
  8493. cache.insert(std::move(kv));
  8494. std::string key;
  8495. std::string val;
  8496. divide_query_pair(b, e, key, val);
  8497. if (!key.empty()) {
  8498. params.emplace(decode_query_component(key), decode_query_component(val));
  8499. }
  8500. });
  8501. }
  8502. inline void parse_query_text(const std::string &s, Params &params) {
  8503. parse_query_text(s.data(), s.size(), params);
  8504. }
  8505. // Normalize a query string by decoding and re-encoding each key/value pair
  8506. // while preserving the original parameter order. This avoids double-encoding
  8507. // and ensures consistent encoding. It works on the raw string rather than
  8508. // parsing into Params and re-serializing, because that round trip cannot
  8509. // reproduce the input: params_to_query_str() always emits '=', so a bare
  8510. // "flag" would come back as "flag=", and parse_query_text() drops exactly
  8511. // duplicated pairs.
  8512. inline std::string normalize_query_string(const std::string &query) {
  8513. std::string result;
  8514. split(query.data(), query.data() + query.size(), '&',
  8515. [&](const char *b, const char *e) {
  8516. std::string key;
  8517. std::string val;
  8518. divide_query_pair(b, e, key, val);
  8519. if (!key.empty()) {
  8520. auto dec_key = decode_query_component(key);
  8521. auto dec_val = decode_query_component(val);
  8522. if (!result.empty()) { result += '&'; }
  8523. result += encode_query_component(dec_key);
  8524. if (!val.empty() || std::find(b, e, '=') != e) {
  8525. result += '=';
  8526. result += encode_query_component(dec_val);
  8527. }
  8528. }
  8529. });
  8530. return result;
  8531. }
  8532. // The query of a client's path: what follows '?', up to the fragment.
  8533. inline std::string query_of(const std::string &path) {
  8534. auto fragment_pos = path.find('#');
  8535. auto query_pos = path.find('?');
  8536. return query_pos < fragment_pos
  8537. ? path.substr(query_pos + 1, fragment_pos - query_pos - 1)
  8538. : std::string();
  8539. }
  8540. // Build the request target that goes on the wire from a caller-supplied path.
  8541. // Shared by the buffered send path and the streaming API so that both put the
  8542. // same bytes in the request line for the same input.
  8543. inline std::string encode_request_target(const std::string &uri,
  8544. bool path_encode) {
  8545. // The fragment stays with the client (RFC 9110 §7.1).
  8546. auto target = uri.substr(0, uri.find('#'));
  8547. // `substr(0, npos)` yields the whole string, which is what the no-query
  8548. // case needs.
  8549. auto query_pos = target.find('?');
  8550. auto path_part = target.substr(0, query_pos);
  8551. std::string query_part;
  8552. if (query_pos != std::string::npos) {
  8553. query_part = target.substr(query_pos + 1);
  8554. }
  8555. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  8556. if (!query_part.empty()) {
  8557. // When path encoding is disabled the caller has supplied an already-encoded
  8558. // target and expects the exact bytes to be sent on the wire, so skip
  8559. // normalization for the query too. Normalizing would decode-then-re-encode
  8560. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  8561. // which a strict RFC 3986 server decodes back as `+`, not a space).
  8562. if (path_encode) {
  8563. auto normalized = normalize_query_string(query_part);
  8564. if (!normalized.empty()) {
  8565. result += '?';
  8566. result += normalized;
  8567. }
  8568. } else {
  8569. result += '?';
  8570. result += query_part;
  8571. }
  8572. }
  8573. return result;
  8574. }
  8575. inline bool parse_multipart_boundary(const std::string &content_type,
  8576. std::string &boundary) {
  8577. std::map<std::string, std::string> params;
  8578. extract_media_type(content_type, &params);
  8579. auto it = params.find("boundary");
  8580. if (it == params.end()) { return false; }
  8581. boundary = it->second;
  8582. // RFC 2046 5.1.1 caps a boundary at 70 characters. The parser scans the body
  8583. // for "--" + boundary, so a body crafted to repeat that delimiter's leading
  8584. // bytes costs a nearly full comparison at nearly every position: the
  8585. // boundary's length multiplies the worst-case cost of scanning a body.
  8586. return !boundary.empty() && boundary.size() <= 70;
  8587. }
  8588. inline void parse_disposition_params(const std::string &s, Params &params) {
  8589. std::set<std::string> cache;
  8590. split_unquoted(
  8591. s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  8592. std::string kv(b, e);
  8593. if (cache.find(kv) != cache.end()) { return; }
  8594. cache.insert(kv);
  8595. std::string key;
  8596. std::string val;
  8597. divide_param_pair(b, e, key, val);
  8598. // Parameter names are case-insensitive (RFC 2045 §5.1)
  8599. if (!key.empty()) {
  8600. params.emplace(case_ignore::to_lower(trim_double_quotes_copy(key)),
  8601. unquote_param(val));
  8602. }
  8603. });
  8604. }
  8605. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8606. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  8607. #else
  8608. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  8609. #endif
  8610. auto is_valid = [](const std::string &str) {
  8611. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  8612. };
  8613. if (s.size() > 7 && case_ignore::equal(s.substr(0, 6), "bytes=")) {
  8614. const auto pos = static_cast<size_t>(6);
  8615. const auto len = static_cast<size_t>(s.size() - 6);
  8616. auto all_valid_ranges = true;
  8617. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  8618. if (!all_valid_ranges) { return; }
  8619. const auto it = std::find(b, e, '-');
  8620. if (it == e) {
  8621. all_valid_ranges = false;
  8622. return;
  8623. }
  8624. const auto lhs = std::string(b, it);
  8625. const auto rhs = std::string(it + 1, e);
  8626. if (!is_valid(lhs) || !is_valid(rhs)) {
  8627. all_valid_ranges = false;
  8628. return;
  8629. }
  8630. ssize_t first = -1;
  8631. if (!lhs.empty()) {
  8632. // Reject an overflowing first-byte-pos; treating it as absent (-1)
  8633. // would turn the range into a suffix range.
  8634. auto res =
  8635. detail::from_chars(lhs.data(), lhs.data() + lhs.size(), first);
  8636. if (res.ec != std::errc{}) {
  8637. all_valid_ranges = false;
  8638. return;
  8639. }
  8640. }
  8641. ssize_t last = -1;
  8642. if (!rhs.empty()) {
  8643. // An overflowing last-byte-pos is past any content length, so keeping
  8644. // -1 ("remainder", RFC 9110 14.1.2) is correct here.
  8645. ssize_t v;
  8646. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  8647. if (res.ec == std::errc{}) { last = v; }
  8648. }
  8649. if ((first == -1 && last == -1) ||
  8650. (first != -1 && last != -1 && first > last)) {
  8651. all_valid_ranges = false;
  8652. return;
  8653. }
  8654. ranges.emplace_back(first, last);
  8655. });
  8656. return all_valid_ranges && !ranges.empty();
  8657. }
  8658. return false;
  8659. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8660. }
  8661. #else
  8662. } catch (...) { return false; }
  8663. #endif
  8664. // Removes each quoted-string, honoring a quoted-pair (RFC 9110 Section 5.6.4)
  8665. inline std::string remove_quoted_strings(const std::string &s) {
  8666. std::string out;
  8667. auto in_quotes = false;
  8668. for (size_t i = 0; i < s.size(); i++) {
  8669. if (s[i] == '"') {
  8670. in_quotes = !in_quotes;
  8671. } else if (!in_quotes) {
  8672. out += s[i];
  8673. } else if (s[i] == '\\') {
  8674. i++;
  8675. }
  8676. }
  8677. return out;
  8678. }
  8679. inline bool parse_accept_header(const std::string &s,
  8680. std::vector<std::string> &content_types) {
  8681. // Parameter values are not used here, so a quoted-string is dropped rather
  8682. // than parsed: a ',' or ';' inside one must not be read as a delimiter.
  8683. if (s.find('"') != std::string::npos) {
  8684. return parse_accept_header(remove_quoted_strings(s), content_types);
  8685. }
  8686. content_types.clear();
  8687. // Empty string is considered valid (no preference)
  8688. if (s.empty()) { return true; }
  8689. struct AcceptEntry {
  8690. std::string media_type;
  8691. double quality;
  8692. int order;
  8693. };
  8694. std::vector<AcceptEntry> entries;
  8695. int order = 0;
  8696. bool has_invalid_entry = false;
  8697. // Split by comma and parse each entry. RFC 9110 Section 5.6.1.2: a recipient
  8698. // has to parse and ignore empty list elements, so a leading, trailing or
  8699. // doubled comma must not turn a legal Accept value into 400 Bad Request.
  8700. // split() skips them, and the header length limit bounds how many a sender
  8701. // can send, so ignoring all of them cannot be used as a denial-of-service
  8702. // vector.
  8703. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  8704. std::string entry(b, e);
  8705. entry = trim_copy(entry);
  8706. AcceptEntry accept_entry;
  8707. accept_entry.order = order++;
  8708. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  8709. accept_entry.media_type, accept_entry.quality)) {
  8710. has_invalid_entry = true;
  8711. return;
  8712. }
  8713. // Remove additional parameters from media type
  8714. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  8715. // Basic validation of media type format
  8716. if (accept_entry.media_type.empty()) {
  8717. has_invalid_entry = true;
  8718. return;
  8719. }
  8720. // Check for basic media type format (should contain '/' or be '*')
  8721. if (accept_entry.media_type != "*" &&
  8722. accept_entry.media_type.find('/') == std::string::npos) {
  8723. has_invalid_entry = true;
  8724. return;
  8725. }
  8726. entries.push_back(std::move(accept_entry));
  8727. });
  8728. // Return false if any invalid entry was found
  8729. if (has_invalid_entry) { return false; }
  8730. // Sort by quality (descending), then by original order (ascending)
  8731. std::sort(entries.begin(), entries.end(),
  8732. [](const AcceptEntry &a, const AcceptEntry &b) {
  8733. if (a.quality != b.quality) {
  8734. return a.quality > b.quality; // Higher quality first
  8735. }
  8736. return a.order < b.order; // Earlier order first for same quality
  8737. });
  8738. // Extract sorted media types
  8739. content_types.reserve(entries.size());
  8740. for (auto &entry : entries) {
  8741. content_types.push_back(std::move(entry.media_type));
  8742. }
  8743. return true;
  8744. }
  8745. class FormDataParser {
  8746. public:
  8747. FormDataParser() = default;
  8748. void set_boundary(std::string &&boundary) {
  8749. boundary_ = std::move(boundary);
  8750. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  8751. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  8752. }
  8753. bool is_valid() const { return is_valid_; }
  8754. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  8755. const ContentReceiver &content_callback) {
  8756. // Once the close delimiter has been seen the rest of the body is epilogue
  8757. // to be discarded (RFC 2046). Drop it without buffering so a large epilogue
  8758. // spread across reads is not copied in only to be erased right away.
  8759. if (state_ == 5) { return true; }
  8760. buf_append(buf, n);
  8761. while (buf_size() > 0) {
  8762. switch (state_) {
  8763. case 0: { // Initial boundary
  8764. auto pos = buf_find(dash_boundary_crlf_);
  8765. if (pos == buf_size()) {
  8766. // Not found yet: keep only a possible partial boundary at the tail so
  8767. // that a body which never contains the boundary cannot grow the
  8768. // buffer (and get rescanned from the start) without bound.
  8769. auto keep = dash_boundary_crlf_.size() - 1;
  8770. if (buf_size() > keep) { buf_erase(buf_size() - keep); }
  8771. return true;
  8772. }
  8773. buf_erase(pos + dash_boundary_crlf_.size());
  8774. state_ = 1;
  8775. break;
  8776. }
  8777. case 1: { // New entry
  8778. clear_file_info();
  8779. header_searched_ = 0;
  8780. state_ = 2;
  8781. break;
  8782. }
  8783. case 2: { // Headers
  8784. // Resume where the last call stopped looking, so that a line arriving
  8785. // a few bytes at a time is not searched from its start each time.
  8786. auto pos = buf_find(crlf_, header_searched_);
  8787. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  8788. while (pos < buf_size()) {
  8789. // Empty line
  8790. if (pos == 0) {
  8791. if (!header_callback(file_)) {
  8792. is_valid_ = false;
  8793. return false;
  8794. }
  8795. buf_erase(crlf_.size());
  8796. state_ = 3;
  8797. break;
  8798. }
  8799. // Check header count limit
  8800. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  8801. is_valid_ = false;
  8802. return false;
  8803. }
  8804. header_count_++;
  8805. const auto header = buf_head(pos);
  8806. if (!parse_header(header.data(), header.data() + header.size(),
  8807. [&](const std::string &, const std::string &) {})) {
  8808. is_valid_ = false;
  8809. return false;
  8810. }
  8811. // Parse and emplace space trimmed headers into a map
  8812. if (!parse_header(
  8813. header.data(), header.data() + header.size(),
  8814. [&](const std::string &key, const std::string &val) {
  8815. file_.headers.emplace(key, val);
  8816. })) {
  8817. is_valid_ = false;
  8818. return false;
  8819. }
  8820. constexpr const char header_content_type[] = "Content-Type:";
  8821. if (start_with_case_ignore(header, header_content_type)) {
  8822. file_.content_type =
  8823. trim_copy(header.substr(str_len(header_content_type)));
  8824. } else {
  8825. std::string disposition_params;
  8826. if (parse_content_disposition(header, disposition_params)) {
  8827. Params params;
  8828. parse_disposition_params(disposition_params, params);
  8829. auto it = params.find("name");
  8830. if (it != params.end()) {
  8831. file_.name = it->second;
  8832. } else {
  8833. is_valid_ = false;
  8834. return false;
  8835. }
  8836. it = params.find("filename");
  8837. if (it != params.end()) { file_.filename = it->second; }
  8838. it = params.find("filename*");
  8839. if (it != params.end()) {
  8840. // RFC 5987: only UTF-8 encoding is allowed
  8841. const auto &val = it->second;
  8842. constexpr const char utf8_prefix[] = "UTF-8''";
  8843. constexpr size_t prefix_len = str_len(utf8_prefix);
  8844. if (val.size() > prefix_len &&
  8845. start_with_case_ignore(val, utf8_prefix)) {
  8846. file_.filename = decode_path_component(
  8847. val.substr(prefix_len)); // override...
  8848. } else {
  8849. is_valid_ = false;
  8850. return false;
  8851. }
  8852. }
  8853. }
  8854. }
  8855. buf_erase(pos + crlf_.size());
  8856. pos = buf_find(crlf_);
  8857. }
  8858. if (state_ != 3) {
  8859. // The CR of the CRLF may be the last byte so far.
  8860. header_searched_ = buf_size() > 0 ? buf_size() - 1 : 0;
  8861. return true;
  8862. }
  8863. break;
  8864. }
  8865. case 3: { // Body
  8866. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  8867. auto pos = buf_find(crlf_dash_boundary_);
  8868. if (pos < buf_size()) {
  8869. if (!content_callback(buf_data(), pos)) {
  8870. is_valid_ = false;
  8871. return false;
  8872. }
  8873. buf_erase(pos + crlf_dash_boundary_.size());
  8874. state_ = 4;
  8875. } else {
  8876. auto len = buf_size() - crlf_dash_boundary_.size();
  8877. if (len > 0) {
  8878. if (!content_callback(buf_data(), len)) {
  8879. is_valid_ = false;
  8880. return false;
  8881. }
  8882. buf_erase(len);
  8883. }
  8884. return true;
  8885. }
  8886. break;
  8887. }
  8888. case 4: { // Boundary
  8889. if (crlf_.size() > buf_size()) { return true; }
  8890. if (buf_start_with(crlf_)) {
  8891. buf_erase(crlf_.size());
  8892. state_ = 1;
  8893. } else if (buf_start_with(dash_)) {
  8894. buf_erase(dash_.size());
  8895. is_valid_ = true;
  8896. state_ = 5;
  8897. } else {
  8898. // Only CRLF (another part follows) and "--" (close-delimiter) are
  8899. // accepted after a boundary; RFC 2046 allows transport-padding in
  8900. // between, but this parser has never supported it. Either way the
  8901. // body is already destined to be rejected, so fail now instead of
  8902. // buffering the rest of it. Both are two bytes, so the check above
  8903. // already guarantees enough buffered data to decide.
  8904. is_valid_ = false;
  8905. return false;
  8906. }
  8907. break;
  8908. }
  8909. case 5: { // Epilogue
  8910. buf_erase(buf_size());
  8911. break;
  8912. }
  8913. }
  8914. }
  8915. return true;
  8916. }
  8917. private:
  8918. void clear_file_info() {
  8919. file_.name.clear();
  8920. file_.filename.clear();
  8921. file_.content_type.clear();
  8922. file_.headers.clear();
  8923. header_count_ = 0;
  8924. }
  8925. bool start_with_case_ignore(const std::string &a, const char *b,
  8926. size_t offset = 0) const {
  8927. const auto b_len = strlen(b);
  8928. if (a.size() < offset + b_len) { return false; }
  8929. for (size_t i = 0; i < b_len; i++) {
  8930. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  8931. return false;
  8932. }
  8933. }
  8934. return true;
  8935. }
  8936. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  8937. // Returns true if header matches, with the params portion in `params_out`.
  8938. bool parse_content_disposition(const std::string &header,
  8939. std::string &params_out) const {
  8940. constexpr const char prefix[] = "Content-Disposition:";
  8941. constexpr size_t prefix_len = str_len(prefix);
  8942. if (!start_with_case_ignore(header, prefix)) { return false; }
  8943. // Skip whitespace after "Content-Disposition:"
  8944. auto pos = prefix_len;
  8945. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  8946. pos++;
  8947. }
  8948. // Match "form-data;" (case-insensitive)
  8949. constexpr const char form_data[] = "form-data;";
  8950. constexpr size_t form_data_len = str_len(form_data);
  8951. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  8952. pos += form_data_len;
  8953. // Skip whitespace after "form-data;"
  8954. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  8955. pos++;
  8956. }
  8957. params_out = header.substr(pos);
  8958. return true;
  8959. }
  8960. const std::string dash_ = "--";
  8961. const std::string crlf_ = "\r\n";
  8962. std::string boundary_;
  8963. std::string dash_boundary_crlf_;
  8964. std::string crlf_dash_boundary_;
  8965. size_t state_ = 0;
  8966. bool is_valid_ = false;
  8967. FormData file_;
  8968. size_t header_count_ = 0;
  8969. size_t header_searched_ = 0;
  8970. // Buffer
  8971. bool start_with(const std::string &a, size_t spos, size_t epos,
  8972. const std::string &b) const {
  8973. if (epos - spos < b.size()) { return false; }
  8974. for (size_t i = 0; i < b.size(); i++) {
  8975. if (a[i + spos] != b[i]) { return false; }
  8976. }
  8977. return true;
  8978. }
  8979. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  8980. const char *buf_data() const { return &buf_[buf_spos_]; }
  8981. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  8982. bool buf_start_with(const std::string &s) const {
  8983. return start_with(buf_, buf_spos_, buf_epos_, s);
  8984. }
  8985. size_t buf_find(const std::string &s, size_t from = 0) const {
  8986. auto c = s.front();
  8987. size_t off = buf_spos_ + from;
  8988. while (off < buf_epos_) {
  8989. auto pos = off;
  8990. while (true) {
  8991. if (pos == buf_epos_) { return buf_size(); }
  8992. if (buf_[pos] == c) { break; }
  8993. pos++;
  8994. }
  8995. auto remaining_size = buf_epos_ - pos;
  8996. if (s.size() > remaining_size) { return buf_size(); }
  8997. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  8998. off = pos + 1;
  8999. }
  9000. return buf_size();
  9001. }
  9002. void buf_append(const char *data, size_t n) {
  9003. auto remaining_size = buf_size();
  9004. if (remaining_size > 0 && buf_spos_ > 0) {
  9005. for (size_t i = 0; i < remaining_size; i++) {
  9006. buf_[i] = buf_[buf_spos_ + i];
  9007. }
  9008. }
  9009. buf_spos_ = 0;
  9010. buf_epos_ = remaining_size;
  9011. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  9012. for (size_t i = 0; i < n; i++) {
  9013. buf_[buf_epos_ + i] = data[i];
  9014. }
  9015. buf_epos_ += n;
  9016. }
  9017. void buf_erase(size_t size) { buf_spos_ += size; }
  9018. std::string buf_;
  9019. size_t buf_spos_ = 0;
  9020. size_t buf_epos_ = 0;
  9021. };
  9022. inline std::string random_string(size_t length) {
  9023. constexpr const char data[] =
  9024. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  9025. std::string result(length, '\0');
  9026. fill_random_bytes(reinterpret_cast<unsigned char *>(&result[0]), length);
  9027. for (auto &c : result) {
  9028. c = data[static_cast<unsigned char>(c) % (sizeof(data) - 1)];
  9029. }
  9030. return result;
  9031. }
  9032. inline std::string make_multipart_data_boundary() {
  9033. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  9034. }
  9035. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  9036. auto valid = true;
  9037. for (size_t i = 0; i < boundary.size(); i++) {
  9038. auto c = boundary[i];
  9039. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  9040. valid = false;
  9041. break;
  9042. }
  9043. }
  9044. return valid;
  9045. }
  9046. // Escape a multipart field name/filename following the WHATWG HTML standard
  9047. // ("escape a multipart form-data name"): '"' -> %22, CR -> %0D, LF -> %0A.
  9048. // As the value is a quoted-string, '\' -> '\\' too, which browsers leave out.
  9049. // With quoted = false, only CR and LF are escaped; this is for header values
  9050. // outside a quoted-string (e.g. Content-Type), where '"' and '\' are legal.
  9051. inline std::string escape_multipart_field(const std::string &s,
  9052. bool quoted = true) {
  9053. std::string result;
  9054. result.reserve(s.size());
  9055. for (auto c : s) {
  9056. switch (c) {
  9057. case '"':
  9058. if (quoted) {
  9059. result += "%22";
  9060. } else {
  9061. result += c;
  9062. }
  9063. break;
  9064. case '\\':
  9065. // A lone backslash would escape the character after it (RFC 9110
  9066. // 5.6.4).
  9067. if (quoted) { result += '\\'; }
  9068. result += c;
  9069. break;
  9070. case '\r': result += "%0D"; break;
  9071. case '\n': result += "%0A"; break;
  9072. default: result += c; break;
  9073. }
  9074. }
  9075. return result;
  9076. }
  9077. template <typename T>
  9078. inline std::string
  9079. serialize_multipart_formdata_item_begin(const T &item,
  9080. const std::string &boundary) {
  9081. std::string body = "--" + boundary + "\r\n";
  9082. body += "Content-Disposition: form-data; name=\"" +
  9083. escape_multipart_field(item.name) + "\"";
  9084. if (!item.filename.empty()) {
  9085. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  9086. }
  9087. body += "\r\n";
  9088. if (!item.content_type.empty()) {
  9089. body +=
  9090. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  9091. "\r\n";
  9092. }
  9093. body += "\r\n";
  9094. return body;
  9095. }
  9096. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  9097. inline std::string
  9098. serialize_multipart_formdata_finish(const std::string &boundary) {
  9099. return "--" + boundary + "--\r\n";
  9100. }
  9101. inline std::string
  9102. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  9103. return "multipart/form-data; boundary=" + boundary;
  9104. }
  9105. inline std::string
  9106. serialize_multipart_formdata(const UploadFormDataItems &items,
  9107. const std::string &boundary, bool finish = true) {
  9108. std::string body;
  9109. for (const auto &item : items) {
  9110. body += serialize_multipart_formdata_item_begin(item, boundary);
  9111. body += item.content + serialize_multipart_formdata_item_end();
  9112. }
  9113. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  9114. return body;
  9115. }
  9116. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  9117. const std::string &boundary) {
  9118. size_t total = 0;
  9119. for (const auto &item : items) {
  9120. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  9121. total += item.content.size();
  9122. total += serialize_multipart_formdata_item_end().size();
  9123. }
  9124. total += serialize_multipart_formdata_finish(boundary).size();
  9125. return total;
  9126. }
  9127. struct MultipartSegment {
  9128. const char *data;
  9129. size_t size;
  9130. };
  9131. // NOTE: items must outlive the returned ContentProvider
  9132. // (safe for synchronous use inside Post/Put/Patch)
  9133. inline ContentProvider
  9134. make_multipart_content_provider(const UploadFormDataItems &items,
  9135. const std::string &boundary) {
  9136. // Own the per-item header strings and the finish string
  9137. std::vector<std::string> owned;
  9138. owned.reserve(items.size() + 1);
  9139. for (const auto &item : items)
  9140. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  9141. owned.push_back(serialize_multipart_formdata_finish(boundary));
  9142. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  9143. std::vector<MultipartSegment> segs;
  9144. segs.reserve(items.size() * 3 + 1);
  9145. static const char crlf[] = "\r\n";
  9146. for (size_t i = 0; i < items.size(); i++) {
  9147. segs.push_back({owned[i].data(), owned[i].size()});
  9148. segs.push_back({items[i].content.data(), items[i].content.size()});
  9149. segs.push_back({crlf, 2});
  9150. }
  9151. segs.push_back({owned.back().data(), owned.back().size()});
  9152. struct MultipartState {
  9153. std::vector<std::string> owned;
  9154. std::vector<MultipartSegment> segs;
  9155. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  9156. };
  9157. auto state = std::make_shared<MultipartState>();
  9158. state->owned = std::move(owned);
  9159. // `segs` holds raw pointers into owned strings; std::string move preserves
  9160. // the data pointer, so these pointers remain valid after the move above.
  9161. state->segs = std::move(segs);
  9162. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  9163. // Buffer multiple small segments into fewer, larger writes to avoid
  9164. // excessive TCP packets when there are many form data items (#2410)
  9165. auto &buf = state->buf;
  9166. auto buf_size = buf.size();
  9167. size_t buf_len = 0;
  9168. size_t remaining = length;
  9169. // Find the first segment containing 'offset'
  9170. size_t pos = 0;
  9171. size_t seg_idx = 0;
  9172. for (; seg_idx < state->segs.size(); seg_idx++) {
  9173. const auto &seg = state->segs[seg_idx];
  9174. if (seg.size > 0 && offset - pos < seg.size) { break; }
  9175. pos += seg.size;
  9176. }
  9177. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  9178. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  9179. const auto &seg = state->segs[seg_idx];
  9180. size_t available = seg.size - seg_offset;
  9181. size_t to_copy = (std::min)(available, remaining);
  9182. const char *src = seg.data + seg_offset;
  9183. seg_offset = 0; // only the first segment has a non-zero offset
  9184. while (to_copy > 0) {
  9185. size_t space = buf_size - buf_len;
  9186. size_t chunk = (std::min)(to_copy, space);
  9187. std::memcpy(buf.data() + buf_len, src, chunk);
  9188. buf_len += chunk;
  9189. src += chunk;
  9190. to_copy -= chunk;
  9191. remaining -= chunk;
  9192. if (buf_len == buf_size) {
  9193. if (!sink.write(buf.data(), buf_len)) { return false; }
  9194. buf_len = 0;
  9195. }
  9196. }
  9197. }
  9198. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  9199. return true;
  9200. };
  9201. }
  9202. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  9203. if (ranges.size() <= 1) return;
  9204. // Sort ranges by start position
  9205. std::sort(ranges.begin(), ranges.end(),
  9206. [](const Range &a, const Range &b) { return a.first < b.first; });
  9207. Ranges coalesced;
  9208. coalesced.reserve(ranges.size());
  9209. for (auto &r : ranges) {
  9210. auto first_pos = r.first;
  9211. auto last_pos = r.second;
  9212. // Handle special cases like in range_error
  9213. if (first_pos == -1 && last_pos == -1) {
  9214. first_pos = 0;
  9215. last_pos = static_cast<ssize_t>(content_length);
  9216. }
  9217. if (first_pos == -1) {
  9218. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  9219. last_pos = static_cast<ssize_t>(content_length) - 1;
  9220. }
  9221. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  9222. last_pos = static_cast<ssize_t>(content_length) - 1;
  9223. }
  9224. // Skip invalid ranges
  9225. if (!(0 <= first_pos && first_pos <= last_pos &&
  9226. last_pos < static_cast<ssize_t>(content_length))) {
  9227. continue;
  9228. }
  9229. // Coalesce with previous range if overlapping or adjacent (but not
  9230. // identical)
  9231. if (!coalesced.empty()) {
  9232. auto &prev = coalesced.back();
  9233. // Check if current range overlaps or is adjacent to previous range
  9234. // but don't coalesce identical ranges (allow duplicates)
  9235. if (first_pos <= prev.second + 1 &&
  9236. !(first_pos == prev.first && last_pos == prev.second)) {
  9237. // Extend the previous range
  9238. prev.second = (std::max)(prev.second, last_pos);
  9239. continue;
  9240. }
  9241. }
  9242. // Add new range
  9243. coalesced.emplace_back(first_pos, last_pos);
  9244. }
  9245. ranges = std::move(coalesced);
  9246. }
  9247. inline bool range_error(Request &req, Response &res) {
  9248. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  9249. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  9250. req.ranges.clear();
  9251. if (res.status == StatusCode::PartialContent_206) {
  9252. res.status = StatusCode::OK_200;
  9253. }
  9254. return false;
  9255. }
  9256. ssize_t content_len = static_cast<ssize_t>(
  9257. res.content_length_ ? res.content_length_ : res.body.size());
  9258. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  9259. size_t overwrapping_count = 0;
  9260. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  9261. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  9262. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  9263. // Too many ranges
  9264. if (CPPHTTPLIB_RANGE_MAX_COUNT > 0 &&
  9265. req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) {
  9266. return true;
  9267. }
  9268. for (auto &r : req.ranges) {
  9269. auto &first_pos = r.first;
  9270. auto &last_pos = r.second;
  9271. if (first_pos == -1 && last_pos == -1) {
  9272. first_pos = 0;
  9273. last_pos = content_len;
  9274. }
  9275. // RFC 9110 14.1.2: a suffix-length longer than the representation
  9276. // selects the entire representation.
  9277. if (first_pos == -1) {
  9278. first_pos = (std::max)(static_cast<ssize_t>(0), content_len - last_pos);
  9279. last_pos = content_len - 1;
  9280. }
  9281. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  9282. // A client can limit the number of bytes requested without knowing the
  9283. // size of the selected representation. If the last-pos value is absent,
  9284. // or if the value is greater than or equal to the current length of the
  9285. // representation data, the byte range is interpreted as the remainder of
  9286. // the representation (i.e., the server replaces the value of last-pos
  9287. // with a value that is one less than the current length of the selected
  9288. // representation).
  9289. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  9290. if (last_pos == -1 || last_pos >= content_len) {
  9291. last_pos = content_len - 1;
  9292. }
  9293. // Range must be within content length
  9294. if (!(0 <= first_pos && first_pos <= last_pos &&
  9295. last_pos <= content_len - 1)) {
  9296. return true;
  9297. }
  9298. // Request must not have more than two overlapping ranges
  9299. for (const auto &processed_range : processed_ranges) {
  9300. if (!(last_pos < processed_range.first ||
  9301. first_pos > processed_range.second)) {
  9302. overwrapping_count++;
  9303. if (overwrapping_count > 2) { return true; }
  9304. break; // Only count once per range
  9305. }
  9306. }
  9307. processed_ranges.emplace_back(first_pos, last_pos);
  9308. }
  9309. // After validation, coalesce overlapping ranges as per RFC 9110
  9310. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  9311. }
  9312. return false;
  9313. }
  9314. inline std::pair<size_t, size_t>
  9315. get_range_offset_and_length(Range r, size_t content_length) {
  9316. assert(r.first != -1 && r.second != -1);
  9317. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  9318. assert(r.first <= r.second &&
  9319. r.second < static_cast<ssize_t>(content_length));
  9320. (void)(content_length);
  9321. return std::make_pair(static_cast<size_t>(r.first),
  9322. static_cast<size_t>(r.second - r.first) + 1);
  9323. }
  9324. inline std::string make_content_range_header_field(
  9325. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  9326. auto st = offset_and_length.first;
  9327. auto ed = st + offset_and_length.second - 1;
  9328. std::string field = "bytes ";
  9329. field += std::to_string(st);
  9330. field += '-';
  9331. field += std::to_string(ed);
  9332. field += '/';
  9333. field += std::to_string(content_length);
  9334. return field;
  9335. }
  9336. template <typename SToken, typename CToken, typename Content>
  9337. bool process_multipart_ranges_data(const Request &req,
  9338. const std::string &boundary,
  9339. const std::string &content_type,
  9340. size_t content_length, SToken stoken,
  9341. CToken ctoken, Content content) {
  9342. for (size_t i = 0; i < req.ranges.size(); i++) {
  9343. ctoken("--");
  9344. stoken(boundary);
  9345. ctoken("\r\n");
  9346. if (!content_type.empty()) {
  9347. ctoken("Content-Type: ");
  9348. stoken(content_type);
  9349. ctoken("\r\n");
  9350. }
  9351. auto offset_and_length =
  9352. get_range_offset_and_length(req.ranges[i], content_length);
  9353. ctoken("Content-Range: ");
  9354. stoken(make_content_range_header_field(offset_and_length, content_length));
  9355. ctoken("\r\n");
  9356. ctoken("\r\n");
  9357. if (!content(offset_and_length.first, offset_and_length.second)) {
  9358. return false;
  9359. }
  9360. ctoken("\r\n");
  9361. }
  9362. ctoken("--");
  9363. stoken(boundary);
  9364. ctoken("--");
  9365. return true;
  9366. }
  9367. inline void make_multipart_ranges_data(const Request &req, Response &res,
  9368. const std::string &boundary,
  9369. const std::string &content_type,
  9370. size_t content_length,
  9371. std::string &data) {
  9372. process_multipart_ranges_data(
  9373. req, boundary, content_type, content_length,
  9374. [&](const std::string &token) { data += token; },
  9375. [&](const std::string &token) { data += token; },
  9376. [&](size_t offset, size_t length) {
  9377. assert(offset + length <= content_length);
  9378. data += res.body.substr(offset, length);
  9379. return true;
  9380. });
  9381. }
  9382. inline size_t get_multipart_ranges_data_length(const Request &req,
  9383. const std::string &boundary,
  9384. const std::string &content_type,
  9385. size_t content_length) {
  9386. size_t data_length = 0;
  9387. process_multipart_ranges_data(
  9388. req, boundary, content_type, content_length,
  9389. [&](const std::string &token) { data_length += token.size(); },
  9390. [&](const std::string &token) { data_length += token.size(); },
  9391. [&](size_t /*offset*/, size_t length) {
  9392. data_length += length;
  9393. return true;
  9394. });
  9395. return data_length;
  9396. }
  9397. template <typename T>
  9398. inline bool
  9399. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  9400. const std::string &boundary,
  9401. const std::string &content_type,
  9402. size_t content_length, const T &is_shutting_down) {
  9403. return process_multipart_ranges_data(
  9404. req, boundary, content_type, content_length,
  9405. [&](const std::string &token) { strm.write(token); },
  9406. [&](const std::string &token) { strm.write(token); },
  9407. [&](size_t offset, size_t length) {
  9408. return write_content(strm, res.content_provider_, offset, length,
  9409. is_shutting_down);
  9410. });
  9411. }
  9412. inline bool has_framed_body(const Request &req) {
  9413. return is_chunked_transfer_encoding(req.headers) ||
  9414. req.get_header_value_u64("Content-Length") > 0;
  9415. }
  9416. inline bool expect_content(const Request &req) {
  9417. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  9418. req.method == "DELETE") {
  9419. return true;
  9420. }
  9421. return has_framed_body(req);
  9422. }
  9423. #ifdef _WIN32
  9424. class WSInit {
  9425. public:
  9426. WSInit() {
  9427. WSADATA wsaData;
  9428. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  9429. }
  9430. ~WSInit() {
  9431. if (is_valid_) WSACleanup();
  9432. }
  9433. bool is_valid_ = false;
  9434. };
  9435. static WSInit wsinit_;
  9436. #endif
  9437. inline std::string unescape_quoted_pairs(const std::string &s) {
  9438. std::string out;
  9439. out.reserve(s.size());
  9440. for (size_t i = 0; i < s.size(); i++) {
  9441. if (s[i] == '\\' && i + 1 < s.size()) {
  9442. out += s[++i];
  9443. } else {
  9444. out += s[i];
  9445. }
  9446. }
  9447. return out;
  9448. }
  9449. // Inverse of unescape_quoted_pairs: prepares a value to sit inside a
  9450. // quoted-string. RFC 9110 §5.6.4 requires a literal '\' or '"' to be sent as a
  9451. // quoted-pair, so the recipient recovers the original value.
  9452. inline std::string escape_quoted_pairs(const std::string &s) {
  9453. std::string out;
  9454. out.reserve(s.size());
  9455. for (auto c : s) {
  9456. if (c == '\\' || c == '"') { out += '\\'; }
  9457. out += c;
  9458. }
  9459. return out;
  9460. }
  9461. // RFC 9110 Section 11.6.1 defines a challenge list as
  9462. // WWW-Authenticate = #challenge
  9463. // challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
  9464. // auth-param = token BWS "=" BWS ( token / quoted-string )
  9465. // so a server may offer several schemes, each with its own comma-separated
  9466. // auth-param list, in either order and either as separate field lines or
  9467. // packed into one. Splitting on every comma would break apart a challenge's
  9468. // own param list; splitting only on the first space would miss a Digest
  9469. // challenge that isn't first. Split on commas that aren't inside a
  9470. // quoted-string instead (split_unquoted), then track which scheme each
  9471. // resulting segment belongs to: a segment whose text before "=" contains
  9472. // whitespace (or that has no "=" at all) starts a new challenge named by its
  9473. // leading token.
  9474. inline bool parse_www_authenticate(const Response &res,
  9475. std::map<std::string, std::string> &auth,
  9476. bool is_proxy) {
  9477. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  9478. auto combined = get_combined_header_value(res.headers, auth_key);
  9479. if (combined.empty()) { return false; }
  9480. auto found_digest = false;
  9481. auto in_digest_challenge = false;
  9482. split_unquoted(
  9483. combined.data(), combined.data() + combined.size(), ',',
  9484. [&](const char *b, const char *e) {
  9485. std::string segment(b, e);
  9486. auto eq_pos = segment.find('=');
  9487. // BWS is allowed on both sides of "=", so the text naming the key (or,
  9488. // for the first segment of a challenge, "<scheme> <key>") must be
  9489. // trimmed before its boundaries are inspected.
  9490. auto key_part = trim_copy(
  9491. eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
  9492. auto space_pos = key_part.find_last_of(" \t");
  9493. if (space_pos != std::string::npos || eq_pos == std::string::npos) {
  9494. // "<scheme>[ <key>]" starts a new challenge.
  9495. auto scheme_end =
  9496. space_pos == std::string::npos ? key_part.size() : space_pos;
  9497. // RFC 7616 Section 3.7: a server may offer more than one Digest
  9498. // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
  9499. // from one challenge is never paired with another's algorithm.
  9500. in_digest_challenge =
  9501. !found_digest &&
  9502. case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
  9503. if (in_digest_challenge) { found_digest = true; }
  9504. if (space_pos == std::string::npos) {
  9505. // Bare scheme (or a token68), no auth-param on this segment.
  9506. return;
  9507. }
  9508. key_part = key_part.substr(space_pos + 1);
  9509. }
  9510. if (!in_digest_challenge) { return; }
  9511. auto val = trim_copy(segment.substr(eq_pos + 1));
  9512. auto unquoted = trim_double_quotes_copy(val);
  9513. if (unquoted.size() != val.size()) {
  9514. unquoted = unescape_quoted_pairs(unquoted);
  9515. }
  9516. auth[std::move(key_part)] = std::move(unquoted);
  9517. });
  9518. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
  9519. // make_digest_authentication_header() dereferences both unconditionally, so
  9520. // a challenge missing either can't produce a usable Authorization header.
  9521. // Treat it the same as no Digest challenge at all.
  9522. return found_digest && auth.find("realm") != auth.end() &&
  9523. auth.find("nonce") != auth.end();
  9524. }
  9525. class ContentProviderAdapter {
  9526. public:
  9527. explicit ContentProviderAdapter(
  9528. ContentProviderWithoutLength &&content_provider)
  9529. : content_provider_(std::move(content_provider)) {}
  9530. bool operator()(size_t offset, size_t, DataSink &sink) {
  9531. return content_provider_(offset, sink);
  9532. }
  9533. private:
  9534. ContentProviderWithoutLength content_provider_;
  9535. };
  9536. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  9537. namespace fields {
  9538. inline bool is_token_char(char c) {
  9539. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  9540. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  9541. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  9542. }
  9543. inline bool is_token(const std::string &s) {
  9544. if (s.empty()) { return false; }
  9545. for (auto c : s) {
  9546. if (!is_token_char(c)) { return false; }
  9547. }
  9548. return true;
  9549. }
  9550. inline bool is_field_name(const std::string &s) { return is_token(s); }
  9551. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  9552. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  9553. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  9554. inline bool is_field_content(const std::string &s) {
  9555. if (s.empty()) { return true; }
  9556. if (s.size() == 1) {
  9557. return is_field_vchar(s[0]);
  9558. } else if (s.size() == 2) {
  9559. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  9560. } else {
  9561. size_t i = 0;
  9562. if (!is_field_vchar(s[i])) { return false; }
  9563. i++;
  9564. while (i < s.size() - 1) {
  9565. auto c = s[i++];
  9566. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  9567. } else {
  9568. return false;
  9569. }
  9570. }
  9571. return is_field_vchar(s[i]);
  9572. }
  9573. }
  9574. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  9575. inline bool is_field_valid(const std::string &name, const std::string &value) {
  9576. return is_field_name(name) && is_field_value(value);
  9577. }
  9578. // RFC 9112 §2.2/§3.2: the request-target has no SP, HTAB or other control
  9579. // characters (incl. bare CR). obs-text (raw UTF-8) is allowed.
  9580. inline bool is_request_target(const std::string &s) {
  9581. return std::all_of(s.begin(), s.end(), is_field_vchar);
  9582. }
  9583. // RFC 9110 §7.2: the bytes of uri-host [ ":" port ], i.e. unreserved,
  9584. // sub-delims, "%", ":" and the IP-literal brackets. An empty value is valid.
  9585. inline bool is_host(const std::string &s) {
  9586. return std::all_of(s.begin(), s.end(), [](char c) {
  9587. return is_ascii_alnum(c) || c == '-' || c == '.' || c == '_' || c == '~' ||
  9588. c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  9589. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  9590. c == '=' || c == '%' || c == ':' || c == '[' || c == ']';
  9591. });
  9592. }
  9593. } // namespace fields
  9594. // Built in memory first, like ClientImpl::write_request, so a rejected header
  9595. // never leaves a partial request on the wire.
  9596. inline bool write_request_head(Stream &strm, Request &req, Error &error) {
  9597. BufferStream bstrm;
  9598. if (write_request_line(bstrm, req.method, req.path) < 0) {
  9599. error = Error::Write;
  9600. return false;
  9601. }
  9602. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  9603. return false;
  9604. }
  9605. const auto &data = bstrm.get_buffer();
  9606. if (!write_data(strm, data.data(), data.size())) {
  9607. error = Error::Write;
  9608. return false;
  9609. }
  9610. return true;
  9611. }
  9612. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  9613. WebSocketUpgradeResponse &upgrade) {
  9614. // Generate a random 16-byte Sec-WebSocket-Key (RFC 6455 Section 4.1)
  9615. std::string key_bytes(16, '\0');
  9616. fill_random_bytes(reinterpret_cast<unsigned char *>(&key_bytes[0]),
  9617. key_bytes.size());
  9618. auto client_key = base64_encode(key_bytes);
  9619. req.headers.erase("Upgrade");
  9620. req.headers.erase("Connection");
  9621. req.headers.erase("Sec-WebSocket-Key");
  9622. req.headers.erase("Sec-WebSocket-Version");
  9623. req.headers.emplace("Upgrade", "websocket");
  9624. req.headers.emplace("Connection", "Upgrade");
  9625. req.headers.emplace("Sec-WebSocket-Key", client_key);
  9626. req.headers.emplace("Sec-WebSocket-Version", "13");
  9627. if (!write_request_head(strm, req, upgrade.error)) { return false; }
  9628. // Verify 101 response and Sec-WebSocket-Accept header
  9629. auto expected_accept = websocket_accept_key(client_key);
  9630. auto offered_subprotocols =
  9631. get_combined_header_value(req.headers, "Sec-WebSocket-Protocol");
  9632. return read_websocket_upgrade_response(strm, expected_accept,
  9633. offered_subprotocols, upgrade);
  9634. }
  9635. inline bool is_ip_address(const std::string &host) {
  9636. struct in_addr addr4;
  9637. struct in6_addr addr6;
  9638. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  9639. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  9640. }
  9641. // One spelling for an IPv6 address, and the IPv4 one for an IPv4-mapped IPv6
  9642. // address, which is how a dual-stack socket reports an IPv4 peer. Anything
  9643. // else, including an address with a zone ID, is returned as it is.
  9644. inline std::string canonical_ip(const std::string &addr) {
  9645. struct in6_addr addr6;
  9646. if (addr.find('%') != std::string::npos ||
  9647. inet_pton(AF_INET6, addr.c_str(), &addr6) != 1) {
  9648. return addr;
  9649. }
  9650. char buf[INET6_ADDRSTRLEN];
  9651. if (IN6_IS_ADDR_V4MAPPED(&addr6)) {
  9652. return inet_ntop(AF_INET, &addr6.s6_addr[12], buf, sizeof(buf)) ? buf
  9653. : addr;
  9654. }
  9655. return inet_ntop(AF_INET6, &addr6, buf, sizeof(buf)) ? buf : addr;
  9656. }
  9657. // `trusted_proxies` holds canonical_ip() spellings.
  9658. inline bool is_trusted_proxy(const std::string &addr,
  9659. const std::vector<std::string> &trusted_proxies) {
  9660. if (trusted_proxies.empty()) { return false; }
  9661. return std::find(trusted_proxies.begin(), trusted_proxies.end(),
  9662. canonical_ip(addr)) != trusted_proxies.end();
  9663. }
  9664. // Resolve where a client should connect for `host`, honoring a user-supplied
  9665. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  9666. // supplying the Host header and SNI; only the connection target changes.
  9667. //
  9668. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  9669. // path. Anything else goes to `connect_host`, which create_socket resolves as
  9670. // a name, or uses as the socket path when the address family is AF_UNIX. An
  9671. // absent or empty mapping leaves `host` as the connection target; without the
  9672. // empty check the value would reach getaddrinfo as a null node and silently
  9673. // resolve to loopback.
  9674. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  9675. const std::string &host, std::string &connect_host,
  9676. std::string &ip) {
  9677. connect_host = host;
  9678. ip.clear();
  9679. auto it = addr_map.find(host);
  9680. if (it == addr_map.end() || it->second.empty()) { return; }
  9681. if (is_ip_address(it->second)) {
  9682. ip = it->second;
  9683. } else {
  9684. connect_host = it->second;
  9685. }
  9686. }
  9687. } // namespace detail
  9688. /*
  9689. * Group 2: detail namespace - SSL common utilities
  9690. */
  9691. #ifdef CPPHTTPLIB_SSL_ENABLED
  9692. namespace detail {
  9693. class SSLSocketStream final : public Stream {
  9694. public:
  9695. SSLSocketStream(
  9696. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9697. time_t read_timeout_usec, time_t write_timeout_sec,
  9698. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  9699. std::chrono::time_point<std::chrono::steady_clock> start_time =
  9700. (std::chrono::steady_clock::time_point::min)());
  9701. ~SSLSocketStream() override;
  9702. bool is_readable() const override;
  9703. bool wait_readable() const override;
  9704. bool wait_writable() const override;
  9705. bool is_peer_alive() const override;
  9706. ssize_t read(char *ptr, size_t size) override;
  9707. ssize_t write(const char *ptr, size_t size) override;
  9708. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  9709. void get_local_ip_and_port(std::string &ip, int &port) const override;
  9710. socket_t socket() const override;
  9711. time_t duration() const override;
  9712. void set_read_timeout(time_t sec, time_t usec = 0) override;
  9713. void set_max_timeout(time_t msec) override;
  9714. void set_read_interrupt(std::function<bool()> interrupted) override;
  9715. // See SocketStream::set_readable_hint().
  9716. void set_readable_hint() { readable_hint_ = true; }
  9717. // The error from the last read() or write() that failed in the TLS layer,
  9718. // with code Success if none did
  9719. const tls::TlsError &tls_error() const { return tls_error_; }
  9720. private:
  9721. bool ensure_readable();
  9722. socket_t sock_;
  9723. tls::session_t session_;
  9724. time_t read_timeout_sec_;
  9725. time_t read_timeout_usec_;
  9726. time_t write_timeout_sec_;
  9727. time_t write_timeout_usec_;
  9728. time_t max_timeout_msec_;
  9729. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  9730. std::function<bool()> read_interrupted_;
  9731. bool readable_hint_ = false;
  9732. tls::TlsError tls_error_;
  9733. };
  9734. // A TLS stream for WebSocket connections, where the receive path and the
  9735. // send path (application send() plus the heartbeat ping thread) run on
  9736. // different threads. A single TLS session must never be entered
  9737. // concurrently, so every call into the session is serialized by one mutex.
  9738. //
  9739. // Unlike SSLSocketStream, the socket is kept non-blocking for the stream's
  9740. // whole lifetime and each read()/write() performs a single non-blocking TLS
  9741. // call under the lock, then waits for readiness with select() outside the
  9742. // lock. The lock is therefore held only for CPU-bound work, so a reader
  9743. // blocked waiting for data never stalls a concurrent sender.
  9744. //
  9745. // This stream is used only for wss:// connections. Plain ws:// and ordinary
  9746. // HTTP/HTTPS keep using SocketStream/SSLSocketStream unchanged.
  9747. class WebSocketSSLStream final : public Stream {
  9748. public:
  9749. WebSocketSSLStream(socket_t sock, tls::session_t session,
  9750. time_t read_timeout_sec, time_t read_timeout_usec,
  9751. time_t write_timeout_sec, time_t write_timeout_usec);
  9752. ~WebSocketSSLStream() override;
  9753. bool is_readable() const override;
  9754. bool wait_readable() const override;
  9755. bool wait_writable() const override;
  9756. ssize_t read(char *ptr, size_t size) override;
  9757. ssize_t write(const char *ptr, size_t size) override;
  9758. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  9759. void get_local_ip_and_port(std::string &ip, int &port) const override;
  9760. socket_t socket() const override;
  9761. time_t duration() const override;
  9762. void set_read_timeout(time_t sec, time_t usec = 0) override;
  9763. void set_max_timeout(time_t msec) override;
  9764. void set_read_interrupt(std::function<bool()> interrupted) override;
  9765. private:
  9766. mutable std::mutex session_mutex_;
  9767. socket_t sock_;
  9768. tls::session_t session_;
  9769. // May change while another thread is in wait_readable(); write timeouts don't
  9770. std::atomic<time_t> read_timeout_sec_;
  9771. std::atomic<time_t> read_timeout_usec_;
  9772. time_t write_timeout_sec_;
  9773. time_t write_timeout_usec_;
  9774. std::atomic<time_t> max_timeout_msec_{0};
  9775. std::atomic<std::chrono::steady_clock::rep> start_time_;
  9776. std::function<bool()> read_interrupted_;
  9777. };
  9778. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9779. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  9780. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  9781. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  9782. unsigned int hash_length = 0;
  9783. unsigned char hash[EVP_MAX_MD_SIZE];
  9784. EVP_DigestInit_ex(context.get(), algo, nullptr);
  9785. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  9786. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  9787. std::stringstream ss;
  9788. for (auto i = 0u; i < hash_length; ++i) {
  9789. ss << std::hex << std::setw(2) << std::setfill('0')
  9790. << static_cast<unsigned int>(hash[i]);
  9791. }
  9792. return ss.str();
  9793. }
  9794. inline std::string MD5(const std::string &s) {
  9795. return message_digest(s, EVP_md5());
  9796. }
  9797. inline std::string SHA_256(const std::string &s) {
  9798. return message_digest(s, EVP_sha256());
  9799. }
  9800. inline std::string SHA_512(const std::string &s) {
  9801. return message_digest(s, EVP_sha512());
  9802. }
  9803. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  9804. namespace {
  9805. template <size_t N>
  9806. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  9807. std::stringstream ss;
  9808. for (size_t i = 0; i < N; ++i) {
  9809. ss << std::hex << std::setw(2) << std::setfill('0')
  9810. << static_cast<unsigned int>(hash[i]);
  9811. }
  9812. return ss.str();
  9813. }
  9814. } // namespace
  9815. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9816. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  9817. // initialized once. PSA state is process-global; do not free it.
  9818. inline bool ensure_mbedtls_psa_crypto() {
  9819. static std::once_flag once;
  9820. static bool ok = false;
  9821. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  9822. return ok;
  9823. }
  9824. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  9825. unsigned char *out, size_t out_size) {
  9826. if (!ensure_mbedtls_psa_crypto()) { return false; }
  9827. size_t olen = 0;
  9828. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  9829. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  9830. olen == out_size;
  9831. }
  9832. #endif
  9833. inline std::string MD5(const std::string &s) {
  9834. unsigned char hash[16];
  9835. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9836. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  9837. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  9838. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9839. hash);
  9840. #else
  9841. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9842. hash);
  9843. #endif
  9844. return hash_to_hex(hash);
  9845. }
  9846. inline std::string SHA_256(const std::string &s) {
  9847. unsigned char hash[32];
  9848. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9849. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  9850. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  9851. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9852. hash, 0);
  9853. #else
  9854. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  9855. s.size(), hash, 0);
  9856. #endif
  9857. return hash_to_hex(hash);
  9858. }
  9859. inline std::string SHA_512(const std::string &s) {
  9860. unsigned char hash[64];
  9861. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9862. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  9863. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  9864. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9865. hash, 0);
  9866. #else
  9867. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  9868. s.size(), hash, 0);
  9869. #endif
  9870. return hash_to_hex(hash);
  9871. }
  9872. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  9873. namespace {
  9874. template <size_t N>
  9875. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  9876. std::stringstream ss;
  9877. for (size_t i = 0; i < N; ++i) {
  9878. ss << std::hex << std::setw(2) << std::setfill('0')
  9879. << static_cast<unsigned int>(hash[i]);
  9880. }
  9881. return ss.str();
  9882. }
  9883. } // namespace
  9884. inline std::string MD5(const std::string &s) {
  9885. unsigned char hash[WC_MD5_DIGEST_SIZE];
  9886. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  9887. static_cast<word32>(s.size()), hash);
  9888. return hash_to_hex(hash);
  9889. }
  9890. inline std::string SHA_256(const std::string &s) {
  9891. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  9892. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  9893. static_cast<word32>(s.size()), hash);
  9894. return hash_to_hex(hash);
  9895. }
  9896. inline std::string SHA_512(const std::string &s) {
  9897. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  9898. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  9899. static_cast<word32>(s.size()), hash);
  9900. return hash_to_hex(hash);
  9901. }
  9902. #endif
  9903. template <typename T>
  9904. inline bool process_server_socket_ssl(
  9905. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  9906. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  9907. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  9908. time_t write_timeout_usec, T callback) {
  9909. // See process_server_socket(). The TLS library keeps already decrypted bytes
  9910. // of a pipelined request, which keep_alive() cannot see on the socket.
  9911. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  9912. write_timeout_sec, write_timeout_usec);
  9913. size_t served = 0;
  9914. return process_server_socket_core(
  9915. strm, served, keep_alive_max_count,
  9916. [&]() { return keep_alive(svr_sock, sock, keep_alive_timeout_sec); },
  9917. callback);
  9918. }
  9919. template <typename T>
  9920. inline bool process_client_socket_ssl(
  9921. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  9922. time_t read_timeout_usec, time_t write_timeout_sec,
  9923. time_t write_timeout_usec, time_t max_timeout_msec,
  9924. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  9925. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  9926. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  9927. start_time);
  9928. return callback(strm);
  9929. }
  9930. // `uri` is req's request-target in origin form, as curl sends it, also when
  9931. // the request line carries the absolute form for a proxy.
  9932. inline std::pair<std::string, std::string> make_digest_authentication_header(
  9933. const Request &req, const std::string &uri,
  9934. const std::map<std::string, std::string> &auth, size_t cnonce_count,
  9935. const std::string &cnonce, const std::string &username,
  9936. const std::string &password, bool is_proxy = false) {
  9937. std::string nc;
  9938. {
  9939. std::stringstream ss;
  9940. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  9941. nc = ss.str();
  9942. }
  9943. std::string qop;
  9944. if (auth.find("qop") != auth.end()) {
  9945. qop = auth.at("qop");
  9946. if (qop.find("auth-int") != std::string::npos) {
  9947. qop = "auth-int";
  9948. } else if (qop.find("auth") != std::string::npos) {
  9949. qop = "auth";
  9950. } else {
  9951. qop.clear();
  9952. }
  9953. }
  9954. std::string algo = "MD5";
  9955. if (auth.find("algorithm") != auth.end()) {
  9956. // algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
  9957. // not a token would otherwise be emitted verbatim and could carry commas
  9958. // or quotes that inject further auth-params into the header below.
  9959. const auto &a = auth.at("algorithm");
  9960. if (fields::is_token(a)) { algo = a; }
  9961. }
  9962. std::string response;
  9963. {
  9964. auto H = algo == "SHA-256" ? detail::SHA_256
  9965. : algo == "SHA-512" ? detail::SHA_512
  9966. : detail::MD5;
  9967. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  9968. auto A2 = req.method + ":" + uri;
  9969. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  9970. if (qop.empty()) {
  9971. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  9972. } else {
  9973. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  9974. ":" + qop + ":" + H(A2));
  9975. }
  9976. }
  9977. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  9978. // Every value placed inside a quoted-string is escaped so a '"' in it cannot
  9979. // close the string early. realm, nonce and opaque come straight from the
  9980. // server's challenge (parse_www_authenticate() already de-escaped them), so
  9981. // without this a crafted challenge injects extra auth-params into the header.
  9982. auto field =
  9983. "Digest username=\"" + detail::escape_quoted_pairs(username) +
  9984. "\", realm=\"" + detail::escape_quoted_pairs(auth.at("realm")) +
  9985. "\", nonce=\"" + detail::escape_quoted_pairs(auth.at("nonce")) +
  9986. "\", uri=\"" + detail::escape_quoted_pairs(uri) +
  9987. "\", algorithm=" + algo +
  9988. (qop.empty() ? ", response=\""
  9989. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce +
  9990. "\", response=\"") +
  9991. response + "\"" +
  9992. (opaque.empty()
  9993. ? ""
  9994. : ", opaque=\"" + detail::escape_quoted_pairs(opaque) + "\"");
  9995. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9996. return std::make_pair(key, field);
  9997. }
  9998. // Follows X509_check_host, which the OpenSSL backend uses, so that every
  9999. // backend accepts the same names.
  10000. inline bool match_hostname(const std::string &pattern,
  10001. const std::string &hostname) {
  10002. // A trailing dot on the host is ignored
  10003. auto host = hostname;
  10004. if (host.size() > 1 && host.back() == '.') { host.pop_back(); }
  10005. // Exact match (case-insensitive)
  10006. if (detail::case_ignore::equal(host, pattern)) { return true; }
  10007. // Split both pattern and hostname into components by '.', keeping any empty
  10008. // one, which no name may have
  10009. auto labels = [](const std::string &s) {
  10010. std::vector<std::string> v;
  10011. size_t b = 0;
  10012. while (true) {
  10013. auto e = s.find('.', b);
  10014. v.push_back(s.substr(b, e - b));
  10015. if (e == std::string::npos) { return v; }
  10016. b = e + 1;
  10017. }
  10018. };
  10019. auto pattern_components = labels(pattern);
  10020. auto host_components = labels(host);
  10021. auto has_empty_label = [](const std::vector<std::string> &v) {
  10022. return std::any_of(v.begin(), v.end(),
  10023. [](const std::string &l) { return l.empty(); });
  10024. };
  10025. if (has_empty_label(pattern_components) || has_empty_label(host_components)) {
  10026. return false;
  10027. }
  10028. // Component count must match
  10029. if (host_components.size() != pattern_components.size()) { return false; }
  10030. // A wildcard needs two labels after it, so that "*.com" matches nothing,
  10031. // and an IDNA label may not have one
  10032. const auto &leftmost = pattern_components.front();
  10033. if (leftmost.find('*') != std::string::npos &&
  10034. (pattern_components.size() < 3 ||
  10035. case_ignore::equal(leftmost.substr(0, 4), "xn--"))) {
  10036. return false;
  10037. }
  10038. // Compare each component with wildcard support
  10039. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  10040. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  10041. // Only the leftmost label may carry a wildcard (RFC 6125 6.4.3)
  10042. auto itr = pattern_components.begin();
  10043. for (const auto &h : host_components) {
  10044. auto &p = *itr;
  10045. auto is_leftmost = itr == pattern_components.begin();
  10046. if (!detail::case_ignore::equal(p, h) && !(is_leftmost && p == "*")) {
  10047. bool partial_match = false;
  10048. if (is_leftmost && !p.empty() && p[p.size() - 1] == '*') {
  10049. const auto prefix_length = p.size() - 1;
  10050. if (prefix_length == 0) {
  10051. partial_match = true;
  10052. } else if (h.size() >= prefix_length) {
  10053. partial_match =
  10054. std::equal(p.begin(),
  10055. p.begin() + static_cast<std::string::difference_type>(
  10056. prefix_length),
  10057. h.begin(), [](const char ca, const char cb) {
  10058. return detail::case_ignore::to_lower(ca) ==
  10059. detail::case_ignore::to_lower(cb);
  10060. });
  10061. }
  10062. }
  10063. if (!partial_match) { return false; }
  10064. }
  10065. ++itr;
  10066. }
  10067. return true;
  10068. }
  10069. #ifdef _WIN32
  10070. // Verify certificate using Windows CertGetCertificateChain API.
  10071. // This provides real-time certificate validation with Windows Update
  10072. // integration, independent of the TLS backend.
  10073. inline bool verify_cert_with_windows_schannel(
  10074. const std::vector<unsigned char> &der_cert, const std::string &hostname,
  10075. bool verify_hostname, uint64_t &out_error, tls::const_session_t session) {
  10076. if (der_cert.empty()) { return false; }
  10077. out_error = 0;
  10078. // Create Windows certificate context from DER data
  10079. auto cert_context = CertCreateCertificateContext(
  10080. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  10081. static_cast<DWORD>(der_cert.size()));
  10082. if (!cert_context) {
  10083. out_error = GetLastError();
  10084. return false;
  10085. }
  10086. auto cert_guard =
  10087. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  10088. // Give CryptoAPI the certificates the server sent. Without them it follows
  10089. // the leaf's AIA URL, which may lead to an issuer under an untrusted root.
  10090. std::vector<tls::cert_t> peer_certs;
  10091. tls::get_peer_certs(session, peer_certs);
  10092. auto store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, nullptr);
  10093. auto store_guard = scope_exit([&] {
  10094. for (auto cert : peer_certs) {
  10095. tls::free_cert(cert);
  10096. }
  10097. if (store) { CertCloseStore(store, 0); }
  10098. });
  10099. for (auto cert : peer_certs) {
  10100. std::vector<unsigned char> der;
  10101. if (store && tls::get_cert_der(cert, der)) {
  10102. CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, der.data(),
  10103. static_cast<DWORD>(der.size()),
  10104. CERT_STORE_ADD_USE_EXISTING, nullptr);
  10105. }
  10106. }
  10107. // Setup chain parameters
  10108. CERT_CHAIN_PARA chain_para = {};
  10109. chain_para.cbSize = sizeof(chain_para);
  10110. // Require the server authentication usage along the chain, which also
  10111. // rejects roots that Windows trusts only for other purposes.
  10112. LPSTR server_auth = const_cast<LPSTR>(szOID_PKIX_KP_SERVER_AUTH);
  10113. chain_para.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
  10114. chain_para.RequestedUsage.Usage.cUsageIdentifier = 1;
  10115. chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = &server_auth;
  10116. // Build certificate chain with revocation checking
  10117. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  10118. auto chain_result = CertGetCertificateChain(
  10119. nullptr, cert_context, nullptr, store, &chain_para,
  10120. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  10121. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  10122. nullptr, &chain_context);
  10123. if (!chain_result || !chain_context) {
  10124. out_error = GetLastError();
  10125. return false;
  10126. }
  10127. auto chain_guard =
  10128. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  10129. // Verify SSL policy
  10130. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  10131. extra_policy_para.cbSize = sizeof(extra_policy_para);
  10132. #ifdef AUTHTYPE_SERVER
  10133. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  10134. #endif
  10135. std::wstring whost;
  10136. if (verify_hostname) {
  10137. whost = u8string_to_wstring(hostname.c_str());
  10138. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  10139. }
  10140. CERT_CHAIN_POLICY_PARA policy_para = {};
  10141. policy_para.cbSize = sizeof(policy_para);
  10142. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  10143. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  10144. #else
  10145. policy_para.dwFlags = 0;
  10146. #endif
  10147. policy_para.pvExtraPolicyPara = &extra_policy_para;
  10148. CERT_CHAIN_POLICY_STATUS policy_status = {};
  10149. policy_status.cbSize = sizeof(policy_status);
  10150. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  10151. &policy_para, &policy_status)) {
  10152. out_error = GetLastError();
  10153. return false;
  10154. }
  10155. if (policy_status.dwError != 0) {
  10156. out_error = policy_status.dwError;
  10157. return false;
  10158. }
  10159. return true;
  10160. }
  10161. #endif // _WIN32
  10162. // Loads CA file/dir configuration and applies the system CA policy to a
  10163. // client TLS context. PEM data and native stores are applied to the context
  10164. // directly at set time; has_custom_store reflects them for the Auto policy
  10165. // decision.
  10166. inline bool load_client_ca_config(tls::ctx_t ctx,
  10167. const std::string &ca_cert_file_path,
  10168. const std::string &ca_cert_dir_path,
  10169. bool has_custom_store, SystemCAMode mode,
  10170. uint64_t &backend_error) {
  10171. auto ret = true;
  10172. if (!ca_cert_file_path.empty()) {
  10173. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  10174. backend_error = tls::get_error();
  10175. ret = false;
  10176. }
  10177. } else if (!ca_cert_dir_path.empty()) {
  10178. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  10179. backend_error = tls::get_error();
  10180. ret = false;
  10181. }
  10182. }
  10183. auto has_custom_ca = !ca_cert_file_path.empty() ||
  10184. !ca_cert_dir_path.empty() || has_custom_store;
  10185. if (mode == SystemCAMode::Enabled ||
  10186. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  10187. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  10188. }
  10189. return ret;
  10190. }
  10191. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10192. // Schannel is skipped when a custom CA is specified, as the Windows
  10193. // certificate store would not know about it, and when system CA trust is
  10194. // explicitly disabled.
  10195. inline bool use_windows_cert_verification(bool enabled,
  10196. const std::string &ca_cert_file_path,
  10197. const std::string &ca_cert_dir_path,
  10198. bool has_custom_store,
  10199. SystemCAMode mode) {
  10200. return enabled && mode != SystemCAMode::Disabled &&
  10201. ca_cert_file_path.empty() && ca_cert_dir_path.empty() &&
  10202. !has_custom_store;
  10203. }
  10204. #endif
  10205. // Serializes the CA certificates installed in ctx as PEM, so they can be
  10206. // loaded into another context.
  10207. inline std::string ca_certs_to_pem(tls::ctx_t ctx) {
  10208. std::string pem;
  10209. std::vector<tls::cert_t> certs;
  10210. tls::get_ca_certs(ctx, certs);
  10211. for (auto cert : certs) {
  10212. std::vector<unsigned char> der;
  10213. if (tls::get_cert_der(cert, der)) {
  10214. auto b64 = base64_encode(std::string(der.begin(), der.end()));
  10215. pem += "-----BEGIN CERTIFICATE-----\n";
  10216. for (size_t i = 0; i < b64.size(); i += 64) {
  10217. pem += b64.substr(i, 64);
  10218. pem += '\n';
  10219. }
  10220. pem += "-----END CERTIFICATE-----\n";
  10221. }
  10222. tls::free_cert(cert);
  10223. }
  10224. return pem;
  10225. }
  10226. // Returns a PemMemory field as a NUL-terminated string: its first len bytes,
  10227. // copied to buf, or pem itself when len is 0.
  10228. inline const char *pem_c_str(const char *pem, size_t len, std::string &buf) {
  10229. if (!pem || len == 0) { return pem; }
  10230. buf.assign(pem, len);
  10231. return buf.c_str();
  10232. }
  10233. // The parts of session setup that only SSLClient needs, plus the handful
  10234. // WebSocketClient also exposes; everything else takes the defaults, which is
  10235. // what keeps the two clients on one implementation.
  10236. struct ClientTlsSessionOptions {
  10237. // Both SSLClient and WebSocketClient expose this independently of
  10238. // certificate verification.
  10239. bool server_hostname_verification = true;
  10240. std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
  10241. // When set, ends the handshake as a timeout does once it returns true
  10242. std::function<bool()> interrupted;
  10243. // When non-null, guards session creation against concurrent use of the
  10244. // context. A WebSocketClient is not safe to use from several threads to
  10245. // begin with, so it passes nothing.
  10246. std::mutex *ctx_mutex = nullptr;
  10247. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10248. // See use_windows_cert_verification().
  10249. bool windows_cert_verification = false;
  10250. // A server certificate verifier works on the backend's chain verification,
  10251. // so the backend keeps deciding and Schannel only adds its own check.
  10252. bool server_certificate_verifier_set = false;
  10253. #endif
  10254. };
  10255. // Filled in on failure for callers that report error details.
  10256. struct ClientTlsSessionError {
  10257. Error error = Error::Success;
  10258. int ssl_error = 0;
  10259. uint64_t backend_error = 0;
  10260. };
  10261. // Establishes a client TLS session on an already connected socket. On failure
  10262. // the session is left for the caller to free: SSLClient frees it right away,
  10263. // WebSocketClient keeps it in a member that shutdown_and_close() cleans up.
  10264. inline bool setup_client_tls_session(
  10265. const std::string &host, tls::ctx_t ctx, tls::session_t &session,
  10266. socket_t sock, bool server_certificate_verification, time_t timeout_sec,
  10267. time_t timeout_usec, ClientTlsSessionError *out_error = nullptr,
  10268. const ClientTlsSessionOptions &options = ClientTlsSessionOptions()) {
  10269. using namespace tls;
  10270. auto fail = [&](Error error, int ssl_error, uint64_t backend_error) {
  10271. if (out_error) {
  10272. out_error->error = error;
  10273. out_error->ssl_error = ssl_error;
  10274. out_error->backend_error = backend_error;
  10275. }
  10276. return false;
  10277. };
  10278. // A TLS failure, whose verification codes name the Error too
  10279. auto fail_tls = [&](ErrorCode code, uint64_t backend_error) {
  10280. auto error = Error::SSLConnection;
  10281. if (code == ErrorCode::CertVerifyFailed) {
  10282. error = Error::SSLServerVerification;
  10283. } else if (code == ErrorCode::HostnameMismatch) {
  10284. error = Error::SSLServerHostnameVerification;
  10285. }
  10286. return fail(error, static_cast<int>(code), backend_error);
  10287. };
  10288. if (!ctx) {
  10289. session = nullptr;
  10290. return fail(Error::SSLConnection, 0, 0);
  10291. }
  10292. // With Windows verification on and no server certificate verifier set,
  10293. // Schannel is the only chain verifier. The backend's trust store is a
  10294. // snapshot of the Windows stores that lacks the roots Windows fetches on
  10295. // demand, so the backend's verdict is not used.
  10296. auto windows_verifies_chain = false;
  10297. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10298. windows_verifies_chain = options.windows_cert_verification &&
  10299. !options.server_certificate_verifier_set;
  10300. #endif
  10301. // The chain, and a host name, are verified during the handshake, so that a
  10302. // server failing them never gets to see a client certificate. Unless
  10303. // Schannel verifies the chain instead, this holds for IP hosts too, whose
  10304. // identity is checked after the handshake by verify_hostname().
  10305. auto verify_in_handshake =
  10306. server_certificate_verification && !windows_verifies_chain;
  10307. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10308. // A session verifier may accept a certificate the built-in check rejects,
  10309. // and runs only after the handshake
  10310. verify_in_handshake = verify_in_handshake && !options.session_verifier;
  10311. #endif
  10312. {
  10313. std::unique_lock<std::mutex> guard;
  10314. if (options.ctx_mutex) {
  10315. guard = std::unique_lock<std::mutex>(*options.ctx_mutex);
  10316. }
  10317. // The mode is set on the context, so under the same lock
  10318. set_verify_client(ctx, verify_in_handshake);
  10319. session = create_session(ctx, sock);
  10320. }
  10321. if (!session) { return fail(Error::SSLConnection, 0, get_error()); }
  10322. // RFC 6066: SNI must not be set for IP addresses; skip it for IP hosts, so
  10323. // their identity is checked post-handshake below instead.
  10324. if (!is_ip_address(host)) {
  10325. if (!set_sni(session, host.c_str(),
  10326. verify_in_handshake && options.server_hostname_verification)) {
  10327. return fail(Error::SSLConnection, 0, get_error());
  10328. }
  10329. }
  10330. TlsError tls_err;
  10331. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, &tls_err,
  10332. options.interrupted)) {
  10333. return fail_tls(tls_err.code, tls_err.backend_code);
  10334. }
  10335. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  10336. if (options.session_verifier) {
  10337. verification_status = options.session_verifier(session);
  10338. }
  10339. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  10340. return fail(Error::SSLServerVerification, 0, get_error());
  10341. }
  10342. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  10343. server_certificate_verification) {
  10344. if (!windows_verifies_chain) {
  10345. auto verify_result = get_verify_result(session);
  10346. if (verify_result != 0) {
  10347. return fail_tls(ErrorCode::CertVerifyFailed,
  10348. static_cast<uint64_t>(verify_result));
  10349. }
  10350. }
  10351. auto server_cert = get_peer_cert(session);
  10352. if (!server_cert) {
  10353. return fail_tls(ErrorCode::CertVerifyFailed, get_error());
  10354. }
  10355. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  10356. // Identity check against the peer certificate, post-handshake for all
  10357. // backends. For IP hosts this is the only identity verification, since no
  10358. // hostname is bound during the handshake.
  10359. if (options.server_hostname_verification) {
  10360. if (!verify_hostname(server_cert, host.c_str())) {
  10361. return fail_tls(ErrorCode::HostnameMismatch, hostname_mismatch_code());
  10362. }
  10363. }
  10364. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10365. // Windows Schannel verification, which lets Windows fetch missing roots
  10366. // and intermediates on demand. It must not be skipped: unless a server
  10367. // certificate verifier is set, it is the only chain check.
  10368. if (options.windows_cert_verification) {
  10369. std::vector<unsigned char> der;
  10370. uint64_t wincrypt_error = 0;
  10371. if (!get_cert_der(server_cert, der) ||
  10372. !verify_cert_with_windows_schannel(
  10373. der, host, options.server_hostname_verification, wincrypt_error,
  10374. session)) {
  10375. return fail_tls(ErrorCode::CertVerifyFailed, wincrypt_error);
  10376. }
  10377. }
  10378. #endif
  10379. }
  10380. return true;
  10381. }
  10382. } // namespace detail
  10383. #endif // CPPHTTPLIB_SSL_ENABLED
  10384. /*
  10385. * Group 3: httplib namespace - Non-SSL public API implementations
  10386. */
  10387. inline void default_socket_options(socket_t sock) {
  10388. set_socket_opt(sock, SOL_SOCKET,
  10389. #ifdef SO_REUSEPORT
  10390. SO_REUSEPORT,
  10391. #else
  10392. SO_REUSEADDR,
  10393. #endif
  10394. 1);
  10395. }
  10396. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  10397. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  10398. sizeof(optval));
  10399. }
  10400. inline std::string get_bearer_token_auth(const Request &req) {
  10401. // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
  10402. // than the prefix carries no token.
  10403. constexpr const char bearer_prefix[] = "Bearer ";
  10404. constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
  10405. auto value = req.get_header_value("Authorization");
  10406. if (value.size() >= bearer_prefix_len &&
  10407. detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
  10408. bearer_prefix)) {
  10409. return value.substr(bearer_prefix_len);
  10410. }
  10411. return "";
  10412. }
  10413. inline const char *status_message(int status) {
  10414. switch (status) {
  10415. case StatusCode::Continue_100: return "Continue";
  10416. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  10417. case StatusCode::Processing_102: return "Processing";
  10418. case StatusCode::EarlyHints_103: return "Early Hints";
  10419. case StatusCode::OK_200: return "OK";
  10420. case StatusCode::Created_201: return "Created";
  10421. case StatusCode::Accepted_202: return "Accepted";
  10422. case StatusCode::NonAuthoritativeInformation_203:
  10423. return "Non-Authoritative Information";
  10424. case StatusCode::NoContent_204: return "No Content";
  10425. case StatusCode::ResetContent_205: return "Reset Content";
  10426. case StatusCode::PartialContent_206: return "Partial Content";
  10427. case StatusCode::MultiStatus_207: return "Multi-Status";
  10428. case StatusCode::AlreadyReported_208: return "Already Reported";
  10429. case StatusCode::IMUsed_226: return "IM Used";
  10430. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  10431. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  10432. case StatusCode::Found_302: return "Found";
  10433. case StatusCode::SeeOther_303: return "See Other";
  10434. case StatusCode::NotModified_304: return "Not Modified";
  10435. case StatusCode::UseProxy_305: return "Use Proxy";
  10436. case StatusCode::unused_306: return "unused";
  10437. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  10438. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  10439. case StatusCode::BadRequest_400: return "Bad Request";
  10440. case StatusCode::Unauthorized_401: return "Unauthorized";
  10441. case StatusCode::PaymentRequired_402: return "Payment Required";
  10442. case StatusCode::Forbidden_403: return "Forbidden";
  10443. case StatusCode::NotFound_404: return "Not Found";
  10444. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  10445. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  10446. case StatusCode::ProxyAuthenticationRequired_407:
  10447. return "Proxy Authentication Required";
  10448. case StatusCode::RequestTimeout_408: return "Request Timeout";
  10449. case StatusCode::Conflict_409: return "Conflict";
  10450. case StatusCode::Gone_410: return "Gone";
  10451. case StatusCode::LengthRequired_411: return "Length Required";
  10452. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  10453. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  10454. case StatusCode::UriTooLong_414: return "URI Too Long";
  10455. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  10456. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  10457. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  10458. case StatusCode::ImATeapot_418: return "I'm a teapot";
  10459. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  10460. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  10461. case StatusCode::Locked_423: return "Locked";
  10462. case StatusCode::FailedDependency_424: return "Failed Dependency";
  10463. case StatusCode::TooEarly_425: return "Too Early";
  10464. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  10465. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  10466. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  10467. case StatusCode::RequestHeaderFieldsTooLarge_431:
  10468. return "Request Header Fields Too Large";
  10469. case StatusCode::UnavailableForLegalReasons_451:
  10470. return "Unavailable For Legal Reasons";
  10471. case StatusCode::NotImplemented_501: return "Not Implemented";
  10472. case StatusCode::BadGateway_502: return "Bad Gateway";
  10473. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  10474. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  10475. case StatusCode::HttpVersionNotSupported_505:
  10476. return "HTTP Version Not Supported";
  10477. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  10478. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  10479. case StatusCode::LoopDetected_508: return "Loop Detected";
  10480. case StatusCode::NotExtended_510: return "Not Extended";
  10481. case StatusCode::NetworkAuthenticationRequired_511:
  10482. return "Network Authentication Required";
  10483. default:
  10484. case StatusCode::InternalServerError_500: return "Internal Server Error";
  10485. }
  10486. }
  10487. inline std::string to_string(const Error error) {
  10488. switch (error) {
  10489. case Error::Success: return "Success (no error)";
  10490. case Error::Unknown: return "Unknown";
  10491. case Error::Connection: return "Could not establish connection";
  10492. case Error::BindIPAddress: return "Failed to bind IP address";
  10493. case Error::Read: return "Failed to read connection";
  10494. case Error::Write: return "Failed to write connection";
  10495. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  10496. case Error::Canceled: return "Connection handling canceled";
  10497. case Error::SSLConnection: return "SSL connection failed";
  10498. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  10499. case Error::SSLServerVerification: return "SSL server verification failed";
  10500. case Error::SSLServerHostnameVerification:
  10501. return "SSL server hostname verification failed";
  10502. case Error::UnsupportedMultipartBoundaryChars:
  10503. return "Unsupported HTTP multipart boundary characters";
  10504. case Error::Compression: return "Compression failed";
  10505. case Error::ConnectionTimeout: return "Connection timed out";
  10506. case Error::ProxyConnection: return "Proxy connection failed";
  10507. case Error::ConnectionClosed: return "Connection closed by server";
  10508. case Error::Timeout: return "Read timeout";
  10509. case Error::ResourceExhaustion: return "Resource exhaustion";
  10510. case Error::TooManyFormDataFiles: return "Too many form data files";
  10511. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  10512. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  10513. case Error::ExceedMaxSocketDescriptorCount:
  10514. return "Exceeded maximum socket descriptor count";
  10515. case Error::InvalidRequestLine: return "Invalid request line";
  10516. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  10517. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  10518. case Error::InvalidHeaders: return "Invalid headers";
  10519. case Error::MultipartParsing: return "Multipart parsing failed";
  10520. case Error::OpenFile: return "Failed to open file";
  10521. case Error::Listen: return "Failed to listen on socket";
  10522. case Error::GetSockName: return "Failed to get socket name";
  10523. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  10524. case Error::HTTPParsing: return "HTTP parsing failed";
  10525. case Error::InvalidRangeHeader: return "Invalid Range header";
  10526. case Error::UnsupportedContentEncoding: return "Unsupported Content-Encoding";
  10527. case Error::WebSocketHandshake: return "WebSocket handshake failed";
  10528. case Error::UserCallbackException: return "User callback threw an exception";
  10529. default: break;
  10530. }
  10531. return "Invalid";
  10532. }
  10533. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  10534. os << to_string(obj);
  10535. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  10536. return os;
  10537. }
  10538. inline std::string hosted_at(const std::string &hostname) {
  10539. std::vector<std::string> addrs;
  10540. hosted_at(hostname, addrs);
  10541. if (addrs.empty()) { return std::string(); }
  10542. return addrs[0];
  10543. }
  10544. inline void hosted_at(const std::string &hostname,
  10545. std::vector<std::string> &addrs) {
  10546. struct addrinfo hints;
  10547. struct addrinfo *result;
  10548. memset(&hints, 0, sizeof(struct addrinfo));
  10549. hints.ai_family = AF_UNSPEC;
  10550. hints.ai_socktype = SOCK_STREAM;
  10551. hints.ai_protocol = 0;
  10552. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  10553. &result, 0)) {
  10554. #if defined __linux__ && !defined __ANDROID__
  10555. res_init();
  10556. #endif
  10557. return;
  10558. }
  10559. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  10560. for (auto rp = result; rp; rp = rp->ai_next) {
  10561. const auto &addr =
  10562. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  10563. std::string ip;
  10564. auto dummy = -1;
  10565. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  10566. dummy)) {
  10567. addrs.emplace_back(std::move(ip));
  10568. }
  10569. }
  10570. }
  10571. inline std::string encode_uri_component(const std::string &value) {
  10572. std::ostringstream escaped;
  10573. escaped.fill('0');
  10574. escaped << std::hex;
  10575. for (auto c : value) {
  10576. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  10577. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  10578. escaped << c;
  10579. } else {
  10580. escaped << std::uppercase;
  10581. escaped << '%' << std::setw(2)
  10582. << static_cast<int>(static_cast<unsigned char>(c));
  10583. escaped << std::nouppercase;
  10584. }
  10585. }
  10586. return escaped.str();
  10587. }
  10588. inline std::string encode_uri(const std::string &value) {
  10589. std::ostringstream escaped;
  10590. escaped.fill('0');
  10591. escaped << std::hex;
  10592. for (auto c : value) {
  10593. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  10594. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  10595. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  10596. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  10597. escaped << c;
  10598. } else {
  10599. escaped << std::uppercase;
  10600. escaped << '%' << std::setw(2)
  10601. << static_cast<int>(static_cast<unsigned char>(c));
  10602. escaped << std::nouppercase;
  10603. }
  10604. }
  10605. return escaped.str();
  10606. }
  10607. inline std::string decode_uri_component(const std::string &value) {
  10608. std::string result;
  10609. for (size_t i = 0; i < value.size(); i++) {
  10610. if (value[i] == '%' && i + 2 < value.size()) {
  10611. auto val = 0;
  10612. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  10613. result += static_cast<char>(val);
  10614. i += 2;
  10615. } else {
  10616. result += value[i];
  10617. }
  10618. } else {
  10619. result += value[i];
  10620. }
  10621. }
  10622. return result;
  10623. }
  10624. inline std::string decode_uri(const std::string &value) {
  10625. std::string result;
  10626. for (size_t i = 0; i < value.size(); i++) {
  10627. if (value[i] == '%' && i + 2 < value.size()) {
  10628. auto val = 0;
  10629. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  10630. auto c = static_cast<char>(val);
  10631. // Keep escapes of the reserved characters that encode_uri leaves
  10632. // literal, so decode_uri is the inverse of encode_uri and an escaped
  10633. // delimiter is not promoted into a real one (as with JS decodeURI).
  10634. if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  10635. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' ||
  10636. c == '#') {
  10637. result += value[i];
  10638. result += value[i + 1];
  10639. result += value[i + 2];
  10640. } else {
  10641. result += c;
  10642. }
  10643. i += 2;
  10644. } else {
  10645. result += value[i];
  10646. }
  10647. } else {
  10648. result += value[i];
  10649. }
  10650. }
  10651. return result;
  10652. }
  10653. inline std::string encode_path_component(const std::string &component) {
  10654. std::string result;
  10655. result.reserve(component.size() * 3);
  10656. for (size_t i = 0; i < component.size(); i++) {
  10657. auto c = static_cast<unsigned char>(component[i]);
  10658. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  10659. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  10660. c == '_' || c == '~') {
  10661. result += static_cast<char>(c);
  10662. }
  10663. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  10664. // "," / ";" / "="
  10665. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  10666. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  10667. c == '=') {
  10668. result += static_cast<char>(c);
  10669. }
  10670. // Colon is allowed in path segments except first segment
  10671. else if (c == ':') {
  10672. result += static_cast<char>(c);
  10673. }
  10674. // @ is allowed in path
  10675. else if (c == '@') {
  10676. result += static_cast<char>(c);
  10677. } else {
  10678. result += '%';
  10679. char hex[3];
  10680. snprintf(hex, sizeof(hex), "%02X", c);
  10681. result.append(hex, 2);
  10682. }
  10683. }
  10684. return result;
  10685. }
  10686. inline std::string decode_path_component(const std::string &component) {
  10687. std::string result;
  10688. result.reserve(component.size());
  10689. for (size_t i = 0; i < component.size(); i++) {
  10690. if (component[i] == '%' && i + 1 < component.size()) {
  10691. if (component[i + 1] == 'u') {
  10692. // Unicode %uXXXX encoding
  10693. auto val = 0;
  10694. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  10695. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  10696. char buff[4];
  10697. size_t len = 0;
  10698. if (detail::from_hex_to_i(component, i + 2, 4, val) &&
  10699. (len = detail::to_utf8(val, buff)) > 0) {
  10700. result.append(buff, len);
  10701. i += 5; // 'u0000'
  10702. } else {
  10703. // Not 4 hex digits, or a surrogate, which is no character: the
  10704. // escape is kept as it is rather than joining its neighbours
  10705. result += component[i];
  10706. }
  10707. } else {
  10708. // Standard %XX encoding
  10709. auto val = 0;
  10710. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  10711. // 2 digits hex codes
  10712. result += static_cast<char>(val);
  10713. i += 2; // 'XX'
  10714. } else {
  10715. result += component[i];
  10716. }
  10717. }
  10718. } else {
  10719. result += component[i];
  10720. }
  10721. }
  10722. return result;
  10723. }
  10724. inline std::string encode_query_component(const std::string &component,
  10725. bool space_as_plus) {
  10726. std::string result;
  10727. result.reserve(component.size() * 3);
  10728. for (size_t i = 0; i < component.size(); i++) {
  10729. auto c = static_cast<unsigned char>(component[i]);
  10730. // Unreserved characters per RFC 3986
  10731. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  10732. c == '_' || c == '~') {
  10733. result += static_cast<char>(c);
  10734. }
  10735. // Space handling
  10736. else if (c == ' ') {
  10737. if (space_as_plus) {
  10738. result += '+';
  10739. } else {
  10740. result += "%20";
  10741. }
  10742. }
  10743. // Plus sign handling
  10744. else if (c == '+') {
  10745. if (space_as_plus) {
  10746. result += "%2B";
  10747. } else {
  10748. result += static_cast<char>(c);
  10749. }
  10750. }
  10751. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  10752. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  10753. c == '*' || c == ',' || c == ';') {
  10754. result += static_cast<char>(c);
  10755. }
  10756. // Colon and @ are allowed in query
  10757. else if (c == ':' || c == '@') {
  10758. result += static_cast<char>(c);
  10759. }
  10760. // Forward slash is allowed in query values
  10761. else if (c == '/') {
  10762. result += static_cast<char>(c);
  10763. }
  10764. // Question mark is allowed in query values (after first ?)
  10765. else if (c == '?') {
  10766. result += static_cast<char>(c);
  10767. } else {
  10768. result += '%';
  10769. char hex[3];
  10770. snprintf(hex, sizeof(hex), "%02X", c);
  10771. result.append(hex, 2);
  10772. }
  10773. }
  10774. return result;
  10775. }
  10776. inline std::string decode_query_component(const std::string &component,
  10777. bool plus_as_space) {
  10778. std::string result;
  10779. result.reserve(component.size());
  10780. for (size_t i = 0; i < component.size(); i++) {
  10781. if (component[i] == '%' && i + 2 < component.size()) {
  10782. auto val = 0;
  10783. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  10784. result += static_cast<char>(val);
  10785. i += 2;
  10786. } else {
  10787. result += component[i];
  10788. }
  10789. } else if (component[i] == '+' && plus_as_space) {
  10790. result += ' '; // + becomes space in form-urlencoded
  10791. } else {
  10792. result += component[i];
  10793. }
  10794. }
  10795. return result;
  10796. }
  10797. inline std::string sanitize_filename(const std::string &filename) {
  10798. // Extract basename: find the last path separator (/ or \) and, on Windows,
  10799. // ':', which ends a drive prefix ("C:..") or names an NTFS stream ("a:b")
  10800. #ifdef _WIN32
  10801. auto pos = filename.find_last_of("/\\:");
  10802. #else
  10803. auto pos = filename.find_last_of("/\\");
  10804. #endif
  10805. auto result =
  10806. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  10807. // Strip null bytes
  10808. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  10809. // Trim whitespace
  10810. {
  10811. auto start = result.find_first_not_of(" \t");
  10812. auto end = result.find_last_not_of(" \t");
  10813. result = (start == std::string::npos)
  10814. ? ""
  10815. : result.substr(start, end - start + 1);
  10816. }
  10817. // Reject . and ..
  10818. if (result == "." || result == "..") { return ""; }
  10819. return result;
  10820. }
  10821. inline std::string append_query_params(const std::string &path,
  10822. const Params &params) {
  10823. // The query ends at the fragment (RFC 3986 3.5), so the params go before it.
  10824. auto fragment_pos = path.find('#');
  10825. auto path_with_query = path.substr(0, fragment_pos);
  10826. path_with_query += path_with_query.find('?') == std::string::npos ? '?' : '&';
  10827. path_with_query += detail::params_to_query_str(params);
  10828. if (fragment_pos != std::string::npos) {
  10829. path_with_query.append(path, fragment_pos, std::string::npos);
  10830. }
  10831. return path_with_query;
  10832. }
  10833. // Header utilities
  10834. inline std::pair<std::string, std::string>
  10835. make_range_header(const Ranges &ranges) {
  10836. std::string field = "bytes=";
  10837. auto i = 0;
  10838. for (const auto &r : ranges) {
  10839. if (i != 0) { field += ", "; }
  10840. if (r.first != -1) { field += std::to_string(r.first); }
  10841. field += '-';
  10842. if (r.second != -1) { field += std::to_string(r.second); }
  10843. i++;
  10844. }
  10845. return std::make_pair("Range", std::move(field));
  10846. }
  10847. inline std::pair<std::string, std::string>
  10848. make_basic_authentication_header(const std::string &username,
  10849. const std::string &password, bool is_proxy) {
  10850. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  10851. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  10852. return std::make_pair(key, std::move(field));
  10853. }
  10854. inline std::pair<std::string, std::string>
  10855. make_bearer_token_authentication_header(const std::string &token,
  10856. bool is_proxy = false) {
  10857. auto field = "Bearer " + token;
  10858. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  10859. return std::make_pair(key, std::move(field));
  10860. }
  10861. namespace detail {
  10862. // Basic auth when a username or password is set, otherwise a bearer token,
  10863. // unless the request already carries the header.
  10864. inline void add_authorization_header(Request &req, const std::string &username,
  10865. const std::string &password,
  10866. const std::string &token, bool is_proxy) {
  10867. if (req.has_header(is_proxy ? "Proxy-Authorization" : "Authorization")) {
  10868. return;
  10869. }
  10870. if (!username.empty() || !password.empty()) {
  10871. req.headers.insert(
  10872. make_basic_authentication_header(username, password, is_proxy));
  10873. } else if (!token.empty()) {
  10874. req.headers.insert(
  10875. make_bearer_token_authentication_header(token, is_proxy));
  10876. }
  10877. }
  10878. } // namespace detail
  10879. // Request implementation
  10880. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  10881. size_t id) const {
  10882. return detail::get_header_value_u64(headers, key, def, id);
  10883. }
  10884. inline bool Request::has_header(const std::string &key) const {
  10885. return detail::has_header(headers, key);
  10886. }
  10887. inline std::string Request::get_header_value(const std::string &key,
  10888. const char *def, size_t id) const {
  10889. return detail::get_header_value(headers, key, def, id);
  10890. }
  10891. inline size_t Request::get_header_value_count(const std::string &key) const {
  10892. return detail::get_header_value_count(headers, key);
  10893. }
  10894. inline void Request::set_header(const std::string &key,
  10895. const std::string &val) {
  10896. detail::set_header(headers, key, val);
  10897. }
  10898. inline bool Request::has_trailer(const std::string &key) const {
  10899. return trailers.find(key) != trailers.end();
  10900. }
  10901. inline std::string Request::get_trailer_value(const std::string &key,
  10902. size_t id) const {
  10903. return detail::get_multimap_value(trailers, key, id);
  10904. }
  10905. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  10906. return trailers.count(key);
  10907. }
  10908. inline bool Request::has_param(const std::string &key) const {
  10909. return params.find(key) != params.end();
  10910. }
  10911. inline std::string Request::get_param_value(const std::string &key,
  10912. size_t id) const {
  10913. return detail::get_multimap_value(params, key, id);
  10914. }
  10915. inline std::vector<std::string>
  10916. Request::get_param_values(const std::string &key) const {
  10917. auto rng = params.equal_range(key);
  10918. std::vector<std::string> values;
  10919. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  10920. for (auto it = rng.first; it != rng.second; ++it) {
  10921. values.push_back(it->second);
  10922. }
  10923. return values;
  10924. }
  10925. inline size_t Request::get_param_value_count(const std::string &key) const {
  10926. return params.count(key);
  10927. }
  10928. inline bool Request::is_multipart_form_data() const {
  10929. const auto &content_type = get_header_value("Content-Type");
  10930. return detail::case_ignore::equal(detail::extract_media_type(content_type),
  10931. "multipart/form-data");
  10932. }
  10933. // Multipart FormData implementation
  10934. inline std::string MultipartFormData::get_field(const std::string &key,
  10935. size_t id) const {
  10936. auto rng = fields.equal_range(key);
  10937. auto it = detail::bounded_next(rng.first, id, rng.second);
  10938. if (it != rng.second) { return it->second.content; }
  10939. return std::string();
  10940. }
  10941. inline std::vector<std::string>
  10942. MultipartFormData::get_fields(const std::string &key) const {
  10943. std::vector<std::string> values;
  10944. auto rng = fields.equal_range(key);
  10945. for (auto it = rng.first; it != rng.second; it++) {
  10946. values.push_back(it->second.content);
  10947. }
  10948. return values;
  10949. }
  10950. inline bool MultipartFormData::has_field(const std::string &key) const {
  10951. return fields.find(key) != fields.end();
  10952. }
  10953. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  10954. return fields.count(key);
  10955. }
  10956. inline FormData MultipartFormData::get_file(const std::string &key,
  10957. size_t id) const {
  10958. return detail::get_multimap_value(files, key, id);
  10959. }
  10960. inline std::vector<FormData>
  10961. MultipartFormData::get_files(const std::string &key) const {
  10962. std::vector<FormData> values;
  10963. auto rng = files.equal_range(key);
  10964. for (auto it = rng.first; it != rng.second; it++) {
  10965. values.push_back(it->second);
  10966. }
  10967. return values;
  10968. }
  10969. inline bool MultipartFormData::has_file(const std::string &key) const {
  10970. return files.find(key) != files.end();
  10971. }
  10972. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  10973. return files.count(key);
  10974. }
  10975. // Multipart FormData writer implementation
  10976. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  10977. return detail::is_multipart_boundary_chars_valid(boundary);
  10978. }
  10979. inline MultipartFormDataWriter::MultipartFormDataWriter()
  10980. : boundary_(detail::make_multipart_data_boundary()) {}
  10981. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  10982. : boundary_(std::move(boundary)) {}
  10983. inline const std::string &MultipartFormDataWriter::boundary() const {
  10984. return boundary_;
  10985. }
  10986. inline std::string MultipartFormDataWriter::content_type() const {
  10987. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  10988. }
  10989. inline std::string
  10990. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  10991. return detail::serialize_multipart_formdata(items, boundary_);
  10992. }
  10993. inline size_t MultipartFormDataWriter::content_length(
  10994. const UploadFormDataItems &items) const {
  10995. return detail::get_multipart_content_length(items, boundary_);
  10996. }
  10997. inline std::string
  10998. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  10999. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  11000. }
  11001. inline std::string MultipartFormDataWriter::item_end() {
  11002. return detail::serialize_multipart_formdata_item_end();
  11003. }
  11004. inline std::string MultipartFormDataWriter::finish() const {
  11005. return detail::serialize_multipart_formdata_finish(boundary_);
  11006. }
  11007. // Response implementation
  11008. namespace detail {
  11009. // A response has one content source: `body`, a content provider, or a file.
  11010. // Each content setter calls this so that the one called last wins.
  11011. inline void clear_content_provider(Response &res) {
  11012. auto releaser = std::move(res.content_provider_resource_releaser_);
  11013. auto success = res.content_provider_success_;
  11014. res.content_length_ = 0;
  11015. res.content_provider_ = nullptr;
  11016. res.content_provider_resource_releaser_ = nullptr;
  11017. res.is_chunked_content_provider_ = false;
  11018. res.is_file_content_provider_ = false;
  11019. res.content_provider_success_ = false;
  11020. res.content_coding_ = EncodingType::None;
  11021. res.file_content_path_.clear();
  11022. res.file_content_content_type_.clear();
  11023. if (releaser) { releaser(success); }
  11024. }
  11025. inline void clear_content(Response &res) {
  11026. res.body.clear();
  11027. clear_content_provider(res);
  11028. }
  11029. // The Content-Type of the old content goes with it.
  11030. inline void set_content_type(Response &res, const std::string &content_type) {
  11031. res.headers.erase("Content-Type");
  11032. res.set_header("Content-Type", content_type);
  11033. }
  11034. // `body` is public, so it can be assigned directly after a provider or a file
  11035. // was set. It came last, so it wins.
  11036. inline void prefer_assigned_body(Response &res) {
  11037. if (!res.body.empty() &&
  11038. (res.content_provider_ || !res.file_content_path_.empty())) {
  11039. clear_content_provider(res);
  11040. }
  11041. }
  11042. // RFC 9112 6.3: a 1xx, 204 or 304 response ends with its header section.
  11043. inline bool body_allowed_for_status(int status) {
  11044. return status >= 200 && status != StatusCode::NoContent_204 &&
  11045. status != StatusCode::NotModified_304;
  11046. }
  11047. // Only a 206 response is served as a partial representation. range_error()
  11048. // validates `req.ranges` only for a 2xx status, so slicing under any other
  11049. // status would start from an unchecked offset.
  11050. inline bool is_partial_content(const Request &req, const Response &res) {
  11051. return !req.ranges.empty() && res.status == StatusCode::PartialContent_206;
  11052. }
  11053. // Sets the Content-Length or Transfer-Encoding framing the body that
  11054. // Server::write_response_core() writes, or closes the connection after a body
  11055. // that has neither. Only the library sets them: one from a handler would go
  11056. // out next to it, or describe some other body.
  11057. inline void set_framing_headers(const Request &req, Response &res,
  11058. const std::string &boundary,
  11059. const std::string &content_type) {
  11060. // A HEAD response may give the length a GET would have had (RFC 9110 9.3.2).
  11061. auto head_length = req.method == "HEAD"
  11062. ? res.get_header_value("Content-Length")
  11063. : std::string();
  11064. res.headers.erase("Content-Length");
  11065. res.headers.erase("Transfer-Encoding");
  11066. if (!body_allowed_for_status(res.status)) { return; }
  11067. if (res.content_provider_) {
  11068. if (res.content_length_ == 0) {
  11069. if (res.is_chunked_content_provider_) {
  11070. res.set_header("Transfer-Encoding", "chunked");
  11071. } else if (req.method != "HEAD") {
  11072. // RFC 9112 6.3: a body with neither ends where the connection does.
  11073. res.headers.erase("Keep-Alive");
  11074. if (!has_header_token(res.headers, "Connection", "close")) {
  11075. res.set_header("Connection", "close");
  11076. }
  11077. }
  11078. return;
  11079. }
  11080. // The part Server::write_content_with_provider() writes.
  11081. auto length = res.content_length_;
  11082. if (is_partial_content(req, res)) {
  11083. length = req.ranges.size() == 1
  11084. ? get_range_offset_and_length(req.ranges[0], length).second
  11085. : get_multipart_ranges_data_length(req, boundary,
  11086. content_type, length);
  11087. }
  11088. res.set_header("Content-Length", std::to_string(length));
  11089. } else if (!res.body.empty()) {
  11090. res.set_header("Content-Length", std::to_string(res.body.size()));
  11091. } else {
  11092. res.set_header("Content-Length", head_length.empty() ? "0" : head_length);
  11093. }
  11094. }
  11095. } // namespace detail
  11096. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  11097. size_t id) const {
  11098. return detail::get_header_value_u64(headers, key, def, id);
  11099. }
  11100. inline bool Response::has_header(const std::string &key) const {
  11101. return headers.find(key) != headers.end();
  11102. }
  11103. inline std::string Response::get_header_value(const std::string &key,
  11104. const char *def,
  11105. size_t id) const {
  11106. return detail::get_header_value(headers, key, def, id);
  11107. }
  11108. inline size_t Response::get_header_value_count(const std::string &key) const {
  11109. return detail::get_header_value_count(headers, key);
  11110. }
  11111. inline void Response::set_header(const std::string &key,
  11112. const std::string &val) {
  11113. detail::set_header(headers, key, val);
  11114. }
  11115. inline bool Response::has_trailer(const std::string &key) const {
  11116. return trailers.find(key) != trailers.end();
  11117. }
  11118. inline std::string Response::get_trailer_value(const std::string &key,
  11119. size_t id) const {
  11120. return detail::get_multimap_value(trailers, key, id);
  11121. }
  11122. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  11123. return trailers.count(key);
  11124. }
  11125. inline void Response::set_redirect(const std::string &url, int stat) {
  11126. if (detail::fields::is_field_value(url)) {
  11127. set_header("Location", url);
  11128. if (300 <= stat && stat < 400) {
  11129. this->status = stat;
  11130. } else {
  11131. this->status = StatusCode::Found_302;
  11132. }
  11133. }
  11134. }
  11135. inline void Response::set_content(const char *s, size_t n,
  11136. const std::string &content_type) {
  11137. body.assign(s, n); // Before the releaser runs; it may own `s`.
  11138. detail::clear_content_provider(*this);
  11139. detail::set_content_type(*this, content_type);
  11140. }
  11141. inline void Response::set_content(const std::string &s,
  11142. const std::string &content_type) {
  11143. set_content(s.data(), s.size(), content_type);
  11144. }
  11145. inline void Response::set_content(std::string &&s,
  11146. const std::string &content_type) {
  11147. body = std::move(s);
  11148. detail::clear_content_provider(*this);
  11149. detail::set_content_type(*this, content_type);
  11150. }
  11151. inline void Response::set_content_provider(
  11152. size_t in_length, const std::string &content_type, ContentProvider provider,
  11153. ContentProviderResourceReleaser resource_releaser) {
  11154. detail::clear_content(*this);
  11155. detail::set_content_type(*this, content_type);
  11156. content_length_ = in_length;
  11157. if (in_length > 0) { content_provider_ = std::move(provider); }
  11158. content_provider_resource_releaser_ = std::move(resource_releaser);
  11159. }
  11160. inline void Response::set_content_provider(
  11161. const std::string &content_type, ContentProviderWithoutLength provider,
  11162. ContentProviderResourceReleaser resource_releaser) {
  11163. detail::clear_content(*this);
  11164. detail::set_content_type(*this, content_type);
  11165. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  11166. content_provider_resource_releaser_ = std::move(resource_releaser);
  11167. }
  11168. inline void Response::set_chunked_content_provider(
  11169. const std::string &content_type, ContentProviderWithoutLength provider,
  11170. ContentProviderResourceReleaser resource_releaser) {
  11171. set_content_provider(content_type, std::move(provider),
  11172. std::move(resource_releaser));
  11173. is_chunked_content_provider_ = true;
  11174. }
  11175. inline void Response::set_file_content(const std::string &path,
  11176. const std::string &content_type) {
  11177. detail::clear_content(*this);
  11178. headers.erase("Content-Type");
  11179. file_content_path_ = path;
  11180. file_content_content_type_ = content_type;
  11181. }
  11182. inline void Response::set_file_content(const std::string &path) {
  11183. set_file_content(path, std::string());
  11184. }
  11185. // Result implementation
  11186. inline size_t Result::get_request_header_value_u64(const std::string &key,
  11187. size_t def,
  11188. size_t id) const {
  11189. return detail::get_header_value_u64(request_headers_, key, def, id);
  11190. }
  11191. inline bool Result::has_request_header(const std::string &key) const {
  11192. return request_headers_.find(key) != request_headers_.end();
  11193. }
  11194. inline std::string Result::get_request_header_value(const std::string &key,
  11195. const char *def,
  11196. size_t id) const {
  11197. return detail::get_header_value(request_headers_, key, def, id);
  11198. }
  11199. inline size_t
  11200. Result::get_request_header_value_count(const std::string &key) const {
  11201. return request_headers_.count(key);
  11202. }
  11203. // Stream implementation
  11204. inline ssize_t Stream::write(const char *ptr) {
  11205. return write(ptr, strlen(ptr));
  11206. }
  11207. inline ssize_t Stream::write(const std::string &s) {
  11208. return write(s.data(), s.size());
  11209. }
  11210. // BodyReader implementation
  11211. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  11212. if (!stream) {
  11213. last_error = Error::Connection;
  11214. return -1;
  11215. }
  11216. if (eof) { return 0; }
  11217. if (!chunked) {
  11218. // Content-Length based reading
  11219. if (has_content_length && bytes_read >= content_length) {
  11220. eof = true;
  11221. return 0;
  11222. }
  11223. auto to_read = len;
  11224. if (has_content_length) {
  11225. auto remaining = content_length - bytes_read;
  11226. to_read = (std::min)(len, remaining);
  11227. }
  11228. auto n = stream->read(buf, to_read);
  11229. // Without Content-Length the body ends when the connection closes
  11230. // (RFC 9112 §6.3); with one, an EOF here came too early
  11231. if (n < 0 || (n == 0 && has_content_length)) {
  11232. last_error = stream->get_error();
  11233. if (last_error == Error::Success) { last_error = Error::Read; }
  11234. }
  11235. if (n <= 0) {
  11236. eof = true;
  11237. return n;
  11238. }
  11239. bytes_read += static_cast<size_t>(n);
  11240. if (has_content_length && bytes_read >= content_length) { eof = true; }
  11241. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  11242. last_error = Error::ExceedMaxPayloadSize;
  11243. eof = true;
  11244. return -1;
  11245. }
  11246. return n;
  11247. }
  11248. // Chunked transfer encoding: delegate to shared decoder instance.
  11249. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  11250. size_t chunk_offset = 0;
  11251. size_t chunk_total = 0;
  11252. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  11253. if (n < 0) {
  11254. last_error = stream->get_error();
  11255. if (last_error == Error::Success) { last_error = Error::Read; }
  11256. eof = true;
  11257. return n;
  11258. }
  11259. if (n == 0) {
  11260. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  11261. eof = true;
  11262. return 0;
  11263. }
  11264. bytes_read += static_cast<size_t>(n);
  11265. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  11266. last_error = Error::ExceedMaxPayloadSize;
  11267. eof = true;
  11268. return -1;
  11269. }
  11270. return n;
  11271. }
  11272. // ThreadPool implementation
  11273. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  11274. time_t idle_timeout_sec)
  11275. : base_thread_count_(n), max_queued_requests_(mqr),
  11276. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  11277. shutdown_(false) {
  11278. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11279. if (max_n != 0 && max_n < n) {
  11280. std::string msg = "max_threads must be >= base_threads";
  11281. throw std::invalid_argument(msg);
  11282. }
  11283. #endif
  11284. max_thread_count_ = max_n == 0 ? n : max_n;
  11285. threads_.reserve(base_thread_count_);
  11286. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11287. try {
  11288. #endif
  11289. for (size_t i = 0; i < base_thread_count_; i++) {
  11290. threads_.emplace_back(std::thread([this]() { worker(false); }));
  11291. }
  11292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11293. } catch (...) {
  11294. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  11295. // signal the workers we already spawned to exit and join them so the
  11296. // vector destructor does not see joinable threads (which would call
  11297. // std::terminate). Then rethrow so the caller learns of the failure.
  11298. {
  11299. std::unique_lock<std::mutex> lock(mutex_);
  11300. shutdown_ = true;
  11301. }
  11302. cond_.notify_all();
  11303. for (auto &t : threads_) {
  11304. if (t.joinable()) { t.join(); }
  11305. }
  11306. throw;
  11307. }
  11308. #endif
  11309. }
  11310. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  11311. {
  11312. std::unique_lock<std::mutex> lock(mutex_);
  11313. if (shutdown_) { return false; }
  11314. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  11315. return false;
  11316. }
  11317. jobs_.push_back(std::move(fn));
  11318. // Spawn a dynamic thread if jobs outnumber idle threads and under max
  11319. if (jobs_.size() > idle_thread_count_ &&
  11320. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  11321. cleanup_finished_threads();
  11322. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11323. try {
  11324. #endif
  11325. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  11326. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11327. } catch (const std::system_error &) {
  11328. // No thread budget left: keep the job queued for an existing worker
  11329. // instead of letting the exception escape the accept loop.
  11330. }
  11331. #endif
  11332. }
  11333. }
  11334. cond_.notify_one();
  11335. return true;
  11336. }
  11337. inline void ThreadPool::shutdown() {
  11338. {
  11339. std::unique_lock<std::mutex> lock(mutex_);
  11340. shutdown_ = true;
  11341. }
  11342. cond_.notify_all();
  11343. for (auto &t : threads_) {
  11344. if (t.joinable()) { t.join(); }
  11345. }
  11346. // Move dynamic_threads_ to a local list under the lock to avoid racing
  11347. // with worker threads that call move_to_finished() concurrently.
  11348. std::list<std::thread> remaining_dynamic;
  11349. {
  11350. std::unique_lock<std::mutex> lock(mutex_);
  11351. remaining_dynamic = std::move(dynamic_threads_);
  11352. }
  11353. for (auto &t : remaining_dynamic) {
  11354. if (t.joinable()) { t.join(); }
  11355. }
  11356. std::unique_lock<std::mutex> lock(mutex_);
  11357. cleanup_finished_threads();
  11358. }
  11359. inline void ThreadPool::move_to_finished(std::thread::id id) {
  11360. // Must be called with mutex_ held
  11361. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  11362. if (it->get_id() == id) {
  11363. finished_threads_.push_back(std::move(*it));
  11364. dynamic_threads_.erase(it);
  11365. return;
  11366. }
  11367. }
  11368. }
  11369. inline void ThreadPool::cleanup_finished_threads() {
  11370. // Must be called with mutex_ held
  11371. for (auto &t : finished_threads_) {
  11372. if (t.joinable()) { t.join(); }
  11373. }
  11374. finished_threads_.clear();
  11375. }
  11376. inline void ThreadPool::worker(bool is_dynamic) {
  11377. for (;;) {
  11378. std::function<void()> fn;
  11379. {
  11380. std::unique_lock<std::mutex> lock(mutex_);
  11381. idle_thread_count_++;
  11382. if (is_dynamic) {
  11383. auto has_work =
  11384. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  11385. [&] { return !jobs_.empty() || shutdown_; });
  11386. if (!has_work) {
  11387. // Timed out with no work - exit this dynamic thread
  11388. idle_thread_count_--;
  11389. move_to_finished(std::this_thread::get_id());
  11390. break;
  11391. }
  11392. } else {
  11393. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  11394. }
  11395. idle_thread_count_--;
  11396. if (shutdown_ && jobs_.empty()) { break; }
  11397. fn = std::move(jobs_.front());
  11398. jobs_.pop_front();
  11399. }
  11400. assert(true == static_cast<bool>(fn));
  11401. fn();
  11402. }
  11403. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  11404. !defined(LIBRESSL_VERSION_NUMBER)
  11405. OPENSSL_thread_stop();
  11406. #endif
  11407. }
  11408. /*
  11409. * Group 1 (continued): detail namespace - Stream implementations
  11410. */
  11411. namespace detail {
  11412. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  11413. time_t timeout_sec, time_t timeout_usec,
  11414. time_t &actual_timeout_sec,
  11415. time_t &actual_timeout_usec) {
  11416. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  11417. auto actual_timeout_msec =
  11418. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  11419. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  11420. actual_timeout_sec = actual_timeout_msec / 1000;
  11421. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  11422. }
  11423. // Socket stream implementation
  11424. inline SocketStream::SocketStream(
  11425. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  11426. time_t write_timeout_sec, time_t write_timeout_usec,
  11427. time_t max_timeout_msec,
  11428. std::chrono::time_point<std::chrono::steady_clock> start_time)
  11429. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  11430. read_timeout_usec_(read_timeout_usec),
  11431. write_timeout_sec_(write_timeout_sec),
  11432. write_timeout_usec_(write_timeout_usec),
  11433. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {}
  11434. inline SocketStream::~SocketStream() = default;
  11435. inline bool SocketStream::is_readable() const {
  11436. return read_buff_off_ < read_buff_content_size_;
  11437. }
  11438. inline bool SocketStream::wait_readable() const {
  11439. if (max_timeout_msec_ <= 0) {
  11440. return select_read_interruptible(sock_, read_timeout_sec_,
  11441. read_timeout_usec_, read_interrupted_) > 0;
  11442. }
  11443. time_t read_timeout_sec;
  11444. time_t read_timeout_usec;
  11445. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  11446. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  11447. return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
  11448. read_interrupted_) > 0;
  11449. }
  11450. inline bool SocketStream::wait_writable() const {
  11451. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  11452. }
  11453. inline bool SocketStream::ensure_readable() {
  11454. if (readable_hint_) {
  11455. readable_hint_ = false;
  11456. return true;
  11457. }
  11458. return wait_readable();
  11459. }
  11460. inline const char *SocketStream::buffered_data(size_t &size) const {
  11461. size = read_buff_content_size_ - read_buff_off_;
  11462. return size ? read_buff_.data() + read_buff_off_ : nullptr;
  11463. }
  11464. inline void SocketStream::release_buffer() {
  11465. assert(read_buff_off_ == read_buff_content_size_);
  11466. std::vector<char>().swap(read_buff_);
  11467. }
  11468. inline void SocketStream::consume_buffered(size_t size) {
  11469. assert(size <= read_buff_content_size_ - read_buff_off_);
  11470. read_buff_off_ += size;
  11471. }
  11472. inline bool SocketStream::is_peer_alive() const {
  11473. return detail::is_socket_alive(sock_);
  11474. }
  11475. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  11476. #ifdef _WIN32
  11477. size =
  11478. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  11479. #else
  11480. size = (std::min)(size,
  11481. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  11482. #endif
  11483. if (read_buff_off_ < read_buff_content_size_) {
  11484. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  11485. if (size <= remaining_size) {
  11486. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  11487. read_buff_off_ += size;
  11488. return static_cast<ssize_t>(size);
  11489. } else {
  11490. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  11491. read_buff_off_ += remaining_size;
  11492. return static_cast<ssize_t>(remaining_size);
  11493. }
  11494. }
  11495. if (!ensure_readable()) {
  11496. error_ = Error::Timeout;
  11497. return -1;
  11498. }
  11499. read_buff_off_ = 0;
  11500. read_buff_content_size_ = 0;
  11501. if (size < read_buff_size_) {
  11502. // Allocated on the first use, which an idle connection may never make.
  11503. if (read_buff_.empty()) { read_buff_.resize(read_buff_size_); }
  11504. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  11505. CPPHTTPLIB_RECV_FLAGS);
  11506. if (n <= 0) {
  11507. if (n == 0) {
  11508. error_ = Error::ConnectionClosed;
  11509. } else {
  11510. error_ = Error::Read;
  11511. }
  11512. return n;
  11513. } else if (n <= static_cast<ssize_t>(size)) {
  11514. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  11515. return n;
  11516. } else {
  11517. memcpy(ptr, read_buff_.data(), size);
  11518. read_buff_off_ = size;
  11519. read_buff_content_size_ = static_cast<size_t>(n);
  11520. return static_cast<ssize_t>(size);
  11521. }
  11522. } else {
  11523. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  11524. if (n <= 0) {
  11525. if (n == 0) {
  11526. error_ = Error::ConnectionClosed;
  11527. } else {
  11528. error_ = Error::Read;
  11529. }
  11530. }
  11531. return n;
  11532. }
  11533. }
  11534. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  11535. if (!wait_writable()) { return -1; }
  11536. // Winsock's send() takes an int length, even on 64-bit Windows
  11537. #ifdef _WIN32
  11538. size =
  11539. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  11540. #endif
  11541. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  11542. }
  11543. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  11544. int &port) const {
  11545. return detail::get_remote_ip_and_port(sock_, ip, port);
  11546. }
  11547. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  11548. int &port) const {
  11549. return detail::get_local_ip_and_port(sock_, ip, port);
  11550. }
  11551. inline socket_t SocketStream::socket() const { return sock_; }
  11552. inline time_t SocketStream::duration() const {
  11553. return static_cast<time_t>(
  11554. std::chrono::duration_cast<std::chrono::milliseconds>(
  11555. std::chrono::steady_clock::now() - start_time_)
  11556. .count());
  11557. }
  11558. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  11559. read_timeout_sec_ = sec;
  11560. read_timeout_usec_ = usec;
  11561. }
  11562. inline void SocketStream::set_max_timeout(time_t msec) {
  11563. max_timeout_msec_ = msec;
  11564. start_time_ = std::chrono::steady_clock::now();
  11565. }
  11566. inline void
  11567. SocketStream::set_read_interrupt(std::function<bool()> interrupted) {
  11568. read_interrupted_ = std::move(interrupted);
  11569. }
  11570. // Buffer stream implementation
  11571. inline bool BufferStream::is_readable() const { return true; }
  11572. inline bool BufferStream::wait_readable() const { return true; }
  11573. inline bool BufferStream::wait_writable() const { return true; }
  11574. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  11575. #if defined(_MSC_VER) && _MSC_VER < 1910
  11576. auto len_read = buffer._Copy_s(ptr, size, size, position);
  11577. #else
  11578. auto len_read = buffer.copy(ptr, size, position);
  11579. #endif
  11580. position += static_cast<size_t>(len_read);
  11581. return static_cast<ssize_t>(len_read);
  11582. }
  11583. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  11584. buffer.append(ptr, size);
  11585. return static_cast<ssize_t>(size);
  11586. }
  11587. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  11588. int & /*port*/) const {}
  11589. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  11590. int & /*port*/) const {}
  11591. inline socket_t BufferStream::socket() const { return 0; }
  11592. inline time_t BufferStream::duration() const { return 0; }
  11593. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  11594. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  11595. : MatcherBase(pattern) {
  11596. constexpr const char marker[] = "/:";
  11597. // One past the last ending position of a path param substring
  11598. std::size_t last_param_end = 0;
  11599. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11600. // Needed to ensure that parameter names are unique during matcher
  11601. // construction
  11602. // If exceptions are disabled, only last duplicate path
  11603. // parameter will be set
  11604. std::unordered_set<std::string> param_name_set;
  11605. #endif
  11606. while (true) {
  11607. const auto marker_pos = pattern.find(
  11608. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  11609. if (marker_pos == std::string::npos) { break; }
  11610. static_fragments_.push_back(
  11611. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  11612. const auto param_name_start = marker_pos + str_len(marker);
  11613. auto sep_pos = pattern.find(separator, param_name_start);
  11614. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  11615. auto param_name =
  11616. pattern.substr(param_name_start, sep_pos - param_name_start);
  11617. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11618. if (param_name_set.find(param_name) != param_name_set.cend()) {
  11619. std::string msg = "Encountered path parameter '" + param_name +
  11620. "' multiple times in route pattern '" + pattern + "'.";
  11621. throw std::invalid_argument(msg);
  11622. }
  11623. #endif
  11624. param_names_.push_back(std::move(param_name));
  11625. last_param_end = sep_pos + 1;
  11626. }
  11627. if (last_param_end < pattern.length()) {
  11628. static_fragments_.push_back(pattern.substr(last_param_end));
  11629. }
  11630. }
  11631. inline bool PathParamsMatcher::match(Request &request) const {
  11632. request.matches = std::smatch();
  11633. request.path_params.clear();
  11634. // A pattern without parameters is just a literal path to compare against
  11635. if (param_names_.empty()) { return request.path == pattern(); }
  11636. request.path_params.reserve(param_names_.size());
  11637. // One past the position at which the path matched the pattern last time
  11638. std::size_t starting_pos = 0;
  11639. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  11640. const auto &fragment = static_fragments_[i];
  11641. if (starting_pos + fragment.length() > request.path.length()) {
  11642. return false;
  11643. }
  11644. // Avoid unnecessary allocation by using strncmp instead of substr +
  11645. // comparison
  11646. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  11647. fragment.length()) != 0) {
  11648. return false;
  11649. }
  11650. starting_pos += fragment.length();
  11651. // Should only happen when we have a static fragment after a param
  11652. // Example: '/users/:id/subscriptions'
  11653. // The 'subscriptions' fragment here does not have a corresponding param
  11654. if (i >= param_names_.size()) { continue; }
  11655. auto sep_pos = request.path.find(separator, starting_pos);
  11656. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  11657. const auto &param_name = param_names_[i];
  11658. request.path_params.emplace(
  11659. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  11660. // Mark everything up to '/' as matched
  11661. starting_pos = sep_pos + 1;
  11662. }
  11663. // Returns false if the path is longer than the pattern
  11664. return starting_pos >= request.path.length();
  11665. }
  11666. inline bool RegexMatcher::match(Request &request) const {
  11667. request.path_params.clear();
  11668. // See CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH: an overlong path is treated as
  11669. // a non-match rather than risking a stack overflow in std::regex_match.
  11670. if (request.path.length() > CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH) {
  11671. return false;
  11672. }
  11673. return std::regex_match(request.path, request.matches, regex_);
  11674. }
  11675. // Enclose IPv6 address in brackets if needed
  11676. inline std::string prepare_host_string(const std::string &host) {
  11677. // Enclose IPv6 address in brackets (but not if already enclosed)
  11678. if (host.find(':') == std::string::npos ||
  11679. (!host.empty() && host[0] == '[')) {
  11680. // IPv4, hostname, or already bracketed IPv6
  11681. return host;
  11682. } else {
  11683. // IPv6 address without brackets
  11684. return "[" + host + "]";
  11685. }
  11686. }
  11687. inline std::string make_host_and_port_string(const std::string &host, int port,
  11688. bool is_ssl) {
  11689. auto result = prepare_host_string(host);
  11690. // Append port if not default
  11691. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  11692. ; // do nothing
  11693. } else {
  11694. result += ":" + std::to_string(port);
  11695. }
  11696. return result;
  11697. }
  11698. // Create "host:port" string always including port number (for CONNECT method)
  11699. inline std::string
  11700. make_host_and_port_string_always_port(const std::string &host, int port) {
  11701. return prepare_host_string(host) + ":" + std::to_string(port);
  11702. }
  11703. // Where a client connects for `host`, as one string: the mapped address or
  11704. // name, or `host` itself.
  11705. inline std::string
  11706. addr_map_target(const std::map<std::string, std::string> &addr_map,
  11707. const std::string &host) {
  11708. std::string connect_host;
  11709. std::string ip;
  11710. apply_addr_map(addr_map, host, connect_host, ip);
  11711. return ip.empty() ? connect_host : ip;
  11712. }
  11713. // Request target of a CONNECT for `host`, with `addr_map` applied.
  11714. inline std::string
  11715. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  11716. const std::string &host, int port) {
  11717. return make_host_and_port_string_always_port(addr_map_target(addr_map, host),
  11718. port);
  11719. }
  11720. // Value for the Host header a client sends when the caller supplied none.
  11721. // Only the value: callers decide where in their header list it goes.
  11722. inline std::string make_default_host_header_value(const std::string &host,
  11723. int port, bool is_ssl,
  11724. int address_family) {
  11725. if (address_family == AF_UNIX) { return "localhost"; }
  11726. return make_host_and_port_string(host, port, is_ssl);
  11727. }
  11728. inline void add_default_user_agent_header(Request &req) {
  11729. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11730. if (!req.has_header("User-Agent")) {
  11731. req.set_header("User-Agent",
  11732. std::string("cpp-httplib/") + CPPHTTPLIB_VERSION);
  11733. }
  11734. #else
  11735. (void)req;
  11736. #endif
  11737. }
  11738. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  11739. NormalizedTarget normalize_target(const std::string &host);
  11740. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  11741. bool host_matches_no_proxy(const NormalizedTarget &target,
  11742. const std::vector<NoProxyEntry> &entries);
  11743. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  11744. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  11745. if (prefix_bits == 0) { return true; }
  11746. int full_bytes = prefix_bits / 8;
  11747. int rem_bits = prefix_bits % 8;
  11748. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  11749. static_cast<size_t>(full_bytes)) != 0) {
  11750. return false;
  11751. }
  11752. if (rem_bits == 0) { return true; }
  11753. auto i = static_cast<size_t>(full_bytes);
  11754. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  11755. return (ip[i] & mask) == (net[i] & mask);
  11756. }
  11757. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  11758. if (token.empty()) { return false; }
  11759. if (token == "*") {
  11760. out.kind = NoProxyKind::Wildcard;
  11761. return true;
  11762. }
  11763. auto slash = token.find('/');
  11764. std::string addr_part =
  11765. (slash == std::string::npos) ? token : token.substr(0, slash);
  11766. std::string prefix_part =
  11767. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  11768. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  11769. // don't silently treat it as a /32 (or /128).
  11770. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  11771. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  11772. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  11773. // when brackets are present.
  11774. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  11775. addr_part.back() == ']';
  11776. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  11777. if (!bracketed) {
  11778. struct in_addr v4;
  11779. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  11780. int prefix = 32;
  11781. if (!prefix_part.empty() &&
  11782. !parse_int_in_range(prefix_part.data(), prefix_part.size(), 0, 32,
  11783. prefix)) {
  11784. return false;
  11785. }
  11786. out.kind = NoProxyKind::IPv4Cidr;
  11787. std::memcpy(out.net.data(), &v4, sizeof(v4));
  11788. out.prefix_bits = prefix;
  11789. return true;
  11790. }
  11791. }
  11792. struct in6_addr v6;
  11793. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  11794. int prefix = 128;
  11795. if (!prefix_part.empty() &&
  11796. !parse_int_in_range(prefix_part.data(), prefix_part.size(), 0, 128,
  11797. prefix)) {
  11798. return false;
  11799. }
  11800. out.kind = NoProxyKind::IPv6Cidr;
  11801. std::memcpy(out.net.data(), &v6, sizeof(v6));
  11802. out.prefix_bits = prefix;
  11803. return true;
  11804. }
  11805. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  11806. // the entry is malformed — don't fall through to the hostname branch.
  11807. if (bracketed) { return false; }
  11808. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  11809. if (slash != std::string::npos) { return false; }
  11810. // Port-specific entries (host:port) are not supported.
  11811. if (token.find(':') != std::string::npos) { return false; }
  11812. std::string hostname = case_ignore::to_lower(token);
  11813. while (!hostname.empty() && hostname.front() == '.') {
  11814. hostname.erase(hostname.begin());
  11815. }
  11816. while (!hostname.empty() && hostname.back() == '.') {
  11817. hostname.pop_back();
  11818. }
  11819. if (hostname.empty()) { return false; }
  11820. out.kind = NoProxyKind::HostnameSuffix;
  11821. out.hostname_pattern = std::move(hostname);
  11822. return true;
  11823. }
  11824. inline std::vector<NoProxyEntry>
  11825. parse_no_proxy_entries(const std::vector<std::string> &patterns) {
  11826. std::vector<NoProxyEntry> entries;
  11827. entries.reserve(patterns.size());
  11828. for (const auto &p : patterns) {
  11829. auto trimmed = trim_copy(p);
  11830. if (trimmed.empty()) { continue; }
  11831. NoProxyEntry entry;
  11832. if (parse_no_proxy_entry(trimmed, entry)) {
  11833. entries.push_back(std::move(entry));
  11834. }
  11835. }
  11836. return entries;
  11837. }
  11838. inline NormalizedTarget normalize_target(const std::string &host) {
  11839. NormalizedTarget t;
  11840. std::string h = host;
  11841. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  11842. h = h.substr(1, h.size() - 2);
  11843. }
  11844. // Strip a single trailing dot so "example.com." canonicalizes to
  11845. // "example.com".
  11846. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  11847. t.hostname = case_ignore::to_lower(h);
  11848. if (!t.hostname.empty()) {
  11849. struct in_addr v4;
  11850. struct in6_addr v6;
  11851. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  11852. t.is_ipv4 = true;
  11853. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  11854. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  11855. t.is_ipv6 = true;
  11856. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  11857. }
  11858. }
  11859. return t;
  11860. }
  11861. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  11862. const std::vector<NoProxyEntry> &entries) {
  11863. if (target.hostname.empty()) { return false; }
  11864. for (const auto &e : entries) {
  11865. switch (e.kind) {
  11866. case NoProxyKind::Wildcard: return true;
  11867. case NoProxyKind::IPv4Cidr:
  11868. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  11869. return true;
  11870. }
  11871. break;
  11872. case NoProxyKind::IPv6Cidr:
  11873. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  11874. return true;
  11875. }
  11876. break;
  11877. case NoProxyKind::HostnameSuffix:
  11878. if (target.is_ipv4 || target.is_ipv6) { break; }
  11879. if (target.hostname == e.hostname_pattern) { return true; }
  11880. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  11881. // an entry of "example.com".
  11882. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  11883. auto offset = target.hostname.size() - e.hostname_pattern.size();
  11884. if (target.hostname[offset - 1] == '.' &&
  11885. target.hostname.compare(offset, e.hostname_pattern.size(),
  11886. e.hostname_pattern) == 0) {
  11887. return true;
  11888. }
  11889. }
  11890. break;
  11891. }
  11892. }
  11893. return false;
  11894. }
  11895. template <typename T>
  11896. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  11897. T header_writer, Error &error) {
  11898. for (const auto &h : headers) {
  11899. if (!detail::fields::is_field_valid(h.first, h.second)) {
  11900. error = Error::InvalidHeaders;
  11901. return false;
  11902. }
  11903. }
  11904. if (header_writer(strm, headers) <= 0) {
  11905. error = Error::Write;
  11906. return false;
  11907. }
  11908. return true;
  11909. }
  11910. } // namespace detail
  11911. /*
  11912. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  11913. */
  11914. #ifdef CPPHTTPLIB_SSL_ENABLED
  11915. namespace detail {
  11916. // SSL socket stream implementation
  11917. inline SSLSocketStream::SSLSocketStream(
  11918. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  11919. time_t read_timeout_usec, time_t write_timeout_sec,
  11920. time_t write_timeout_usec, time_t max_timeout_msec,
  11921. std::chrono::time_point<std::chrono::steady_clock> start_time)
  11922. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  11923. read_timeout_usec_(read_timeout_usec),
  11924. write_timeout_sec_(write_timeout_sec),
  11925. write_timeout_usec_(write_timeout_usec),
  11926. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  11927. tls_error_.code = tls::ErrorCode::Success;
  11928. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11929. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  11930. // Note: create_session() also clears this, but SSLClient currently
  11931. // uses ssl_new() which does not. Until full TLS API migration is complete,
  11932. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  11933. // SSL session was created.
  11934. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  11935. #endif
  11936. }
  11937. inline SSLSocketStream::~SSLSocketStream() = default;
  11938. inline bool SSLSocketStream::is_readable() const {
  11939. return tls::pending(session_) > 0;
  11940. }
  11941. inline bool SSLSocketStream::wait_readable() const {
  11942. if (max_timeout_msec_ <= 0) {
  11943. return select_read_interruptible(sock_, read_timeout_sec_,
  11944. read_timeout_usec_, read_interrupted_) > 0;
  11945. }
  11946. time_t read_timeout_sec;
  11947. time_t read_timeout_usec;
  11948. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  11949. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  11950. return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
  11951. read_interrupted_) > 0;
  11952. }
  11953. inline bool SSLSocketStream::wait_writable() const {
  11954. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  11955. !tls::is_peer_closed(session_, sock_);
  11956. }
  11957. inline bool SSLSocketStream::ensure_readable() {
  11958. if (readable_hint_) {
  11959. readable_hint_ = false;
  11960. return true;
  11961. }
  11962. return wait_readable();
  11963. }
  11964. inline bool SSLSocketStream::is_peer_alive() const {
  11965. return !tls::is_peer_closed(session_, sock_);
  11966. }
  11967. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  11968. if (tls::pending(session_) > 0) {
  11969. tls::TlsError err;
  11970. auto ret = tls::read(session_, ptr, size, err);
  11971. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  11972. error_ = Error::ConnectionClosed;
  11973. } else if (ret < 0) {
  11974. tls_error_ = err;
  11975. }
  11976. return ret;
  11977. } else if (ensure_readable()) {
  11978. tls::TlsError err;
  11979. auto ret = tls::read(session_, ptr, size, err);
  11980. if (ret < 0) {
  11981. auto n = 1000;
  11982. #ifdef _WIN32
  11983. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  11984. (err.code == tls::ErrorCode::SyscallError &&
  11985. WSAGetLastError() == WSAETIMEDOUT))) {
  11986. #else
  11987. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  11988. #endif
  11989. if (tls::pending(session_) > 0) {
  11990. ret = tls::read(session_, ptr, size, err);
  11991. if (ret >= 0) { return ret; }
  11992. break;
  11993. } else if (wait_readable()) {
  11994. std::this_thread::sleep_for(std::chrono::microseconds{10});
  11995. ret = tls::read(session_, ptr, size, err);
  11996. if (ret >= 0) { return ret; }
  11997. } else {
  11998. break;
  11999. }
  12000. }
  12001. assert(ret < 0);
  12002. tls_error_ = err;
  12003. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  12004. error_ = Error::ConnectionClosed;
  12005. }
  12006. return ret;
  12007. } else {
  12008. error_ = Error::Timeout;
  12009. return -1;
  12010. }
  12011. }
  12012. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  12013. if (wait_writable()) {
  12014. auto handle_size =
  12015. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  12016. tls::TlsError err;
  12017. auto ret = tls::write(session_, ptr, handle_size, err);
  12018. if (ret < 0) {
  12019. auto n = 1000;
  12020. #ifdef _WIN32
  12021. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  12022. (err.code == tls::ErrorCode::SyscallError &&
  12023. WSAGetLastError() == WSAETIMEDOUT))) {
  12024. #else
  12025. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  12026. #endif
  12027. if (wait_writable()) {
  12028. std::this_thread::sleep_for(std::chrono::microseconds{10});
  12029. ret = tls::write(session_, ptr, handle_size, err);
  12030. if (ret >= 0) { return ret; }
  12031. } else {
  12032. break;
  12033. }
  12034. }
  12035. assert(ret < 0);
  12036. tls_error_ = err;
  12037. }
  12038. return ret;
  12039. }
  12040. return -1;
  12041. }
  12042. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  12043. int &port) const {
  12044. detail::get_remote_ip_and_port(sock_, ip, port);
  12045. }
  12046. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  12047. int &port) const {
  12048. detail::get_local_ip_and_port(sock_, ip, port);
  12049. }
  12050. inline socket_t SSLSocketStream::socket() const { return sock_; }
  12051. inline time_t SSLSocketStream::duration() const {
  12052. return static_cast<time_t>(
  12053. std::chrono::duration_cast<std::chrono::milliseconds>(
  12054. std::chrono::steady_clock::now() - start_time_)
  12055. .count());
  12056. }
  12057. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  12058. read_timeout_sec_ = sec;
  12059. read_timeout_usec_ = usec;
  12060. }
  12061. inline void SSLSocketStream::set_max_timeout(time_t msec) {
  12062. max_timeout_msec_ = msec;
  12063. start_time_ = std::chrono::steady_clock::now();
  12064. }
  12065. inline void
  12066. SSLSocketStream::set_read_interrupt(std::function<bool()> interrupted) {
  12067. read_interrupted_ = std::move(interrupted);
  12068. }
  12069. inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
  12070. tls::session_t session,
  12071. time_t read_timeout_sec,
  12072. time_t read_timeout_usec,
  12073. time_t write_timeout_sec,
  12074. time_t write_timeout_usec)
  12075. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  12076. read_timeout_usec_(read_timeout_usec),
  12077. write_timeout_sec_(write_timeout_sec),
  12078. write_timeout_usec_(write_timeout_usec),
  12079. start_time_(std::chrono::steady_clock::now().time_since_epoch().count()) {
  12080. // The receive and send paths run on different threads, so each TLS call is
  12081. // driven in non-blocking mode and readiness is awaited with select()
  12082. // outside the session lock. Set the socket non-blocking once here; it is
  12083. // never flipped back, so no thread races on the flag.
  12084. detail::set_nonblocking(sock_, true);
  12085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12086. SSL_clear_mode(static_cast<SSL *>(session_), SSL_MODE_AUTO_RETRY);
  12087. #endif
  12088. }
  12089. inline WebSocketSSLStream::~WebSocketSSLStream() = default;
  12090. inline bool WebSocketSSLStream::is_readable() const {
  12091. std::lock_guard<std::mutex> guard(session_mutex_);
  12092. return tls::pending(session_) > 0;
  12093. }
  12094. inline bool WebSocketSSLStream::wait_readable() const {
  12095. auto max_timeout_msec = max_timeout_msec_.load();
  12096. if (max_timeout_msec <= 0) {
  12097. return select_read_interruptible(sock_, read_timeout_sec_,
  12098. read_timeout_usec_, read_interrupted_) > 0;
  12099. }
  12100. time_t read_timeout_sec;
  12101. time_t read_timeout_usec;
  12102. calc_actual_timeout(max_timeout_msec, duration(), read_timeout_sec_,
  12103. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  12104. return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
  12105. read_interrupted_) > 0;
  12106. }
  12107. inline bool WebSocketSSLStream::wait_writable() const {
  12108. // Unlike SSLSocketStream, this deliberately does not call is_peer_closed():
  12109. // that probe toggles the socket's blocking flag, which would race with the
  12110. // concurrent reader on a permanently non-blocking socket.
  12111. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  12112. }
  12113. inline ssize_t WebSocketSSLStream::read(char *ptr, size_t size) {
  12114. tls::TlsError err;
  12115. auto n = 1000;
  12116. while (--n >= 0) {
  12117. {
  12118. std::lock_guard<std::mutex> guard(session_mutex_);
  12119. auto ret = tls::read(session_, ptr, size, err);
  12120. if (ret > 0) { return ret; }
  12121. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  12122. error_ = Error::ConnectionClosed;
  12123. return ret;
  12124. }
  12125. }
  12126. // ret < 0. On a non-blocking socket a TLS read can stop needing either
  12127. // direction: the send path shares this session, so output it left pending
  12128. // has to be flushed before more input can be decrypted. Anything else is
  12129. // a hard error.
  12130. auto needs_readable = err.code == tls::ErrorCode::WantRead;
  12131. #ifdef _WIN32
  12132. // On Windows a socket timeout surfaces as a syscall error, not WantRead.
  12133. needs_readable =
  12134. needs_readable || (err.code == tls::ErrorCode::SyscallError &&
  12135. WSAGetLastError() == WSAETIMEDOUT);
  12136. #endif
  12137. if (!needs_readable && err.code != tls::ErrorCode::WantWrite) {
  12138. error_ = Error::Read;
  12139. return -1;
  12140. }
  12141. if (!(needs_readable ? wait_readable() : wait_writable())) {
  12142. error_ = Error::Timeout;
  12143. return -1;
  12144. }
  12145. }
  12146. // Out of retries. Recording a reason matters: a caller that reads get_error()
  12147. // to tell a timeout from a close would otherwise see whatever the previous
  12148. // failure left behind (error_ is never cleared on success).
  12149. error_ = Error::Read;
  12150. return -1;
  12151. }
  12152. inline ssize_t WebSocketSSLStream::write(const char *ptr, size_t size) {
  12153. auto handle_size = std::min<size_t>(size, (std::numeric_limits<int>::max)());
  12154. tls::TlsError err;
  12155. auto n = 1000;
  12156. while (--n >= 0) {
  12157. {
  12158. std::lock_guard<std::mutex> guard(session_mutex_);
  12159. auto ret = tls::write(session_, ptr, handle_size, err);
  12160. if (ret >= 0) { return ret; }
  12161. }
  12162. // ret < 0. As in read(), either direction can be needed: a renegotiation
  12163. // or a post-handshake message must be consumed before the record goes
  12164. // out. Anything else is a hard error.
  12165. auto needs_writable = err.code == tls::ErrorCode::WantWrite;
  12166. #ifdef _WIN32
  12167. // On Windows a socket timeout surfaces as a syscall error, not WantWrite.
  12168. needs_writable =
  12169. needs_writable || (err.code == tls::ErrorCode::SyscallError &&
  12170. WSAGetLastError() == WSAETIMEDOUT);
  12171. #endif
  12172. if (!needs_writable && err.code != tls::ErrorCode::WantRead) { return -1; }
  12173. if (!(needs_writable ? wait_writable() : wait_readable())) { return -1; }
  12174. }
  12175. return -1;
  12176. }
  12177. inline void WebSocketSSLStream::get_remote_ip_and_port(std::string &ip,
  12178. int &port) const {
  12179. detail::get_remote_ip_and_port(sock_, ip, port);
  12180. }
  12181. inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
  12182. int &port) const {
  12183. detail::get_local_ip_and_port(sock_, ip, port);
  12184. }
  12185. inline socket_t WebSocketSSLStream::socket() const { return sock_; }
  12186. inline time_t WebSocketSSLStream::duration() const {
  12187. auto start = std::chrono::steady_clock::time_point(
  12188. std::chrono::steady_clock::duration(start_time_.load()));
  12189. return static_cast<time_t>(
  12190. std::chrono::duration_cast<std::chrono::milliseconds>(
  12191. std::chrono::steady_clock::now() - start)
  12192. .count());
  12193. }
  12194. // Start time first: a reader that sees the new bound also sees its start
  12195. inline void WebSocketSSLStream::set_max_timeout(time_t msec) {
  12196. start_time_ = std::chrono::steady_clock::now().time_since_epoch().count();
  12197. max_timeout_msec_ = msec;
  12198. }
  12199. inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
  12200. read_timeout_sec_ = sec;
  12201. read_timeout_usec_ = usec;
  12202. }
  12203. inline void
  12204. WebSocketSSLStream::set_read_interrupt(std::function<bool()> interrupted) {
  12205. read_interrupted_ = std::move(interrupted);
  12206. }
  12207. } // namespace detail
  12208. #endif // CPPHTTPLIB_SSL_ENABLED
  12209. /*
  12210. * Group 4: Server implementation
  12211. */
  12212. // A kept-alive connection that the event loop of set_keep_alive_parking()
  12213. // owns while it is idle, and a worker owns while it serves a request. A
  12214. // derived class adds the transport: the stream, and for TLS the session.
  12215. struct Server::KeepAliveConnection {
  12216. KeepAliveConnection(socket_t s, Server &server) : svr(server), sock(s) {}
  12217. // Every owner closes it before letting go, which the transport hooks need;
  12218. // this is only a net, which cannot reach them any more.
  12219. virtual ~KeepAliveConnection() {
  12220. if (sock != INVALID_SOCKET) { detail::drain_and_close_socket(sock, 0); }
  12221. }
  12222. // On a worker before the first request, e.g. for a TLS handshake. False
  12223. // closes the connection. One that reads from the socket clears turn.woken.
  12224. virtual bool open() { return true; }
  12225. // Serves requests while they come: serve_on() with the transport's stream.
  12226. virtual bool serve() = 0;
  12227. // Before it is parked. Nothing is buffered then.
  12228. virtual void release_buffers() {}
  12229. // Before the socket of an open connection is closed, e.g. to send TLS
  12230. // close_notify.
  12231. virtual void shut_down(bool /*graceful*/) {}
  12232. // On a worker, once the event loop has seen the socket readable. Afterwards
  12233. // turn.park tells whether it may be parked again.
  12234. bool resume() {
  12235. turn = Turn();
  12236. return svr.serve_guarded([this]() {
  12237. if (!opened) {
  12238. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  12239. detail::get_local_ip_and_port(sock, local_addr, local_port);
  12240. if (!open()) { return false; }
  12241. opened = true;
  12242. }
  12243. return serve();
  12244. });
  12245. }
  12246. // From the event loop, which must not wait for the peer.
  12247. void close_idle() {
  12248. assert(sock != INVALID_SOCKET);
  12249. if (opened) {
  12250. detail::set_nonblocking(sock, true);
  12251. shut_down(true);
  12252. }
  12253. detail::drain_and_close_socket(sock, 0);
  12254. sock = INVALID_SOCKET;
  12255. }
  12256. // From the worker that served it.
  12257. void close_served(bool graceful) {
  12258. assert(sock != INVALID_SOCKET);
  12259. if (opened) {
  12260. shut_down(graceful);
  12261. detail::drain_and_close_socket(sock);
  12262. } else {
  12263. // It never got as far as a request, e.g. a failed TLS handshake.
  12264. detail::shutdown_socket(sock);
  12265. detail::close_socket(sock);
  12266. }
  12267. sock = INVALID_SOCKET;
  12268. }
  12269. template <typename S>
  12270. bool serve_on(S &strm,
  12271. const std::function<void(Request &)> &setup_request = nullptr) {
  12272. return detail::process_server_socket_core(
  12273. strm, served, svr.keep_alive_max_count_,
  12274. [this]() { return wait_for_next_request(); },
  12275. [&](Stream &s, bool close_connection, bool &connection_closed) {
  12276. return svr.process_request(s, remote_addr, remote_port, local_addr,
  12277. local_port, close_connection,
  12278. connection_closed, setup_request,
  12279. &turn.websocket_upgraded);
  12280. });
  12281. }
  12282. bool wait_for_next_request() {
  12283. // The event loop saw the socket readable just before this ran.
  12284. if (turn.woken) {
  12285. turn.woken = false;
  12286. return true;
  12287. }
  12288. if (svr.is_stopping()) { return false; }
  12289. // Waiting here for a slow client would keep the worker from others.
  12290. turn.park = detail::select_read(sock, 0, 0) <= 0;
  12291. return !turn.park;
  12292. }
  12293. // A worker's time with it, from resume() until it is parked or closed.
  12294. struct Turn {
  12295. bool woken = true;
  12296. bool park = false;
  12297. bool websocket_upgraded = false;
  12298. };
  12299. Server &svr;
  12300. socket_t sock;
  12301. int remote_port = 0;
  12302. int local_port = 0;
  12303. bool opened = false; // by resume(), once open() has succeeded
  12304. Turn turn;
  12305. size_t served = 0;
  12306. std::string remote_addr;
  12307. std::string local_addr;
  12308. // While parked
  12309. std::list<std::shared_ptr<KeepAliveConnection>>::iterator parked_at;
  12310. std::chrono::steady_clock::time_point deadline;
  12311. };
  12312. struct Server::PlainConnection final : Server::KeepAliveConnection {
  12313. PlainConnection(socket_t s, Server &server)
  12314. : KeepAliveConnection(s, server),
  12315. strm(s, server.read_timeout_sec_, server.read_timeout_usec_,
  12316. server.write_timeout_sec_, server.write_timeout_usec_) {}
  12317. bool serve() override { return serve_on(strm); }
  12318. void release_buffers() override { strm.release_buffer(); }
  12319. // Kept across requests: it may hold the start of a pipelined request.
  12320. detail::SocketStream strm;
  12321. };
  12322. struct Server::ParkingState {
  12323. using Clock = std::chrono::steady_clock;
  12324. using Token = detail::Poller::Token;
  12325. using Connection = std::shared_ptr<KeepAliveConnection>;
  12326. // Kept for the Server's life, so that stop() can wake() it without a lock.
  12327. std::unique_ptr<detail::Poller> poller;
  12328. // The listening socket while parking_loop() watches it. Whichever of stop()
  12329. // and parking_loop() takes it out of here decides who closes it, so that it
  12330. // is never closed while the poller still watches it.
  12331. std::atomic<socket_t> listen_sock{INVALID_SOCKET};
  12332. // From stop(): whether parking_loop() takes over closing `sock`.
  12333. bool release_listen(socket_t sock) {
  12334. if (!listen_sock.compare_exchange_strong(sock, INVALID_SOCKET)) {
  12335. return false;
  12336. }
  12337. poller->wake();
  12338. return true;
  12339. }
  12340. // From a worker: hands an idle connection back, unless the loop has ended.
  12341. bool give_back(Connection conn) {
  12342. {
  12343. std::lock_guard<std::mutex> guard(mutex);
  12344. if (closed) { return false; }
  12345. returned.push_back(std::move(conn));
  12346. }
  12347. poller->wake();
  12348. return true;
  12349. }
  12350. // The rest belongs to parking_loop(). A parked connection's token is its
  12351. // address, and `parked` lists them in the order they expire.
  12352. // Closes it and returns false when the poller cannot watch it: unwatched,
  12353. // it would only wait for its deadline.
  12354. bool park(Connection conn, Clock::time_point deadline) {
  12355. auto &c = *conn;
  12356. c.deadline = deadline;
  12357. c.parked_at = parked.insert(parked.end(), std::move(conn));
  12358. if (poller->arm(c.sock, reinterpret_cast<Token>(&c))) { return true; }
  12359. unpark(reinterpret_cast<Token>(&c))->close_idle();
  12360. return false;
  12361. }
  12362. Connection unpark(Token token) {
  12363. auto &c = *reinterpret_cast<KeepAliveConnection *>(token);
  12364. auto conn = std::move(*c.parked_at);
  12365. parked.erase(c.parked_at);
  12366. return conn;
  12367. }
  12368. Clock::time_point next_deadline() const {
  12369. return parked.empty() ? (Clock::time_point::max)()
  12370. : parked.front()->deadline;
  12371. }
  12372. void expire(Clock::time_point now) {
  12373. while (!parked.empty() && parked.front()->deadline <= now) {
  12374. poller->disarm(parked.front()->sock);
  12375. parked.front()->close_idle();
  12376. parked.pop_front();
  12377. }
  12378. }
  12379. // Closes them here rather than wherever the last reference goes, which may
  12380. // be a worker that has just given one back, or the destructor, which cannot
  12381. // reach the transport.
  12382. void close_all() {
  12383. std::vector<Connection> left;
  12384. {
  12385. std::lock_guard<std::mutex> guard(mutex);
  12386. closed = true;
  12387. left.swap(returned);
  12388. }
  12389. for (auto &conn : parked) {
  12390. poller->disarm(conn->sock);
  12391. conn->close_idle();
  12392. }
  12393. for (auto &conn : left) {
  12394. conn->close_idle();
  12395. }
  12396. for (auto &conn : backlog) {
  12397. conn->close_idle();
  12398. }
  12399. parked.clear();
  12400. backlog.clear();
  12401. }
  12402. std::mutex mutex;
  12403. std::vector<Connection> returned;
  12404. bool closed = false;
  12405. std::list<Connection> parked;
  12406. std::list<Connection> backlog;
  12407. };
  12408. // HTTP server implementation
  12409. inline Server::Server()
  12410. : new_task_queue([] {
  12411. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  12412. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  12413. }) {
  12414. #ifndef _WIN32
  12415. signal(SIGPIPE, SIG_IGN);
  12416. #endif
  12417. set_keep_alive_parking(CPPHTTPLIB_KEEPALIVE_PARKING);
  12418. }
  12419. inline Server::~Server() = default;
  12420. inline std::unique_ptr<detail::MatcherBase>
  12421. Server::make_matcher(const std::string &pattern) {
  12422. // Path params take precedence, so "/users/:id/(.*)" keeps being matched as
  12423. // a path params pattern
  12424. if (pattern.find("/:") != std::string::npos) {
  12425. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  12426. }
  12427. // A pattern with no regex metacharacter only has to be compared literally,
  12428. // which is what PathParamsMatcher already does when it captures no
  12429. // parameter, so std::regex is only worth building for the patterns that
  12430. // actually need it
  12431. if (pattern.find_first_of(".^$|()[]{}*+?\\") == std::string::npos) {
  12432. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  12433. }
  12434. return detail::make_unique<detail::RegexMatcher>(pattern);
  12435. }
  12436. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  12437. return add_handler(get_handlers_, pattern, std::move(handler));
  12438. }
  12439. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  12440. return add_handler(post_handlers_, pattern, std::move(handler));
  12441. }
  12442. inline Server &Server::Post(const std::string &pattern,
  12443. HandlerWithContentReader handler) {
  12444. return add_handler(post_handlers_for_content_reader_, pattern,
  12445. std::move(handler));
  12446. }
  12447. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  12448. return add_handler(put_handlers_, pattern, std::move(handler));
  12449. }
  12450. inline Server &Server::Put(const std::string &pattern,
  12451. HandlerWithContentReader handler) {
  12452. return add_handler(put_handlers_for_content_reader_, pattern,
  12453. std::move(handler));
  12454. }
  12455. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  12456. return add_handler(patch_handlers_, pattern, std::move(handler));
  12457. }
  12458. inline Server &Server::Patch(const std::string &pattern,
  12459. HandlerWithContentReader handler) {
  12460. return add_handler(patch_handlers_for_content_reader_, pattern,
  12461. std::move(handler));
  12462. }
  12463. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  12464. return add_handler(delete_handlers_, pattern, std::move(handler));
  12465. }
  12466. inline Server &Server::Delete(const std::string &pattern,
  12467. HandlerWithContentReader handler) {
  12468. return add_handler(delete_handlers_for_content_reader_, pattern,
  12469. std::move(handler));
  12470. }
  12471. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  12472. return add_handler(options_handlers_, pattern, std::move(handler));
  12473. }
  12474. inline const std::set<std::string> &Server::builtin_methods() {
  12475. thread_local const std::set<std::string> methods{
  12476. "GET", "HEAD", "POST", "PUT", "DELETE",
  12477. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  12478. return methods;
  12479. }
  12480. inline Server::CustomHandlerEntry *
  12481. Server::custom_entry_for_registration(const std::string &method) {
  12482. // Built-in methods are refused for two different reasons. GET, HEAD, POST,
  12483. // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
  12484. // routing() before the custom tables are consulted, so a route registered
  12485. // for one of them could never fire. CONNECT, TRACE and PRI have no branch
  12486. // there and would be reachable, but they carry protocol-level meaning
  12487. // (tunnel setup, request echo, the HTTP/2 connection preface) that this
  12488. // library does not route.
  12489. if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
  12490. output_error_log(Error::InvalidHTTPMethod, nullptr);
  12491. has_invalid_registration_ = true;
  12492. return nullptr;
  12493. }
  12494. return &custom_handlers_[method];
  12495. }
  12496. inline Server &Server::CustomRoute(const std::string &method,
  12497. const std::string &pattern,
  12498. Handler handler) {
  12499. auto *entry = custom_entry_for_registration(method);
  12500. if (!entry) { return *this; }
  12501. return add_handler(entry->handlers, pattern, std::move(handler));
  12502. }
  12503. inline Server &Server::CustomRoute(const std::string &method,
  12504. const std::string &pattern,
  12505. HandlerWithContentReader handler) {
  12506. auto *entry = custom_entry_for_registration(method);
  12507. if (!entry) { return *this; }
  12508. return add_handler(entry->handlers_for_content_reader, pattern,
  12509. std::move(handler));
  12510. }
  12511. inline const Server::CustomHandlerEntry *
  12512. Server::find_custom_entry(const std::string &method) const {
  12513. // find() alone would be correct here. The empty() check is what keeps the
  12514. // per-request cost off servers that never call CustomRoute(), which is the
  12515. // overwhelmingly common case; keep it rather than walking into the tree.
  12516. if (custom_handlers_.empty()) { return nullptr; }
  12517. auto it = custom_handlers_.find(method);
  12518. return it == custom_handlers_.end() ? nullptr : &it->second;
  12519. }
  12520. inline Server &Server::WebSocket(const std::string &pattern,
  12521. WebSocketHandler handler) {
  12522. websocket_handlers_.push_back(
  12523. {make_matcher(pattern), std::move(handler), nullptr});
  12524. return *this;
  12525. }
  12526. inline Server &Server::WebSocket(const std::string &pattern,
  12527. WebSocketHandler handler,
  12528. SubProtocolSelector sub_protocol_selector) {
  12529. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  12530. std::move(sub_protocol_selector)});
  12531. return *this;
  12532. }
  12533. inline bool Server::set_base_dir(const std::string &dir,
  12534. const std::string &mount_point) {
  12535. return set_mount_point(mount_point, dir);
  12536. }
  12537. inline bool Server::set_mount_point(const std::string &mount_point,
  12538. const std::string &dir, Headers headers) {
  12539. detail::FileStat stat(dir);
  12540. if (stat.is_dir()) {
  12541. std::string mnt = !mount_point.empty() ? mount_point : "/";
  12542. if (!mnt.empty() && mnt[0] == '/') {
  12543. // Without the resolved directory, a file could not be checked to be
  12544. // inside it.
  12545. std::string resolved_base;
  12546. if (!detail::canonicalize_path(dir.c_str(), resolved_base)) {
  12547. return false;
  12548. }
  12549. #if defined(_WIN32)
  12550. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  12551. resolved_base += '\\';
  12552. }
  12553. #else
  12554. if (resolved_base.back() != '/') { resolved_base += '/'; }
  12555. #endif
  12556. base_dirs_.push_back(
  12557. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  12558. return true;
  12559. }
  12560. }
  12561. return false;
  12562. }
  12563. inline bool Server::remove_mount_point(const std::string &mount_point) {
  12564. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  12565. if (it->mount_point == mount_point) {
  12566. base_dirs_.erase(it);
  12567. return true;
  12568. }
  12569. }
  12570. return false;
  12571. }
  12572. inline Server &
  12573. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  12574. const std::string &mime) {
  12575. // Keyed as find_content_type() looks it up
  12576. auto key = detail::case_ignore::to_lower(ext);
  12577. if (!key.empty() && key[0] == '.') { key.erase(0, 1); }
  12578. file_extension_and_mimetype_map_[key] = mime;
  12579. return *this;
  12580. }
  12581. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  12582. default_file_mimetype_ = mime;
  12583. return *this;
  12584. }
  12585. inline Server &Server::set_file_request_handler(Handler handler) {
  12586. file_request_handler_ = std::move(handler);
  12587. return *this;
  12588. }
  12589. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  12590. std::true_type) {
  12591. error_handler_ = std::move(handler);
  12592. return *this;
  12593. }
  12594. inline Server &Server::set_error_handler_core(Handler handler,
  12595. std::false_type) {
  12596. error_handler_ = [handler](const Request &req, Response &res) {
  12597. handler(req, res);
  12598. return HandlerResponse::Handled;
  12599. };
  12600. return *this;
  12601. }
  12602. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  12603. exception_handler_ = std::move(handler);
  12604. return *this;
  12605. }
  12606. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  12607. pre_routing_handler_ = std::move(handler);
  12608. return *this;
  12609. }
  12610. inline Server &Server::set_post_routing_handler(Handler handler) {
  12611. post_routing_handler_ = std::move(handler);
  12612. return *this;
  12613. }
  12614. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  12615. pre_request_handler_ = std::move(handler);
  12616. return *this;
  12617. }
  12618. inline Server &Server::set_logger(Logger logger) {
  12619. logger_ = std::move(logger);
  12620. return *this;
  12621. }
  12622. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  12623. error_logger_ = std::move(error_logger);
  12624. return *this;
  12625. }
  12626. inline Server &Server::set_pre_compression_logger(Logger logger) {
  12627. pre_compression_logger_ = std::move(logger);
  12628. return *this;
  12629. }
  12630. inline Server &
  12631. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  12632. expect_100_continue_handler_ = std::move(handler);
  12633. return *this;
  12634. }
  12635. inline Server &Server::set_start_handler(StartHandler handler) {
  12636. start_handler_ = std::move(handler);
  12637. return *this;
  12638. }
  12639. inline Server &Server::set_address_family(int family) {
  12640. address_family_ = family;
  12641. return *this;
  12642. }
  12643. inline Server &Server::set_tcp_nodelay(bool on) {
  12644. tcp_nodelay_ = on;
  12645. return *this;
  12646. }
  12647. inline Server &Server::set_ipv6_v6only(bool on) {
  12648. ipv6_v6only_ = on;
  12649. return *this;
  12650. }
  12651. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  12652. socket_options_ = std::move(socket_options);
  12653. return *this;
  12654. }
  12655. inline Server &Server::set_default_headers(Headers headers) {
  12656. default_headers_ = std::move(headers);
  12657. return *this;
  12658. }
  12659. inline Server &Server::set_header_writer(
  12660. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12661. header_writer_ = writer;
  12662. return *this;
  12663. }
  12664. inline Server &
  12665. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  12666. trusted_proxies_.clear();
  12667. trusted_proxies_.reserve(proxies.size());
  12668. for (const auto &proxy : proxies) {
  12669. trusted_proxies_.push_back(detail::canonical_ip(proxy));
  12670. }
  12671. return *this;
  12672. }
  12673. inline Server &Server::set_keep_alive_max_count(size_t count) {
  12674. keep_alive_max_count_ = count;
  12675. return *this;
  12676. }
  12677. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  12678. keep_alive_timeout_sec_ = sec;
  12679. return *this;
  12680. }
  12681. template <class Rep, class Period>
  12682. inline Server &Server::set_keep_alive_timeout(
  12683. const std::chrono::duration<Rep, Period> &duration) {
  12684. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  12685. set_keep_alive_timeout(sec);
  12686. });
  12687. return *this;
  12688. }
  12689. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  12690. read_timeout_sec_ = sec;
  12691. read_timeout_usec_ = usec;
  12692. return *this;
  12693. }
  12694. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  12695. write_timeout_sec_ = sec;
  12696. write_timeout_usec_ = usec;
  12697. return *this;
  12698. }
  12699. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  12700. idle_interval_sec_ = sec;
  12701. idle_interval_usec_ = usec;
  12702. idle_interval_set_ = true;
  12703. return *this;
  12704. }
  12705. inline Server &Server::set_keep_alive_parking(bool on) {
  12706. // Never destroyed once made: stop() may use it from another thread.
  12707. if (on && !parking_) {
  12708. auto poller = detail::make_poller();
  12709. if (poller) {
  12710. parking_.reset(new ParkingState());
  12711. parking_->poller = std::move(poller);
  12712. }
  12713. }
  12714. keep_alive_parking_ = on;
  12715. return *this;
  12716. }
  12717. inline Server &Server::set_payload_max_length(size_t length) {
  12718. payload_max_length_ = length;
  12719. return *this;
  12720. }
  12721. inline Server &Server::set_compress(bool on) {
  12722. compress_ = on;
  12723. return *this;
  12724. }
  12725. inline Server &Server::set_static_file_compression(bool on) {
  12726. static_file_compression_ = on;
  12727. return *this;
  12728. }
  12729. inline Server &Server::set_static_file_compression_min_length(size_t length) {
  12730. static_file_compression_min_length_ = length;
  12731. return *this;
  12732. }
  12733. inline Server &Server::set_static_file_compression_max_length(size_t length) {
  12734. static_file_compression_max_length_ = length;
  12735. return *this;
  12736. }
  12737. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  12738. websocket_max_missed_pongs_ = count;
  12739. return *this;
  12740. }
  12741. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  12742. websocket_ping_interval_sec_ = sec;
  12743. return *this;
  12744. }
  12745. template <class Rep, class Period>
  12746. inline Server &Server::set_websocket_ping_interval(
  12747. const std::chrono::duration<Rep, Period> &duration) {
  12748. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  12749. set_websocket_ping_interval(sec);
  12750. });
  12751. return *this;
  12752. }
  12753. inline bool Server::bind_to_port(const std::string &host, int port,
  12754. int socket_flags) {
  12755. auto ret = bind_internal(host, port, socket_flags);
  12756. if (ret == -1) { is_decommissioned = true; }
  12757. return ret >= 0;
  12758. }
  12759. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  12760. auto ret = bind_internal(host, 0, socket_flags);
  12761. if (ret == -1) { is_decommissioned = true; }
  12762. return ret;
  12763. }
  12764. inline bool Server::listen_after_bind() { return listen_internal(); }
  12765. inline bool Server::listen(const std::string &host, int port,
  12766. int socket_flags) {
  12767. return bind_to_port(host, port, socket_flags) && listen_internal();
  12768. }
  12769. inline bool Server::is_running() const { return is_running_; }
  12770. inline void Server::wait_until_ready() const {
  12771. while (!is_running_ && !is_decommissioned) {
  12772. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  12773. }
  12774. }
  12775. inline void Server::stop() noexcept {
  12776. // Release the listening socket whether or not the accept loop is running:
  12777. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  12778. // exchange is what makes this safe to call concurrently with the accept loop.
  12779. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  12780. if (sock != INVALID_SOCKET && !(parking_ && parking_->release_listen(sock))) {
  12781. detail::shutdown_socket(sock);
  12782. detail::close_socket(sock);
  12783. }
  12784. is_decommissioned = false;
  12785. }
  12786. inline void Server::decommission() { is_decommissioned = true; }
  12787. inline bool Server::parse_request_line(const char *s, Request &req) const {
  12788. auto len = strlen(s);
  12789. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  12790. len -= 2;
  12791. {
  12792. // RFC 9112 §3: exactly one SP between the method, the target and the
  12793. // version. Taking other whitespace as a separator too lets recipients
  12794. // that parse more strictly see a different request.
  12795. auto end = s + len;
  12796. if (std::count(s, end, ' ') != 2) { return false; }
  12797. auto sp1 = std::find(s, end, ' ');
  12798. auto sp2 = std::find(sp1 + 1, end, ' ');
  12799. if (sp1 == s || sp2 == sp1 + 1 || sp2 + 1 == end) { return false; }
  12800. req.method.assign(s, sp1);
  12801. req.target.assign(sp1 + 1, sp2);
  12802. req.version.assign(sp2 + 1, end);
  12803. }
  12804. // A method outside the built-in set is accepted only when a handler has been
  12805. // registered for it with CustomRoute().
  12806. const auto &methods = builtin_methods();
  12807. if (methods.find(req.method) == methods.end() &&
  12808. !find_custom_entry(req.method)) {
  12809. output_error_log(Error::InvalidHTTPMethod, &req);
  12810. return false;
  12811. }
  12812. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  12813. output_error_log(Error::InvalidHTTPVersion, &req);
  12814. return false;
  12815. }
  12816. // A request-target has no fragment (RFC 9112 §3.2), and one stripped here
  12817. // would leave this server routing a different path than a cache or a
  12818. // filter in front of it sees.
  12819. if (!detail::fields::is_request_target(req.target) ||
  12820. req.target.find('#') != std::string::npos) {
  12821. return false;
  12822. }
  12823. {
  12824. detail::divide(req.target, '?',
  12825. [&](const char *lhs_data, std::size_t lhs_size,
  12826. const char *rhs_data, std::size_t rhs_size) {
  12827. req.path =
  12828. decode_path_component(std::string(lhs_data, lhs_size));
  12829. detail::parse_query_text(rhs_data, rhs_size, req.params);
  12830. });
  12831. }
  12832. return true;
  12833. }
  12834. inline bool Server::write_response(Stream &strm, bool close_connection,
  12835. Request &req, Response &res) {
  12836. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  12837. // incorrectly to the error content.
  12838. req.ranges.clear();
  12839. return write_response_core(strm, close_connection, req, res, false);
  12840. }
  12841. inline bool Server::write_response_with_content(Stream &strm,
  12842. bool close_connection,
  12843. const Request &req,
  12844. Response &res) {
  12845. return write_response_core(strm, close_connection, req, res, true);
  12846. }
  12847. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  12848. const Request &req, Response &res,
  12849. bool need_apply_ranges) {
  12850. assert(res.status != -1);
  12851. if (400 <= res.status && error_handler_ &&
  12852. error_handler_(req, res) == HandlerResponse::Handled) {
  12853. need_apply_ranges = true;
  12854. }
  12855. // Before anything below reads res.headers, which the handlers may have
  12856. // filled directly
  12857. detail::erase_invalid_fields(res.headers);
  12858. if (!detail::body_allowed_for_status(res.status)) {
  12859. detail::clear_content(res);
  12860. }
  12861. detail::prefer_assigned_body(res);
  12862. std::string content_type;
  12863. std::string boundary;
  12864. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  12865. // Prepare additional headers
  12866. if (close_connection ||
  12867. detail::has_header_token(req.headers, "Connection", "close") ||
  12868. 400 <= res.status || // Don't leave connections open after errors
  12869. // The client withholds the body until `100 Continue`, which was never
  12870. // sent, so whether and when the body follows is unknown.
  12871. (req.expect_100_continue_pending_ && detail::has_framed_body(req)) ||
  12872. // The body was left partway, e.g. by a content receiver that returned
  12873. // false, so the rest of it cannot be told from the next request.
  12874. (req.body_read_started_ && !req.body_consumed_)) {
  12875. res.set_header("Connection", "close");
  12876. } else {
  12877. std::string s = "timeout=";
  12878. s += std::to_string(keep_alive_timeout_sec_);
  12879. if (keep_alive_max_count_ > 0) {
  12880. s += ", max=";
  12881. s += std::to_string(keep_alive_max_count_);
  12882. }
  12883. res.set_header("Keep-Alive", s);
  12884. }
  12885. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  12886. !res.has_header("Content-Type")) {
  12887. res.set_header("Content-Type", "text/plain");
  12888. }
  12889. detail::set_framing_headers(req, res, boundary, content_type);
  12890. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  12891. res.set_header("Accept-Ranges", "bytes");
  12892. }
  12893. if (post_routing_handler_) {
  12894. post_routing_handler_(req, res);
  12895. detail::erase_invalid_fields(res.headers);
  12896. // Again, for a body or framing headers the handler changed.
  12897. detail::set_framing_headers(req, res, boundary, content_type);
  12898. }
  12899. // Response line and headers
  12900. detail::BufferStream bstrm;
  12901. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  12902. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  12903. // Combine a small body with the headers so the whole response leaves in a
  12904. // single write. A large body is written on its own instead: a copy of it
  12905. // costs more than the extra write saves.
  12906. auto send_body =
  12907. req.method != "HEAD" && detail::body_allowed_for_status(res.status);
  12908. auto body_is_separate = false;
  12909. auto provider_done = false;
  12910. if (send_body && !res.body.empty() && !res.content_provider_) {
  12911. if (res.body.size() < CPPHTTPLIB_SEND_BUFSIZ) {
  12912. bstrm.write(res.body.data(), res.body.size());
  12913. } else {
  12914. body_is_separate = true;
  12915. }
  12916. } else if (send_body && res.content_provider_ &&
  12917. res.is_file_content_provider_ &&
  12918. res.content_length_ < CPPHTTPLIB_SEND_BUFSIZ) {
  12919. // A small file is read into the same buffer. Other providers may produce
  12920. // their data over time, so they are never held back.
  12921. if (!write_content_with_provider(bstrm, req, res, boundary, content_type)) {
  12922. return false;
  12923. }
  12924. provider_done = true;
  12925. }
  12926. // Log before writing to avoid race condition with client-side code that
  12927. // accesses logger-captured data immediately after receiving the response.
  12928. output_log(req, res);
  12929. // Flush buffer
  12930. auto &data = bstrm.get_buffer();
  12931. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  12932. if (body_is_separate) {
  12933. return detail::write_data(strm, res.body.data(), res.body.size());
  12934. }
  12935. // Streaming body
  12936. if (send_body && res.content_provider_) {
  12937. if (!provider_done &&
  12938. !write_content_with_provider(strm, req, res, boundary, content_type)) {
  12939. return false;
  12940. }
  12941. res.content_provider_success_ = true;
  12942. }
  12943. return true;
  12944. }
  12945. inline bool
  12946. Server::write_content_with_provider(Stream &strm, const Request &req,
  12947. Response &res, const std::string &boundary,
  12948. const std::string &content_type) {
  12949. auto is_shutting_down = [this]() { return is_stopping(); };
  12950. if (res.content_length_ > 0) {
  12951. if (!detail::is_partial_content(req, res)) {
  12952. return detail::write_content(strm, res.content_provider_, 0,
  12953. res.content_length_, is_shutting_down);
  12954. } else if (req.ranges.size() == 1) {
  12955. auto offset_and_length = detail::get_range_offset_and_length(
  12956. req.ranges[0], res.content_length_);
  12957. return detail::write_content(strm, res.content_provider_,
  12958. offset_and_length.first,
  12959. offset_and_length.second, is_shutting_down);
  12960. } else {
  12961. return detail::write_multipart_ranges_data(
  12962. strm, req, res, boundary, content_type, res.content_length_,
  12963. is_shutting_down);
  12964. }
  12965. } else {
  12966. if (res.is_chunked_content_provider_) {
  12967. // Use the coding `apply_ranges()` chose when it wrote the headers;
  12968. // re-negotiating here would disagree with them, e.g. once a handler's
  12969. // own Content-Encoding header suppresses the negotiation.
  12970. auto compressor = detail::make_compressor(res.content_coding_);
  12971. if (!compressor) {
  12972. compressor = detail::make_unique<detail::nocompressor>();
  12973. }
  12974. return detail::write_content_chunked(strm, res.content_provider_,
  12975. is_shutting_down, *compressor);
  12976. } else {
  12977. return detail::write_content_without_length(strm, res.content_provider_,
  12978. is_shutting_down);
  12979. }
  12980. }
  12981. }
  12982. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  12983. FormFields::iterator cur_field;
  12984. FormFiles::iterator cur_file;
  12985. auto is_text_field = false;
  12986. size_t count = 0;
  12987. if (read_content_core(
  12988. strm, req, res,
  12989. // Regular
  12990. [&](const char *buf, size_t n) {
  12991. // Prevent arithmetic overflow when checking sizes.
  12992. // Avoid computing (req.body.size() + n) directly because
  12993. // adding two unsigned `size_t` values can wrap around and
  12994. // produce a small result instead of indicating overflow.
  12995. // Instead, check using subtraction: ensure `n` does not
  12996. // exceed the remaining capacity `max_size() - size()`.
  12997. if (req.body.size() >= req.body.max_size() ||
  12998. n > req.body.max_size() - req.body.size()) {
  12999. return false;
  13000. }
  13001. // Limit decompressed body size to payload_max_length_ to protect
  13002. // against "zip bomb" attacks where a small compressed payload
  13003. // decompresses to a massive size.
  13004. if (payload_max_length_ > 0 &&
  13005. (req.body.size() >= payload_max_length_ ||
  13006. n > payload_max_length_ - req.body.size())) {
  13007. return false;
  13008. }
  13009. req.body.append(buf, n);
  13010. return true;
  13011. },
  13012. // Multipart FormData
  13013. [&](const FormData &file) {
  13014. if (CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT > 0 &&
  13015. count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  13016. output_error_log(Error::TooManyFormDataFiles, &req);
  13017. return false;
  13018. }
  13019. if (file.filename.empty()) {
  13020. cur_field = req.form.fields.emplace(
  13021. file.name, FormField{file.name, file.content, file.headers});
  13022. is_text_field = true;
  13023. } else {
  13024. cur_file = req.form.files.emplace(file.name, file);
  13025. is_text_field = false;
  13026. }
  13027. return true;
  13028. },
  13029. [&](const char *buf, size_t n) {
  13030. if (is_text_field) {
  13031. auto &content = cur_field->second.content;
  13032. if (content.size() + n > content.max_size()) { return false; }
  13033. content.append(buf, n);
  13034. } else {
  13035. auto &content = cur_file->second.content;
  13036. if (content.size() + n > content.max_size()) { return false; }
  13037. content.append(buf, n);
  13038. }
  13039. return true;
  13040. })) {
  13041. const auto &content_type = req.get_header_value("Content-Type");
  13042. if (detail::case_ignore::equal(detail::extract_media_type(content_type),
  13043. "application/x-www-form-urlencoded")) {
  13044. if (CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH > 0 &&
  13045. req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  13046. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  13047. output_error_log(Error::ExceedMaxPayloadSize, &req);
  13048. return false;
  13049. }
  13050. detail::parse_query_text(req.body, req.params);
  13051. }
  13052. return true;
  13053. }
  13054. return false;
  13055. }
  13056. inline bool Server::read_content_with_content_receiver(
  13057. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  13058. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  13059. return read_content_core(strm, req, res, std::move(receiver),
  13060. std::move(multipart_header),
  13061. std::move(multipart_receiver));
  13062. }
  13063. inline bool Server::read_content_core(
  13064. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  13065. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  13066. detail::FormDataParser multipart_form_data_parser;
  13067. ContentReceiverWithProgress out;
  13068. if (req.is_multipart_form_data()) {
  13069. const auto &content_type = req.get_header_value("Content-Type");
  13070. std::string boundary;
  13071. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  13072. res.status = StatusCode::BadRequest_400;
  13073. output_error_log(Error::MultipartParsing, &req);
  13074. return false;
  13075. }
  13076. multipart_form_data_parser.set_boundary(std::move(boundary));
  13077. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  13078. return multipart_form_data_parser.parse(buf, n, multipart_header,
  13079. multipart_receiver);
  13080. };
  13081. } else {
  13082. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  13083. size_t /*len*/) { return receiver(buf, n); };
  13084. }
  13085. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  13086. if (!req.has_header("Content-Length") &&
  13087. !detail::is_chunked_transfer_encoding(req.headers)) {
  13088. return true;
  13089. }
  13090. // A second read would start where the first one stopped, or in the next
  13091. // request.
  13092. if (req.body_read_started_) { return false; }
  13093. // The client is waiting for this before it sends the body.
  13094. if (req.expect_100_continue_pending_) {
  13095. req.expect_100_continue_pending_ = false;
  13096. detail::write_response_line(strm, StatusCode::Continue_100);
  13097. strm.write("\r\n");
  13098. }
  13099. // Set before reading, since a receiver may also stop by throwing.
  13100. req.body_read_started_ = true;
  13101. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  13102. out, true)) {
  13103. return false;
  13104. }
  13105. req.body_consumed_ = true;
  13106. if (req.is_multipart_form_data()) {
  13107. if (!multipart_form_data_parser.is_valid()) {
  13108. res.status = StatusCode::BadRequest_400;
  13109. output_error_log(Error::MultipartParsing, &req);
  13110. return false;
  13111. }
  13112. }
  13113. return true;
  13114. }
  13115. inline bool Server::handle_file_request(Request &req, Response &res) {
  13116. if (!detail::is_valid_path(req.path)) { return false; }
  13117. for (const auto &entry : base_dirs_) {
  13118. // Prefix match, on a path segment boundary. A mount point of "/mount"
  13119. // covers "/mount" and "/mount/...", but must not swallow "/mountdir/...".
  13120. // One that already ends in '/' (the root mount among them) carries its own
  13121. // boundary; set_mount_point() guarantees the mount point is not empty.
  13122. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point) &&
  13123. (entry.mount_point.back() == '/' ||
  13124. req.path.size() == entry.mount_point.size() ||
  13125. req.path[entry.mount_point.size()] == '/')) {
  13126. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  13127. auto path = entry.base_dir + sub_path;
  13128. if (path.back() == '/') { path += "index.html"; }
  13129. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  13130. // but symlinks/junctions can still escape the base directory. A path
  13131. // that cannot be resolved, which includes one that does not exist, is
  13132. // not served from here.
  13133. std::string resolved_path;
  13134. if (!detail::canonicalize_path(path.c_str(), resolved_path)) { continue; }
  13135. if (!detail::is_path_within_base(resolved_path,
  13136. entry.resolved_base_dir)) {
  13137. res.status = StatusCode::Forbidden_403;
  13138. return true;
  13139. }
  13140. detail::FileStat stat(path);
  13141. if (stat.is_dir()) {
  13142. // Relative, so "//dir" cannot name another host; "./" keeps a ':'
  13143. // in the name from reading as a scheme.
  13144. auto name = req.path.substr(req.path.rfind('/') + 1);
  13145. res.set_redirect("./" + encode_path_component(name) + "/",
  13146. StatusCode::MovedPermanently_301);
  13147. return true;
  13148. }
  13149. if (stat.is_file()) {
  13150. for (const auto &kv : entry.headers) {
  13151. res.set_header(kv.first, kv.second);
  13152. }
  13153. auto content_type = detail::find_content_type(
  13154. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  13155. auto encoding = detail::EncodingType::None;
  13156. if (static_file_compression_) {
  13157. encoding = static_file_encoding(req, res, content_type, stat.size());
  13158. }
  13159. // The ETag names the representation actually sent, so a client that
  13160. // cached the compressed form revalidates against the compressed ETag
  13161. // and still gets a 304, while one that took identity keeps the plain
  13162. // ETag.
  13163. auto etag = detail::compute_etag(
  13164. stat, encoding == detail::EncodingType::None
  13165. ? std::string()
  13166. : std::string("-") + detail::encoding_name(encoding));
  13167. if (!etag.empty()) { res.set_header("ETag", etag); }
  13168. auto mtime = stat.mtime();
  13169. auto last_modified = detail::file_mtime_to_http_date(mtime);
  13170. if (!last_modified.empty()) {
  13171. res.set_header("Last-Modified", last_modified);
  13172. }
  13173. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  13174. check_if_range(req, etag, mtime);
  13175. auto mm = std::make_shared<detail::mmap>(path.c_str());
  13176. if (!mm->is_open()) {
  13177. output_error_log(Error::OpenFile, &req);
  13178. return false;
  13179. }
  13180. detail::set_file_content_provider(res, mm, content_type, encoding);
  13181. if (req.method != "HEAD" && file_request_handler_) {
  13182. file_request_handler_(req, res);
  13183. }
  13184. return true;
  13185. } else {
  13186. output_error_log(Error::OpenFile, &req);
  13187. }
  13188. }
  13189. }
  13190. return false;
  13191. }
  13192. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  13193. const std::string &etag,
  13194. time_t mtime) const {
  13195. // Handle conditional GET:
  13196. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  13197. // 2. If-Modified-Since is checked only when If-None-Match is absent
  13198. if (req.has_header("If-None-Match")) {
  13199. if (!etag.empty()) {
  13200. auto val =
  13201. detail::get_combined_header_value(req.headers, "If-None-Match");
  13202. // NOTE: We use exact string matching here. This works correctly
  13203. // because our server always generates weak ETags (W/"..."), and
  13204. // clients typically send back the same ETag they received.
  13205. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  13206. // If-None-Match, where W/"x" and "x" would match, but this
  13207. // simplified implementation requires exact matches.
  13208. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  13209. [&](const char *b, const char *e) {
  13210. auto seg_len = static_cast<size_t>(e - b);
  13211. return (seg_len == 1 && *b == '*') ||
  13212. (seg_len == etag.size() &&
  13213. std::equal(b, e, etag.begin()));
  13214. });
  13215. if (ret) {
  13216. res.status = StatusCode::NotModified_304;
  13217. return true;
  13218. }
  13219. }
  13220. } else if (req.has_header("If-Modified-Since")) {
  13221. auto val = req.get_header_value("If-Modified-Since");
  13222. auto t = detail::parse_http_date(val);
  13223. if (t != static_cast<time_t>(-1) && mtime <= t) {
  13224. res.status = StatusCode::NotModified_304;
  13225. return true;
  13226. }
  13227. }
  13228. return false;
  13229. }
  13230. inline bool Server::check_if_range(Request &req, const std::string &etag,
  13231. time_t mtime) const {
  13232. // Handle If-Range for partial content requests (RFC 9110
  13233. // Section 13.1.5). If-Range is only evaluated when Range header is
  13234. // present. If the validator matches, serve partial content; otherwise
  13235. // serve full content.
  13236. if (!req.ranges.empty() && req.has_header("If-Range")) {
  13237. auto val = req.get_header_value("If-Range");
  13238. auto is_valid_range = [&]() {
  13239. if (detail::is_strong_etag(val)) {
  13240. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  13241. // comparison.
  13242. return (!etag.empty() && val == etag);
  13243. } else if (detail::is_weak_etag(val)) {
  13244. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  13245. return false;
  13246. } else {
  13247. // HTTP-date comparison
  13248. auto t = detail::parse_http_date(val);
  13249. return (t != static_cast<time_t>(-1) && mtime <= t);
  13250. }
  13251. };
  13252. if (!is_valid_range()) {
  13253. // Validator doesn't match: ignore Range and serve full content
  13254. req.ranges.clear();
  13255. return false;
  13256. }
  13257. }
  13258. return true;
  13259. }
  13260. inline socket_t
  13261. Server::create_server_socket(const std::string &host, int port,
  13262. int socket_flags,
  13263. SocketOptions socket_options) const {
  13264. return detail::create_socket(
  13265. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  13266. ipv6_v6only_, std::move(socket_options),
  13267. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  13268. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  13269. output_error_log(Error::BindIPAddress, nullptr);
  13270. return false;
  13271. }
  13272. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  13273. output_error_log(Error::Listen, nullptr);
  13274. return false;
  13275. }
  13276. return true;
  13277. });
  13278. }
  13279. inline int Server::bind_internal(const std::string &host, int port,
  13280. int socket_flags) {
  13281. if (is_decommissioned) { return -1; }
  13282. if (!is_valid()) { return -1; }
  13283. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  13284. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  13285. if (port == 0) {
  13286. struct sockaddr_storage addr;
  13287. socklen_t addr_len = sizeof(addr);
  13288. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  13289. &addr_len) == -1) {
  13290. output_error_log(Error::GetSockName, nullptr);
  13291. return -1;
  13292. }
  13293. if (addr.ss_family == AF_INET) {
  13294. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  13295. } else if (addr.ss_family == AF_INET6) {
  13296. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  13297. } else {
  13298. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  13299. return -1;
  13300. }
  13301. } else {
  13302. return port;
  13303. }
  13304. }
  13305. inline bool Server::listen_internal() {
  13306. // A stop() between bind and listen leaves nothing to accept on. Report
  13307. // failure instead of returning success without ever serving, and mark the
  13308. // server decommissioned the way any failed listen does so that a concurrent
  13309. // wait_until_ready() wakes up instead of spinning forever.
  13310. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  13311. is_decommissioned = true;
  13312. return false;
  13313. }
  13314. auto ret = true;
  13315. is_running_ = true;
  13316. auto se = detail::scope_exit([&]() { is_running_ = false; });
  13317. if (start_handler_) { start_handler_(); }
  13318. {
  13319. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  13320. ret = keep_alive_parking_ && parking_ ? parking_loop(*task_queue)
  13321. : accept_loop(*task_queue);
  13322. task_queue->shutdown();
  13323. }
  13324. is_decommissioned = !ret;
  13325. return ret;
  13326. }
  13327. inline void Server::prepare_accepted_socket(socket_t sock) const {
  13328. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
  13329. read_timeout_usec_);
  13330. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
  13331. write_timeout_usec_);
  13332. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  13333. }
  13334. // Serves each connection on one worker thread for its whole life.
  13335. inline bool Server::accept_loop(TaskQueue &task_queue) {
  13336. auto ret = true;
  13337. while (svr_sock_ != INVALID_SOCKET) {
  13338. #ifndef _WIN32
  13339. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  13340. #endif
  13341. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  13342. idle_interval_usec_);
  13343. if (val == 0) { // Timeout
  13344. task_queue.on_idle();
  13345. continue;
  13346. }
  13347. #ifndef _WIN32
  13348. }
  13349. #endif
  13350. auto sock = detail::accept_socket(svr_sock_);
  13351. if (sock == INVALID_SOCKET) {
  13352. // NOTE: Winsock reports failures through WSAGetLastError() and never
  13353. // touches the CRT errno, so the two have to be asked platform by
  13354. // platform rather than by testing errno here.
  13355. if (detail::is_accept_resource_error()) {
  13356. // The per-process descriptor limit or the network stack's buffer
  13357. // space has been reached. Try to accept new connections after a
  13358. // short sleep.
  13359. std::this_thread::sleep_for(std::chrono::microseconds{1});
  13360. continue;
  13361. } else if (detail::is_accept_transient_error()) {
  13362. continue;
  13363. }
  13364. if (abandon_listen_socket()) { ret = false; }
  13365. break;
  13366. }
  13367. prepare_accepted_socket(sock);
  13368. if (!task_queue.enqueue(
  13369. [this, sock]() { process_and_close_socket(sock); })) {
  13370. output_error_log(Error::ResourceExhaustion, nullptr);
  13371. detail::shutdown_socket(sock);
  13372. detail::close_socket(sock);
  13373. }
  13374. }
  13375. return ret;
  13376. }
  13377. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13378. // Call from a catch block. The response is a 500 unless the exception handler
  13379. // sets another status. Returns whether the exception handler ran.
  13380. inline bool Server::handle_exception(Request &req, Response &res) {
  13381. res.status = StatusCode::InternalServerError_500;
  13382. if (!exception_handler_) { return false; }
  13383. exception_handler_(req, res, std::current_exception());
  13384. return true;
  13385. }
  13386. #endif
  13387. inline bool Server::routing(Request &req, Response &res, Stream &strm,
  13388. bool skip_pre_routing) {
  13389. if (!skip_pre_routing && pre_routing_handler_ &&
  13390. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  13391. return true;
  13392. }
  13393. // File handler
  13394. if ((req.method == "GET" || req.method == "HEAD") &&
  13395. handle_file_request(req, res)) {
  13396. return true;
  13397. }
  13398. const auto *custom = find_custom_entry(req.method);
  13399. // The second clause mirrors what expect_content() does unconditionally for
  13400. // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
  13401. // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
  13402. // `allprop`) would skip its handler and fall through to 404.
  13403. if (detail::expect_content(req) ||
  13404. (custom && !custom->handlers_for_content_reader.empty())) {
  13405. // Content reader handler
  13406. {
  13407. // Track whether the ContentReader was aborted due to the decompressed
  13408. // payload exceeding `payload_max_length_`.
  13409. // The user handler runs after the lambda returns, so we must restore the
  13410. // 413 status if the handler overwrites it.
  13411. bool content_reader_payload_too_large = false;
  13412. ContentReader reader(
  13413. [&](ContentReceiver receiver) {
  13414. auto result = read_content_with_content_receiver(
  13415. strm, req, res, std::move(receiver), nullptr, nullptr);
  13416. if (!result) {
  13417. output_error_log(Error::Read, &req);
  13418. if (res.status == StatusCode::PayloadTooLarge_413) {
  13419. content_reader_payload_too_large = true;
  13420. }
  13421. }
  13422. return result;
  13423. },
  13424. [&](FormDataHeader header, ContentReceiver receiver) {
  13425. auto result = read_content_with_content_receiver(
  13426. strm, req, res, nullptr, std::move(header),
  13427. std::move(receiver));
  13428. if (!result) {
  13429. output_error_log(Error::Read, &req);
  13430. if (res.status == StatusCode::PayloadTooLarge_413) {
  13431. content_reader_payload_too_large = true;
  13432. }
  13433. }
  13434. return result;
  13435. });
  13436. bool dispatched = false;
  13437. if (req.method == "POST") {
  13438. dispatched = dispatch_request_for_content_reader(
  13439. req, res, std::move(reader), post_handlers_for_content_reader_);
  13440. } else if (req.method == "PUT") {
  13441. dispatched = dispatch_request_for_content_reader(
  13442. req, res, std::move(reader), put_handlers_for_content_reader_);
  13443. } else if (req.method == "PATCH") {
  13444. dispatched = dispatch_request_for_content_reader(
  13445. req, res, std::move(reader), patch_handlers_for_content_reader_);
  13446. } else if (req.method == "DELETE") {
  13447. dispatched = dispatch_request_for_content_reader(
  13448. req, res, std::move(reader), delete_handlers_for_content_reader_);
  13449. } else if (custom) {
  13450. dispatched = dispatch_request_for_content_reader(
  13451. req, res, std::move(reader), custom->handlers_for_content_reader);
  13452. }
  13453. if (dispatched) {
  13454. if (content_reader_payload_too_large) {
  13455. // Enforce the limit: override any status the handler may have set
  13456. // and return false so the error path sends a plain 413 response.
  13457. res.status = StatusCode::PayloadTooLarge_413;
  13458. detail::clear_content(res);
  13459. return false;
  13460. }
  13461. return true;
  13462. }
  13463. }
  13464. // NOTE: `req.body` is not read here. For a regular handler the body is
  13465. // read inside dispatch_request(), after the route has matched and the
  13466. // pre-request handler has approved the request, so that a rejected
  13467. // request (e.g. failed authentication) never forces us to buffer a
  13468. // potentially large body.
  13469. }
  13470. // Regular handler
  13471. if (req.method == "GET" || req.method == "HEAD") {
  13472. return dispatch_request(req, res, get_handlers_, strm);
  13473. } else if (req.method == "POST") {
  13474. return dispatch_request(req, res, post_handlers_, strm);
  13475. } else if (req.method == "PUT") {
  13476. return dispatch_request(req, res, put_handlers_, strm);
  13477. } else if (req.method == "DELETE") {
  13478. return dispatch_request(req, res, delete_handlers_, strm);
  13479. } else if (req.method == "OPTIONS") {
  13480. return dispatch_request(req, res, options_handlers_, strm);
  13481. } else if (req.method == "PATCH") {
  13482. return dispatch_request(req, res, patch_handlers_, strm);
  13483. } else if (custom) {
  13484. return dispatch_request(req, res, custom->handlers, strm);
  13485. }
  13486. res.status = StatusCode::BadRequest_400;
  13487. return false;
  13488. }
  13489. inline bool Server::dispatch_request(Request &req, Response &res,
  13490. const Handlers &handlers, Stream &strm) {
  13491. for (const auto &x : handlers) {
  13492. const auto &matcher = x.first;
  13493. const auto &handler = x.second;
  13494. if (matcher->match(req)) {
  13495. req.matched_route = matcher->pattern();
  13496. // Run the pre-request handler before reading the body so a rejected
  13497. // request (e.g. failed authentication) never forces us to buffer a
  13498. // potentially large body. `req.matched_route` is available here.
  13499. if (pre_request_handler_ &&
  13500. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  13501. return true;
  13502. }
  13503. // The route matched and the request was approved; read the body now.
  13504. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  13505. output_error_log(Error::Read, &req);
  13506. return false;
  13507. }
  13508. handler(req, res);
  13509. return true;
  13510. }
  13511. }
  13512. return false;
  13513. }
  13514. // Decides the content coding for a response served straight from a file. Both
  13515. // the ETag, which has to name the representation actually sent, and
  13516. // `apply_static_file_compression()` go through this, so the two cannot drift
  13517. // apart.
  13518. inline detail::EncodingType
  13519. Server::static_file_encoding(const Request &req, const Response &res,
  13520. const std::string &content_type,
  13521. size_t length) const {
  13522. if (!static_file_compression_) { return detail::EncodingType::None; }
  13523. // Nothing to compress, and an empty file already answers with
  13524. // `Content-Length: 0`. Checked on its own so that a zero floor still cannot
  13525. // turn an empty body into a 20-byte gzip stream.
  13526. if (length == 0) { return detail::EncodingType::None; }
  13527. // A file that already fits in a single packet gains nothing from being made
  13528. // smaller, since it still travels in that one segment, and a file of a few
  13529. // bytes comes out larger than it went in.
  13530. if (length < static_file_compression_min_length_) {
  13531. return detail::EncodingType::None;
  13532. }
  13533. // RFC 9110 applies Range to the representation after content coding, so a
  13534. // compressed 206 would mean compressing the whole file and then slicing it.
  13535. // Serve ranges from the identity representation instead.
  13536. if (!req.ranges.empty()) { return detail::EncodingType::None; }
  13537. if (static_file_compression_max_length_ > 0 &&
  13538. length > static_file_compression_max_length_) {
  13539. return detail::EncodingType::None;
  13540. }
  13541. return detail::encoding_type(req, res, content_type);
  13542. }
  13543. // Compresses a file-backed content provider into `res.body`. Returns false when
  13544. // the response is left untouched.
  13545. inline bool Server::apply_static_file_compression(const Request &req,
  13546. Response &res) const {
  13547. auto type = res.content_coding_;
  13548. if (type == detail::EncodingType::None || !res.content_provider_) {
  13549. return false;
  13550. }
  13551. auto compressor = detail::make_compressor(type);
  13552. if (!compressor) { return false; }
  13553. output_pre_compression_log(req, res);
  13554. std::string compressed;
  13555. if (!detail::compress_content_provider(res.content_provider_,
  13556. res.content_length_, *compressor,
  13557. compressed)) {
  13558. return false;
  13559. }
  13560. res.body.swap(compressed);
  13561. // The provider was consumed in full, so its releaser hears about a success.
  13562. res.content_provider_success_ = true;
  13563. detail::clear_content_provider(res);
  13564. res.set_header("Content-Encoding", detail::encoding_name(type));
  13565. res.set_header("Vary", "Accept-Encoding");
  13566. return true;
  13567. }
  13568. inline void Server::apply_ranges(const Request &req, Response &res,
  13569. std::string &content_type,
  13570. std::string &boundary) const {
  13571. // A known-length content provider leaves `res.body` empty, so the compressor
  13572. // at the end of this function never runs for one (issue #2545). A file-backed
  13573. // provider is fully readable right here, so compress it and answer with an
  13574. // ordinary body: `Content-Length` and HEAD keep working, and the response
  13575. // takes the same path as `set_content()` from here on. Range requests never
  13576. // get a content coding, so `Content-Range` still names identity bytes and
  13577. // none of the range handling below applies.
  13578. if (apply_static_file_compression(req, res)) { return; }
  13579. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  13580. auto it = res.headers.find("Content-Type");
  13581. if (it != res.headers.end()) {
  13582. content_type = it->second;
  13583. res.headers.erase(it);
  13584. }
  13585. boundary = detail::make_multipart_data_boundary();
  13586. res.set_header("Content-Type",
  13587. "multipart/byteranges; boundary=" + boundary);
  13588. }
  13589. auto type =
  13590. compress_ ? detail::encoding_type(req, res) : detail::EncodingType::None;
  13591. if (res.body.empty()) {
  13592. if (res.content_length_ > 0 && req.ranges.size() == 1 &&
  13593. res.status == StatusCode::PartialContent_206) {
  13594. auto offset_and_length = detail::get_range_offset_and_length(
  13595. req.ranges[0], res.content_length_);
  13596. auto content_range = detail::make_content_range_header_field(
  13597. offset_and_length, res.content_length_);
  13598. res.set_header("Content-Range", content_range);
  13599. } else if (res.is_chunked_content_provider_) {
  13600. res.content_coding_ = type;
  13601. if (type != detail::EncodingType::None) {
  13602. res.set_header("Content-Encoding", detail::encoding_name(type));
  13603. res.set_header("Vary", "Accept-Encoding");
  13604. }
  13605. }
  13606. } else {
  13607. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  13608. ;
  13609. } else if (req.ranges.size() == 1) {
  13610. auto offset_and_length =
  13611. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  13612. auto offset = offset_and_length.first;
  13613. auto length = offset_and_length.second;
  13614. auto content_range = detail::make_content_range_header_field(
  13615. offset_and_length, res.body.size());
  13616. res.set_header("Content-Range", content_range);
  13617. assert(offset + length <= res.body.size());
  13618. res.body = res.body.substr(offset, length);
  13619. } else {
  13620. std::string data;
  13621. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  13622. res.body.size(), data);
  13623. res.body.swap(data);
  13624. }
  13625. if (type != detail::EncodingType::None) {
  13626. output_pre_compression_log(req, res);
  13627. if (auto compressor = detail::make_compressor(type)) {
  13628. std::string compressed;
  13629. if (compressor->compress(res.body.data(), res.body.size(), true,
  13630. [&](const char *data, size_t data_len) {
  13631. compressed.append(data, data_len);
  13632. return true;
  13633. })) {
  13634. res.body.swap(compressed);
  13635. res.set_header("Content-Encoding", detail::encoding_name(type));
  13636. res.set_header("Vary", "Accept-Encoding");
  13637. }
  13638. }
  13639. }
  13640. res.content_length_ = res.body.size();
  13641. }
  13642. }
  13643. inline bool Server::dispatch_request_for_content_reader(
  13644. Request &req, Response &res, ContentReader content_reader,
  13645. const HandlersForContentReader &handlers) const {
  13646. for (const auto &x : handlers) {
  13647. const auto &matcher = x.first;
  13648. const auto &handler = x.second;
  13649. if (matcher->match(req)) {
  13650. req.matched_route = matcher->pattern();
  13651. if (!pre_request_handler_ ||
  13652. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  13653. handler(req, res, content_reader);
  13654. }
  13655. return true;
  13656. }
  13657. }
  13658. return false;
  13659. }
  13660. inline std::string
  13661. get_client_ip(const std::string &x_forwarded_for,
  13662. const std::vector<std::string> &trusted_proxies) {
  13663. // X-Forwarded-For is a comma-separated list per RFC 7239
  13664. std::vector<std::string> ip_list;
  13665. detail::split(x_forwarded_for.data(),
  13666. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  13667. [&](const char *b, const char *e) {
  13668. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  13669. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  13670. });
  13671. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  13672. // no segments. Signal "no client IP derived" with an empty string so the
  13673. // caller can fall back to the connection-level remote address.
  13674. if (ip_list.empty()) { return std::string(); }
  13675. // Each hop appends the address it received the request from, so the rightmost
  13676. // entries are the ones written by our own infrastructure while the leftmost
  13677. // are whatever the original client chose to send. Walk from the right and
  13678. // skip trusted proxies; the first address that is not a trusted proxy is the
  13679. // furthest point still attributable to a real hop, i.e. the client. Scanning
  13680. // from the left instead lets a client forge an arbitrary address by following
  13681. // it with a trusted proxy's address, which the left-to-right scan then
  13682. // returned as the client.
  13683. for (size_t i = ip_list.size(); i-- > 0;) {
  13684. const auto &ip = ip_list[i];
  13685. if (!detail::is_trusted_proxy(ip, trusted_proxies)) { return ip; }
  13686. }
  13687. // Every hop was a trusted proxy; fall back to the first entry.
  13688. return ip_list.front();
  13689. }
  13690. inline bool
  13691. Server::process_request(Stream &strm, const std::string &remote_addr,
  13692. int remote_port, const std::string &local_addr,
  13693. int local_port, bool close_connection,
  13694. bool &connection_closed,
  13695. const std::function<void(Request &)> &setup_request,
  13696. bool *websocket_upgraded) {
  13697. std::array<char, 2048> buf{};
  13698. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  13699. // The read timeout bounds the request line and headers as a whole, so a
  13700. // client sending them a byte at a time cannot hold the worker any longer.
  13701. auto read_timeout_msec = read_timeout_sec_ * 1000 + read_timeout_usec_ / 1000;
  13702. strm.set_max_timeout(read_timeout_msec);
  13703. // Connection has been closed on client
  13704. if (!line_reader.getline()) { return false; }
  13705. // RFC 9112 2.2: ignore an empty line received before the request-line. Some
  13706. // clients send an extra CRLF after a request body, which would otherwise be
  13707. // parsed as the next request on a persistent connection.
  13708. if (strcmp(line_reader.ptr(), "\r\n") == 0 && !line_reader.getline()) {
  13709. return false;
  13710. }
  13711. Request req;
  13712. req.start_time_ = std::chrono::steady_clock::now();
  13713. req.remote_addr = remote_addr;
  13714. req.remote_port = remote_port;
  13715. req.local_addr = local_addr;
  13716. req.local_port = local_port;
  13717. Response res;
  13718. res.version = "HTTP/1.1";
  13719. res.headers = default_headers_;
  13720. // RFC 9112 §9.6: a server that sends the "close" connection option must
  13721. // close the connection after that response, whichever path wrote it (an
  13722. // error status, a handler, or a rejected request). Reading on would also
  13723. // parse whatever the client sent next on a connection it considers done.
  13724. auto honor_connection_close = detail::scope_exit([&] {
  13725. if (detail::has_header_token(res.headers, "Connection", "close")) {
  13726. connection_closed = true;
  13727. }
  13728. });
  13729. // Request line and headers. A rejected message leaves the rest of it (and
  13730. // any body) unread, so the connection cannot be reused: the leftover bytes
  13731. // would be parsed as the next request.
  13732. if (!parse_request_line(line_reader.ptr(), req)) {
  13733. connection_closed = true;
  13734. res.status = StatusCode::BadRequest_400;
  13735. output_error_log(Error::InvalidRequestLine, &req);
  13736. return write_response(strm, close_connection, req, res);
  13737. }
  13738. // Request headers
  13739. if (!detail::read_headers(strm, req.headers)) {
  13740. connection_closed = true;
  13741. res.status = StatusCode::BadRequest_400;
  13742. output_error_log(Error::InvalidHeaders, &req);
  13743. return write_response(strm, close_connection, req, res);
  13744. }
  13745. strm.set_max_timeout(0);
  13746. // RFC 9112 §6.3: Reject requests whose framing is invalid or ambiguous,
  13747. // which would otherwise let an intermediary and this parser disagree on
  13748. // where the body ends and enable request smuggling. Three cases: a
  13749. // Content-Length that is not a valid decimal length (e.g. "42, 42", "+42"
  13750. // or empty), which would otherwise be read as "no body"; a non-zero
  13751. // Content-Length alongside any Transfer-Encoding (Content-Length: 0 is
  13752. // tolerated for compatibility with existing clients); and a
  13753. // Transfer-Encoding whose final coding is not chunked, which leaves the body
  13754. // length undeterminable. None of them may fall through to the "no body"
  13755. // path, or the body bytes are parsed as the next request on a persistent
  13756. // connection.
  13757. auto is_invalid_content_length = false;
  13758. detail::get_header_value_u64(req.headers, "Content-Length", 0, 0,
  13759. is_invalid_content_length);
  13760. if (is_invalid_content_length ||
  13761. detail::has_conflicting_content_length(req.headers) ||
  13762. (req.has_header("Transfer-Encoding") &&
  13763. !detail::is_chunked_transfer_encoding(req.headers))) {
  13764. connection_closed = true;
  13765. res.status = StatusCode::BadRequest_400;
  13766. return write_response(strm, close_connection, req, res);
  13767. }
  13768. // RFC 9112 6.1: a lone "chunked" is the only transfer coding implemented
  13769. if (req.has_header("Transfer-Encoding") &&
  13770. (req.get_header_value_count("Transfer-Encoding") != 1 ||
  13771. !detail::case_ignore::equal(req.get_header_value("Transfer-Encoding"),
  13772. "chunked"))) {
  13773. connection_closed = true;
  13774. res.status = StatusCode::NotImplemented_501;
  13775. return write_response(strm, close_connection, req, res);
  13776. }
  13777. // RFC 9112 §6.1: a Transfer-Encoding alongside a Content-Length, or in an
  13778. // HTTP/1.0 request, is honoured, but the connection closes after the
  13779. // response.
  13780. if (detail::has_faulty_transfer_encoding(req)) { connection_closed = true; }
  13781. // RFC 9112 §3.2: Reject more than one Host field line, an invalid Host
  13782. // value, or none in HTTP/1.1, so that every recipient of the request sees
  13783. // the same authority.
  13784. auto host_count = req.get_header_value_count("Host");
  13785. if (host_count > 1 || (host_count == 0 && req.version == "HTTP/1.1") ||
  13786. !detail::fields::is_host(req.get_header_value("Host"))) {
  13787. connection_closed = true;
  13788. res.status = StatusCode::BadRequest_400;
  13789. output_error_log(Error::InvalidHeaders, &req);
  13790. return write_response(strm, close_connection, req, res);
  13791. }
  13792. // Check if the request URI doesn't exceed the limit
  13793. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  13794. connection_closed = true;
  13795. res.status = StatusCode::UriTooLong_414;
  13796. output_error_log(Error::ExceedUriMaxLength, &req);
  13797. return write_response(strm, close_connection, req, res);
  13798. }
  13799. if (detail::has_header_token(req.headers, "Connection", "close")) {
  13800. connection_closed = true;
  13801. }
  13802. if (req.version == "HTTP/1.0" &&
  13803. !detail::has_header_token(req.headers, "Connection", "keep-alive")) {
  13804. connection_closed = true;
  13805. }
  13806. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  13807. // itself a trusted proxy. Otherwise any direct client could spoof
  13808. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  13809. if (detail::is_trusted_proxy(remote_addr, trusted_proxies_) &&
  13810. req.has_header("X-Forwarded-For")) {
  13811. // Some proxies append the address they observed as a separate
  13812. // X-Forwarded-For field line instead of extending the one the client sent
  13813. // (e.g. HAProxy's "option forwardfor"), so the whole combined value has to
  13814. // be scanned. Reading only the first occurrence would hand back the
  13815. // client-supplied, and therefore forgeable, value.
  13816. auto x_forwarded_for =
  13817. detail::get_combined_header_value(req.headers, "X-Forwarded-For");
  13818. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  13819. req.remote_addr = derived.empty() ? remote_addr : derived;
  13820. } else {
  13821. req.remote_addr = remote_addr;
  13822. }
  13823. req.remote_port = remote_port;
  13824. req.local_addr = local_addr;
  13825. req.local_port = local_port;
  13826. if (req.has_header("Accept")) {
  13827. auto accept_header =
  13828. detail::get_combined_header_value(req.headers, "Accept");
  13829. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  13830. connection_closed = true;
  13831. res.status = StatusCode::BadRequest_400;
  13832. output_error_log(Error::HTTPParsing, &req);
  13833. return write_response(strm, close_connection, req, res);
  13834. }
  13835. }
  13836. // RFC 9110 14.2: range handling is defined only for GET (and so for HEAD)
  13837. if ((req.method == "GET" || req.method == "HEAD") &&
  13838. req.has_header("Range")) {
  13839. const auto &range_header_value = req.get_header_value("Range");
  13840. // RFC 9110 14.2: a range unit other than bytes must be ignored
  13841. auto unit = range_header_value.substr(0, range_header_value.find('='));
  13842. if (detail::case_ignore::equal(unit, "bytes") &&
  13843. !detail::parse_range_header(range_header_value, req.ranges)) {
  13844. connection_closed = true;
  13845. res.status = StatusCode::RangeNotSatisfiable_416;
  13846. output_error_log(Error::InvalidRangeHeader, &req);
  13847. return write_response(strm, close_connection, req, res);
  13848. }
  13849. }
  13850. if (setup_request) { setup_request(req); }
  13851. // RFC 9110 10.1.1: Expect is a comma-separated list whose value is
  13852. // case-insensitive, and a 100-continue expectation in an HTTP/1.0 request
  13853. // must be ignored. An expectation we do not recognize is left alone; the
  13854. // 417 the section allows for one is a MAY, not a requirement.
  13855. //
  13856. // `100 Continue` itself is deferred until the body is actually read (see
  13857. // read_content_core), so a request rejected by a later handler never
  13858. // invites the client to send a body nobody will read.
  13859. if (req.version != "HTTP/1.0" &&
  13860. detail::has_header_token(req.headers, "Expect", "100-continue")) {
  13861. int status = StatusCode::Continue_100;
  13862. if (expect_100_continue_handler_) {
  13863. status = expect_100_continue_handler_(req, res);
  13864. }
  13865. if (status == StatusCode::Continue_100) {
  13866. req.expect_100_continue_pending_ = true;
  13867. } else {
  13868. if (res.status == -1) { res.status = status; }
  13869. connection_closed = true;
  13870. return write_response(strm, true, req, res);
  13871. }
  13872. }
  13873. // Setup `is_connection_closed` method
  13874. auto sock = strm.socket();
  13875. req.is_connection_closed = [sock]() {
  13876. return !detail::is_socket_alive(sock);
  13877. };
  13878. // WebSocket upgrade
  13879. // Run pre_routing_handler_ and pre_request_handler_ before upgrading so
  13880. // that authentication and other middleware can reject the request with an
  13881. // HTTP response (e.g., 401) before the protocol switches.
  13882. // The response says so when this connection closes after it.
  13883. auto close_after_response = close_connection || connection_closed;
  13884. // An upgrade request has been through pre-routing before it reaches routing()
  13885. auto is_upgrade = detail::is_websocket_upgrade(req);
  13886. if (is_upgrade) {
  13887. // A response given here leaves the body unread, and it would be parsed as
  13888. // the next request.
  13889. auto close_if_answered =
  13890. close_after_response || detail::has_framed_body(req);
  13891. const WebSocketHandlerEntry *ws_route = nullptr;
  13892. std::string selected_subprotocol;
  13893. auto answer_before_upgrade = [&]() -> bool {
  13894. if (pre_routing_handler_ &&
  13895. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  13896. return true;
  13897. }
  13898. for (const auto &entry : websocket_handlers_) {
  13899. if (!entry.matcher->match(req)) { continue; }
  13900. req.matched_route = entry.matcher->pattern();
  13901. if (pre_request_handler_ &&
  13902. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  13903. return true;
  13904. }
  13905. ws_route = &entry;
  13906. if (entry.sub_protocol_selector) {
  13907. auto protocol_header = detail::get_combined_header_value(
  13908. req.headers, "Sec-WebSocket-Protocol");
  13909. if (!protocol_header.empty()) {
  13910. std::vector<std::string> protocols;
  13911. detail::split(protocol_header.data(),
  13912. protocol_header.data() + protocol_header.size(), ',',
  13913. [&](const char *b, const char *e) {
  13914. protocols.emplace_back(b, e);
  13915. });
  13916. selected_subprotocol = entry.sub_protocol_selector(protocols);
  13917. // Ignore a selection the client did not offer (RFC 6455 4.2.2)
  13918. if (std::find(protocols.begin(), protocols.end(),
  13919. selected_subprotocol) == protocols.end()) {
  13920. selected_subprotocol.clear();
  13921. }
  13922. }
  13923. }
  13924. return false;
  13925. }
  13926. return false;
  13927. };
  13928. auto answered = false;
  13929. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13930. answered = answer_before_upgrade();
  13931. #else
  13932. try {
  13933. answered = answer_before_upgrade();
  13934. } catch (...) {
  13935. if (!handle_exception(req, res)) {
  13936. return write_response(strm, close_if_answered, req, res);
  13937. }
  13938. answered = true;
  13939. }
  13940. #endif
  13941. if (answered) {
  13942. if (res.status == -1) { res.status = StatusCode::OK_200; }
  13943. return write_response_with_content(strm, close_if_answered, req, res);
  13944. }
  13945. if (ws_route) {
  13946. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  13947. auto accept_key = detail::websocket_accept_key(client_key);
  13948. // Send 101 Switching Protocols
  13949. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  13950. "Upgrade: websocket\r\n"
  13951. "Connection: Upgrade\r\n"
  13952. "Sec-WebSocket-Accept: " +
  13953. accept_key + "\r\n";
  13954. if (!selected_subprotocol.empty()) {
  13955. if (!detail::fields::is_field_value(selected_subprotocol)) {
  13956. return false;
  13957. }
  13958. handshake_response +=
  13959. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  13960. }
  13961. handshake_response += "\r\n";
  13962. if (strm.write(handshake_response.data(), handshake_response.size()) <
  13963. 0) {
  13964. return false;
  13965. }
  13966. connection_closed = true;
  13967. if (websocket_upgraded) { *websocket_upgraded = true; }
  13968. auto stopping = [this] { return is_stopping(); };
  13969. if (CPPHTTPLIB_WEBSOCKET_TCP_NODELAY) {
  13970. set_socket_opt(strm.socket(), IPPROTO_TCP, TCP_NODELAY, 1);
  13971. }
  13972. #ifdef CPPHTTPLIB_SSL_ENABLED
  13973. if (req.ssl) {
  13974. // wss: the heartbeat ping thread and the read path enter the same
  13975. // TLS session from different threads. Hand the WebSocket a stream
  13976. // that serializes every TLS call, so the shared SSLSocketStream on
  13977. // the plain HTTP/HTTPS paths stays untouched.
  13978. auto ws_strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  13979. strm.socket(), const_cast<tls::session_t>(req.ssl),
  13980. CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
  13981. write_timeout_sec_, write_timeout_usec_));
  13982. ws::WebSocket ws(std::move(ws_strm), req, true,
  13983. websocket_ping_interval_sec_,
  13984. websocket_max_missed_pongs_, stopping);
  13985. ws_route->handler(req, ws);
  13986. return true;
  13987. }
  13988. #endif
  13989. // Use WebSocket-specific read timeout instead of HTTP timeout
  13990. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
  13991. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  13992. websocket_max_missed_pongs_, stopping);
  13993. ws_route->handler(req, ws);
  13994. return true;
  13995. }
  13996. // No WebSocket route: route it as a plain HTTP request
  13997. }
  13998. // Routing
  13999. auto routed = false;
  14000. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14001. routed = routing(req, res, strm, is_upgrade);
  14002. #else
  14003. try {
  14004. routed = routing(req, res, strm, is_upgrade);
  14005. } catch (...) { routed = handle_exception(req, res); }
  14006. #endif
  14007. auto ret = false;
  14008. if (routed) {
  14009. if (res.status == -1) {
  14010. res.status = req.ranges.empty() ? StatusCode::OK_200
  14011. : StatusCode::PartialContent_206;
  14012. }
  14013. // Before the Range checks below, so they see the body's own length.
  14014. detail::prefer_assigned_body(res);
  14015. // Serve file content by using a content provider
  14016. auto file_open_error = false;
  14017. if (!res.file_content_path_.empty()) {
  14018. const auto &path = res.file_content_path_;
  14019. auto mm = std::make_shared<detail::mmap>(path.c_str());
  14020. if (!mm->is_open()) {
  14021. res.status = StatusCode::NotFound_404;
  14022. output_error_log(Error::OpenFile, &req);
  14023. file_open_error = true;
  14024. } else {
  14025. auto content_type = res.file_content_content_type_;
  14026. if (content_type.empty()) {
  14027. // One the handler set after set_file_content()
  14028. content_type = res.get_header_value("Content-Type");
  14029. }
  14030. if (content_type.empty()) {
  14031. content_type = detail::find_content_type(
  14032. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  14033. }
  14034. detail::set_file_content_provider(
  14035. res, mm, content_type,
  14036. static_file_encoding(req, res, content_type, mm->size()));
  14037. }
  14038. }
  14039. if (file_open_error) {
  14040. ret = write_response(strm, close_after_response, req, res);
  14041. } else if (detail::range_error(req, res)) {
  14042. detail::clear_content(res);
  14043. res.status = StatusCode::RangeNotSatisfiable_416;
  14044. ret = write_response(strm, close_after_response, req, res);
  14045. } else {
  14046. ret = write_response_with_content(strm, close_after_response, req, res);
  14047. }
  14048. } else {
  14049. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  14050. ret = write_response(strm, close_after_response, req, res);
  14051. }
  14052. // Drain any unconsumed framed body to prevent request smuggling on
  14053. // keep-alive. Without framing there is no body to drain — reading would
  14054. // consume the next request (issue #2450). If the response has committed the
  14055. // connection to close, there is no next request to protect. A body read in
  14056. // part cannot be drained from where it stopped, so the connection closes,
  14057. // as it does when the body is longer than the drain limit or does not
  14058. // arrive within the read timeout.
  14059. if (!req.body_consumed_ && detail::has_framed_body(req) &&
  14060. !detail::has_header_token(res.headers, "Connection", "close")) {
  14061. strm.set_max_timeout(read_timeout_msec);
  14062. int dummy_status;
  14063. if (req.body_read_started_ ||
  14064. !detail::read_content(
  14065. strm, req, CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH, dummy_status,
  14066. nullptr, [](const char *, size_t, size_t, size_t) { return true; },
  14067. false)) {
  14068. connection_closed = true;
  14069. }
  14070. }
  14071. return ret;
  14072. }
  14073. inline bool Server::is_valid() const { return !has_invalid_registration_; }
  14074. inline bool Server::process_and_close_socket(socket_t sock) {
  14075. std::string remote_addr;
  14076. int remote_port = 0;
  14077. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  14078. std::string local_addr;
  14079. int local_port = 0;
  14080. detail::get_local_ip_and_port(sock, local_addr, local_port);
  14081. bool websocket_upgraded = false;
  14082. auto ret = serve_guarded([&]() {
  14083. return detail::process_server_socket(
  14084. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  14085. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14086. write_timeout_usec_,
  14087. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  14088. return process_request(strm, remote_addr, remote_port, local_addr,
  14089. local_port, close_connection,
  14090. connection_closed, nullptr,
  14091. &websocket_upgraded);
  14092. });
  14093. });
  14094. detail::drain_and_close_socket(sock);
  14095. return ret;
  14096. }
  14097. // After accept() failed for good. Takes the descriptor out of svr_sock_
  14098. // before closing it: a later stop() would otherwise shutdown()/close() a value
  14099. // the OS may have reused, and keep_alive() watches svr_sock_ to notice the
  14100. // server is gone. The exchange also settles the race with a concurrent stop(),
  14101. // since whichever side takes the descriptor closes it exactly once. Returns
  14102. // false when stop() took it first.
  14103. inline bool Server::abandon_listen_socket() {
  14104. auto sock = svr_sock_.exchange(INVALID_SOCKET);
  14105. if (sock == INVALID_SOCKET) { return false; }
  14106. detail::close_socket(sock);
  14107. output_error_log(Error::Connection, nullptr);
  14108. return true;
  14109. }
  14110. // Like accept_loop(), but a connection waiting for its next request sits in
  14111. // the poller instead of keeping a worker. A worker serves a connection while it
  14112. // has requests to read, then gives it back to this loop.
  14113. inline bool Server::parking_loop(TaskQueue &task_queue) {
  14114. using Clock = ParkingState::Clock;
  14115. using Connection = ParkingState::Connection;
  14116. const ParkingState::Token listen_token = 0;
  14117. const auto never = (Clock::time_point::max)();
  14118. auto &st = *parking_;
  14119. auto &poller = *st.poller;
  14120. std::vector<ParkingState::Token> ready;
  14121. poller.wait(0, ready); // drops a wake() left from an earlier stop()
  14122. {
  14123. std::lock_guard<std::mutex> guard(st.mutex);
  14124. st.closed = false;
  14125. }
  14126. // Publish the listening socket before checking that stop() has not taken it,
  14127. // so that a stop() from now on leaves closing it to this loop.
  14128. auto listen_sock = svr_sock_.load();
  14129. st.listen_sock = listen_sock;
  14130. auto listening = listen_sock != INVALID_SOCKET && svr_sock_ == listen_sock;
  14131. if (listening) { detail::set_nonblocking(listen_sock, true); }
  14132. auto listen_rearm_at = Clock::now(); // `never` while it is armed
  14133. auto fatal = false;
  14134. const auto check_interval =
  14135. std::chrono::duration_cast<Clock::duration>(std::chrono::microseconds(
  14136. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND));
  14137. // Never shorter than the interval keep_alive() first waits, so that a
  14138. // request sent right after connecting is served even with a timeout of 0.
  14139. const auto keep_alive =
  14140. (std::max)(Clock::duration(std::chrono::seconds(keep_alive_timeout_sec_)),
  14141. check_interval);
  14142. // Only an interval the user asked for: Windows' default exists for the sake
  14143. // of stop(), which wake() already serves here.
  14144. const auto idle = std::chrono::microseconds(
  14145. idle_interval_set_ ? idle_interval_sec_ * 1000000 + idle_interval_usec_
  14146. : 0);
  14147. auto next_idle = idle.count() > 0 ? Clock::now() + idle : never;
  14148. auto park = [&](Connection conn, Clock::time_point now) {
  14149. if (!st.park(std::move(conn), now + keep_alive)) {
  14150. output_error_log(Error::ResourceExhaustion, nullptr);
  14151. }
  14152. };
  14153. auto dispatch = [&](const Connection &conn) {
  14154. return task_queue.enqueue([this, conn]() { resume_connection(conn); });
  14155. };
  14156. // The only way into the queue besides the backlog, which nothing overtakes.
  14157. // When the queue is full, a new connection is turned away, as accept_loop()
  14158. // does, and an established one waits in the backlog, since closing it would
  14159. // lose its request. A TaskQueue gives no sign when it has room again, so the
  14160. // backlog is retried every check_interval.
  14161. auto submit = [&](Connection conn) {
  14162. if (st.backlog.empty() && dispatch(conn)) { return; }
  14163. if (conn->opened) {
  14164. st.backlog.push_back(std::move(conn));
  14165. return;
  14166. }
  14167. conn->close_idle();
  14168. output_error_log(Error::ResourceExhaustion, nullptr);
  14169. };
  14170. std::vector<Connection> returned;
  14171. while (listening && svr_sock_ == listen_sock) {
  14172. auto now = Clock::now();
  14173. if (now >= listen_rearm_at) {
  14174. listen_rearm_at =
  14175. poller.arm(listen_sock, listen_token) ? never : now + check_interval;
  14176. }
  14177. // At most a minute, which keeps the timeout below within an int.
  14178. auto until = (std::min)({st.next_deadline(), listen_rearm_at, next_idle,
  14179. st.backlog.empty() ? never : now + check_interval,
  14180. now + std::chrono::seconds(60)});
  14181. // Rounded up, so that the wait does not end just short of the deadline.
  14182. auto timeout = std::chrono::duration_cast<std::chrono::milliseconds>(
  14183. until - now + std::chrono::microseconds(999));
  14184. poller.wait(static_cast<int>((std::max)(timeout.count(),
  14185. std::chrono::milliseconds::rep(0))),
  14186. ready);
  14187. if (svr_sock_ != listen_sock) { break; }
  14188. now = Clock::now();
  14189. {
  14190. std::lock_guard<std::mutex> guard(st.mutex);
  14191. returned.swap(st.returned);
  14192. }
  14193. for (auto &conn : returned) {
  14194. park(std::move(conn), now);
  14195. }
  14196. returned.clear();
  14197. // Connections that found the queue full go first, in their order.
  14198. while (!st.backlog.empty() && dispatch(st.backlog.front())) {
  14199. st.backlog.pop_front();
  14200. }
  14201. for (auto token : ready) {
  14202. if (token == listen_token) {
  14203. listen_rearm_at = now;
  14204. // A batch per round, so that a burst of new connections does not
  14205. // hold up the ones that are ready.
  14206. for (auto i = 0; i < 64; i++) {
  14207. auto sock = detail::accept_socket(listen_sock);
  14208. if (sock == INVALID_SOCKET) {
  14209. if (detail::is_would_block_error()) { break; }
  14210. if (detail::is_accept_resource_error()) {
  14211. // Out of descriptors: let the deadlines free some first.
  14212. listen_rearm_at = now + check_interval;
  14213. break;
  14214. }
  14215. if (detail::is_accept_transient_error()) { continue; }
  14216. fatal = true;
  14217. break;
  14218. }
  14219. // Some platforms make it non-blocking like the listening socket.
  14220. detail::set_nonblocking(sock, false);
  14221. prepare_accepted_socket(sock);
  14222. park(new_keep_alive_connection(sock), now);
  14223. if (idle.count() > 0) { next_idle = now + idle; }
  14224. }
  14225. continue;
  14226. }
  14227. submit(st.unpark(token));
  14228. }
  14229. if (fatal) { break; }
  14230. st.expire(now);
  14231. if (now >= next_idle) {
  14232. task_queue.on_idle();
  14233. next_idle = now + idle;
  14234. }
  14235. }
  14236. // A worker still serving a request closes its connection itself.
  14237. st.close_all();
  14238. poller.disarm(listen_sock);
  14239. // See ParkingState::listen_sock.
  14240. if (st.listen_sock.exchange(INVALID_SOCKET) == INVALID_SOCKET) {
  14241. // stop() handed it over.
  14242. detail::shutdown_socket(listen_sock);
  14243. detail::close_socket(listen_sock);
  14244. return true;
  14245. }
  14246. return !(fatal && abandon_listen_socket());
  14247. }
  14248. inline std::shared_ptr<Server::KeepAliveConnection>
  14249. Server::new_keep_alive_connection(socket_t sock) {
  14250. return std::make_shared<PlainConnection>(sock, *this);
  14251. }
  14252. inline void
  14253. Server::resume_connection(std::shared_ptr<KeepAliveConnection> conn) {
  14254. auto &st = *parking_;
  14255. auto &c = *conn;
  14256. auto ret = c.resume();
  14257. if (c.turn.park) {
  14258. c.release_buffers(); // it may stay idle for long
  14259. if (st.give_back(conn)) { return; }
  14260. }
  14261. c.close_served(!c.turn.websocket_upgraded && ret);
  14262. }
  14263. inline void Server::output_log(const Request &req, const Response &res) const {
  14264. if (logger_) {
  14265. std::lock_guard<std::mutex> guard(logger_mutex_);
  14266. logger_(req, res);
  14267. }
  14268. }
  14269. inline void Server::output_pre_compression_log(const Request &req,
  14270. const Response &res) const {
  14271. if (pre_compression_logger_) {
  14272. std::lock_guard<std::mutex> guard(logger_mutex_);
  14273. pre_compression_logger_(req, res);
  14274. }
  14275. }
  14276. inline void Server::output_error_log(const Error &err,
  14277. const Request *req) const {
  14278. if (error_logger_) {
  14279. std::lock_guard<std::mutex> guard(logger_mutex_);
  14280. error_logger_(err, req);
  14281. }
  14282. }
  14283. /*
  14284. * Group 5: ClientImpl and Client (Universal) implementation
  14285. */
  14286. // HTTP client implementation
  14287. inline ClientImpl::ClientImpl(const std::string &host)
  14288. : ClientImpl(host, 80, std::string(), std::string()) {}
  14289. inline ClientImpl::ClientImpl(const std::string &host, int port)
  14290. : ClientImpl(host, port, std::string(), std::string()) {}
  14291. inline ClientImpl::ClientImpl(const std::string &host, int port,
  14292. const std::string &client_cert_path,
  14293. const std::string &client_key_path)
  14294. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  14295. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  14296. inline ClientImpl::~ClientImpl() {
  14297. // Wait until all the requests in flight are handled.
  14298. size_t retry_count = 10;
  14299. while (retry_count-- > 0) {
  14300. {
  14301. std::lock_guard<std::mutex> guard(socket_mutex_);
  14302. if (socket_requests_in_flight_ == 0) { break; }
  14303. }
  14304. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  14305. }
  14306. std::lock_guard<std::mutex> guard(socket_mutex_);
  14307. shutdown_socket(socket_);
  14308. close_socket(socket_);
  14309. }
  14310. inline bool ClientImpl::is_valid() const { return true; }
  14311. inline bool
  14312. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  14313. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  14314. if (no_proxy_entries_.empty()) { return true; }
  14315. // host_ is const so its normalized form is invariant; cache it. The
  14316. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  14317. if (host == host_) {
  14318. if (!host_normalized_valid_) {
  14319. host_normalized_ = detail::normalize_target(host_);
  14320. host_normalized_valid_ = true;
  14321. }
  14322. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  14323. }
  14324. auto target = detail::normalize_target(host);
  14325. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  14326. }
  14327. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  14328. if (is_proxy_enabled_for_host(host_)) {
  14329. return detail::create_client_socket(
  14330. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  14331. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  14332. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  14333. write_timeout_sec_, write_timeout_usec_, interface_, error,
  14334. stop_interrupt());
  14335. }
  14336. // Check is custom IP or hostname specified for host_
  14337. std::string connect_host;
  14338. std::string ip;
  14339. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  14340. return detail::create_client_socket(
  14341. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  14342. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  14343. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14344. write_timeout_usec_, interface_, error, stop_interrupt());
  14345. }
  14346. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  14347. Error &error) {
  14348. auto sock = create_client_socket(error);
  14349. if (sock == INVALID_SOCKET) { return false; }
  14350. socket.sock = sock;
  14351. return true;
  14352. }
  14353. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  14354. socket_tls_settings_version_ = tls_settings_version_;
  14355. return create_and_connect_socket(socket, error);
  14356. }
  14357. inline bool ClientImpl::setup_proxy_connection(
  14358. Socket & /*socket*/,
  14359. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  14360. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  14361. return true;
  14362. }
  14363. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  14364. bool /*shutdown_gracefully*/) {
  14365. // If there are any requests in flight from threads other than us, then it's
  14366. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  14367. assert(socket_requests_in_flight_ == 0 ||
  14368. socket_requests_are_from_thread_ == std::this_thread::get_id());
  14369. }
  14370. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  14371. if (socket.sock == INVALID_SOCKET) { return; }
  14372. detail::shutdown_socket(socket.sock);
  14373. }
  14374. inline void ClientImpl::close_socket(Socket &socket) {
  14375. // If there are requests in flight in another thread, usually closing
  14376. // the socket will be fine and they will simply receive an error when
  14377. // using the closed socket, but it is still a bug since rarely the OS
  14378. // may reassign the socket id to be used for a new socket, and then
  14379. // suddenly they will be operating on a live socket that is different
  14380. // than the one they intended!
  14381. assert(socket_requests_in_flight_ == 0 ||
  14382. socket_requests_are_from_thread_ == std::this_thread::get_id());
  14383. // It is also a bug if this happens while SSL is still active
  14384. #ifdef CPPHTTPLIB_SSL_ENABLED
  14385. assert(socket.ssl == nullptr);
  14386. #endif
  14387. if (socket.sock == INVALID_SOCKET) { return; }
  14388. detail::close_socket(socket.sock);
  14389. socket.sock = INVALID_SOCKET;
  14390. }
  14391. inline void ClientImpl::disconnect(bool gracefully) {
  14392. shutdown_ssl(socket_, gracefully);
  14393. shutdown_socket(socket_);
  14394. close_socket(socket_);
  14395. }
  14396. inline bool ClientImpl::socket_reusable() {
  14397. if (!socket_.is_open()) { return false; }
  14398. // RFC 9112 9.2: data with no request outstanding is not a response
  14399. if (detail::select_read(socket_.sock, 0, 0) != 0) {
  14400. disconnect(/*gracefully=*/false);
  14401. return false;
  14402. }
  14403. if (is_ssl() && socket_tls_settings_version_ != tls_settings_version_) {
  14404. disconnect(/*gracefully=*/true);
  14405. return false;
  14406. }
  14407. return true;
  14408. }
  14409. inline bool ClientImpl::prepare_socket(
  14410. std::unique_lock<std::mutex> &guard,
  14411. std::chrono::time_point<std::chrono::steady_clock> start_time,
  14412. Response &res, bool &success, Error &error) {
  14413. auto opened = true;
  14414. if (!socket_reusable()) {
  14415. Socket socket;
  14416. guard.unlock();
  14417. opened = ensure_socket_connection(socket, error);
  14418. if (opened) {
  14419. opened = setup_proxy_connection(socket, start_time, res, success, error);
  14420. } else {
  14421. success = false;
  14422. }
  14423. guard.lock();
  14424. socket_ = socket;
  14425. }
  14426. if (stop_requested_) {
  14427. disconnect(/*gracefully=*/false);
  14428. error = Error::Canceled;
  14429. success = false;
  14430. return false;
  14431. }
  14432. return opened;
  14433. }
  14434. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  14435. Response &res,
  14436. bool skip_100_continue) const {
  14437. std::array<char, 2048> buf{};
  14438. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  14439. if (!line_reader.getline()) { return false; }
  14440. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  14441. res.reason)) {
  14442. return req.method == "CONNECT";
  14443. }
  14444. // Skip interim (1xx) responses along with their header fields, except a 100
  14445. // Continue the caller handles itself for Expect: 100-continue. 101 ends
  14446. // HTTP on the connection, so it is final. A server sending them without end
  14447. // would hold the client, so there may be only so many.
  14448. size_t interim_count = 0;
  14449. while (100 <= res.status && res.status < 200 &&
  14450. res.status != StatusCode::SwitchingProtocol_101 &&
  14451. (skip_100_continue || res.status != StatusCode::Continue_100)) {
  14452. if (++interim_count > CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT) {
  14453. return false;
  14454. }
  14455. Headers interim_headers;
  14456. if (!detail::read_headers(strm, interim_headers)) { return false; }
  14457. if (!line_reader.getline()) { return false; } // next response line
  14458. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  14459. res.reason)) {
  14460. return false;
  14461. }
  14462. }
  14463. return true;
  14464. }
  14465. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  14466. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  14467. // A same-origin redirect and a digest retry send through here again. Only
  14468. // the call the caller made reports a failure, once, with its request.
  14469. auto outermost = send_depth_++ == 0;
  14470. auto se = detail::scope_exit([&] { send_depth_--; });
  14471. if (outermost) {
  14472. error = Error::Success;
  14473. stop_requested_ = false;
  14474. }
  14475. auto ret = send_(req, res, error);
  14476. if (error == Error::SSLPeerCouldBeClosed_) {
  14477. assert(!ret);
  14478. ret = send_(req, res, error);
  14479. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  14480. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  14481. }
  14482. // Also an answer that carries an error, such as a proxy's 407
  14483. if (outermost && error != Error::Success) { output_error_log(error, &req); }
  14484. return ret;
  14485. }
  14486. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  14487. #ifdef CPPHTTPLIB_SSL_ENABLED
  14488. // Don't let an earlier attempt's TLS error show up in this one's Result. A
  14489. // client that failed to set up its TLS context keeps reporting why.
  14490. if (is_valid()) {
  14491. last_ssl_error_ = 0;
  14492. last_backend_error_ = 0;
  14493. }
  14494. #endif
  14495. {
  14496. std::unique_lock<std::mutex> guard(socket_mutex_);
  14497. // Set this to false immediately - if it ever gets set to true by the end
  14498. // of the request, we know another thread instructed us to close the
  14499. // socket.
  14500. socket_should_be_closed_when_request_is_done_ = false;
  14501. auto success = true;
  14502. if (!prepare_socket(guard, req.start_time_, res, success, error)) {
  14503. return success;
  14504. }
  14505. // Mark the current socket as being in use so that it cannot be closed by
  14506. // anyone else while this request is ongoing, even though we will be
  14507. // releasing the mutex.
  14508. if (socket_requests_in_flight_ > 1) {
  14509. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  14510. }
  14511. socket_requests_in_flight_ += 1;
  14512. socket_requests_are_from_thread_ = std::this_thread::get_id();
  14513. }
  14514. for (const auto &header : default_headers_) {
  14515. if (req.headers.find(header.first) == req.headers.end()) {
  14516. req.headers.insert(header);
  14517. }
  14518. }
  14519. auto ret = false;
  14520. auto close_connection = !keep_alive_;
  14521. auto se = detail::scope_exit([&]() {
  14522. // Briefly lock mutex in order to mark that a request is no longer ongoing
  14523. std::lock_guard<std::mutex> guard(socket_mutex_);
  14524. socket_requests_in_flight_ -= 1;
  14525. if (socket_requests_in_flight_ <= 0) {
  14526. assert(socket_requests_in_flight_ == 0);
  14527. socket_requests_are_from_thread_ = std::thread::id();
  14528. }
  14529. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  14530. !ret) {
  14531. disconnect(/*gracefully=*/true);
  14532. }
  14533. });
  14534. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  14535. strm.set_read_interrupt(stop_interrupt());
  14536. return handle_request(strm, req, res, close_connection, error);
  14537. });
  14538. if (!ret) {
  14539. if (error == Error::Success) { error = Error::Unknown; }
  14540. }
  14541. return ret;
  14542. }
  14543. inline Result ClientImpl::send(const Request &req) {
  14544. auto req2 = req;
  14545. return send_(std::move(req2));
  14546. }
  14547. inline Result ClientImpl::send_(Request &&req) {
  14548. auto res = detail::make_unique<Response>();
  14549. auto error = Error::Success;
  14550. #ifdef CPPHTTPLIB_SSL_ENABLED
  14551. // Hold the request lock until the Result has read this request's TLS error
  14552. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  14553. #endif
  14554. auto ret = send(req, *res, error);
  14555. #ifdef CPPHTTPLIB_SSL_ENABLED
  14556. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  14557. last_ssl_error_, last_backend_error_};
  14558. #else
  14559. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  14560. #endif
  14561. }
  14562. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  14563. const std::string &ct) {
  14564. (void)for_stream;
  14565. // Default headers are meant for the origin and may carry its credentials, so
  14566. // keep them off the CONNECT request the proxy reads.
  14567. if (r.method != "CONNECT") {
  14568. for (const auto &header : default_headers_) {
  14569. if (!r.has_header(header.first)) { r.headers.insert(header); }
  14570. }
  14571. }
  14572. // RFC 9110 5.3 recommends sending control data such as Host first, so
  14573. // prepend it rather than appending it after the caller's own fields.
  14574. if (!r.has_header("Host")) {
  14575. r.headers.emplace_front(
  14576. "Host", detail::make_default_host_header_value(host_, port_, is_ssl(),
  14577. address_family_));
  14578. }
  14579. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  14580. if (!r.content_receiver) {
  14581. if (!r.has_header("Accept-Encoding")) {
  14582. std::string accept_encoding;
  14583. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14584. accept_encoding = "br";
  14585. #endif
  14586. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14587. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  14588. accept_encoding += "gzip, deflate";
  14589. #endif
  14590. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14591. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  14592. accept_encoding += "zstd";
  14593. #endif
  14594. r.set_header("Accept-Encoding", accept_encoding);
  14595. }
  14596. detail::add_default_user_agent_header(r);
  14597. }
  14598. if (!r.body.empty()) {
  14599. if (!ct.empty() && !r.has_header("Content-Type")) {
  14600. r.headers.emplace("Content-Type", ct);
  14601. }
  14602. if (!r.has_header("Content-Length")) {
  14603. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  14604. }
  14605. }
  14606. }
  14607. inline ClientImpl::StreamHandle
  14608. ClientImpl::open_stream(const std::string &method, const std::string &path,
  14609. const Params &params, const Headers &headers,
  14610. const std::string &body,
  14611. const std::string &content_type) {
  14612. // Encode the target exactly like the buffered send path does, so that the
  14613. // same `path` produces the same request line through either API.
  14614. auto raw_query_path =
  14615. params.empty() ? path : append_query_params(path, params);
  14616. Request req;
  14617. req.method = method;
  14618. req.path = detail::encode_request_target(raw_query_path, path_encode_);
  14619. req.headers = headers;
  14620. req.body = body;
  14621. prepare_default_headers(req, true, content_type);
  14622. auto handle = open_stream_(req);
  14623. // Like a buffered request, a stream that fails to open is reported once
  14624. if (handle.error != Error::Success) { output_error_log(handle.error, &req); }
  14625. return handle;
  14626. }
  14627. inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) {
  14628. StreamHandle handle;
  14629. handle.response = detail::make_unique<Response>();
  14630. handle.error = Error::Success;
  14631. handle.connection_ = detail::make_unique<ClientConnection>();
  14632. {
  14633. // A request in flight uses socket_ without holding socket_mutex_
  14634. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  14635. if (send_depth_ == 0) { stop_requested_ = false; }
  14636. std::unique_lock<std::mutex> guard(socket_mutex_);
  14637. auto success = true;
  14638. if (!prepare_socket(guard, std::chrono::steady_clock::now(),
  14639. *handle.response, success, handle.error)) {
  14640. if (!success) { handle.response.reset(); }
  14641. return handle;
  14642. }
  14643. transfer_socket_ownership_to_handle(handle);
  14644. }
  14645. #ifdef CPPHTTPLIB_SSL_ENABLED
  14646. if (is_ssl() && handle.connection_->session) {
  14647. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  14648. handle.connection_->sock, handle.connection_->session,
  14649. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14650. write_timeout_usec_);
  14651. } else {
  14652. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  14653. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  14654. write_timeout_sec_, write_timeout_usec_);
  14655. }
  14656. #else
  14657. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  14658. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  14659. write_timeout_sec_, write_timeout_usec_);
  14660. #endif
  14661. handle.stream_ = handle.socket_stream_.get();
  14662. auto &strm = *handle.stream_;
  14663. // Only for the head, as the handle may outlive this client
  14664. strm.set_read_interrupt(stop_interrupt());
  14665. auto release_interrupt =
  14666. detail::scope_exit([&] { strm.set_read_interrupt(nullptr); });
  14667. // After connecting, as for a buffered request
  14668. add_credential_headers(req);
  14669. // Build the request line and headers in memory first, like write_request()
  14670. // does, so that a rejected header leaves nothing on the wire.
  14671. {
  14672. detail::BufferStream bstrm;
  14673. // The path follows the authority in absolute-form, so one that does not
  14674. // begin with '/' (e.g. "@evil.example/x") would name another host.
  14675. auto prefix = proxy_target_prefix();
  14676. if ((!prefix.empty() && req.path[0] != '/') ||
  14677. detail::write_request_line(bstrm, req.method, prefix + req.path) < 0) {
  14678. handle.error = Error::Write;
  14679. handle.response.reset();
  14680. return handle;
  14681. }
  14682. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  14683. handle.error)) {
  14684. handle.response.reset();
  14685. return handle;
  14686. }
  14687. const auto &data = bstrm.get_buffer();
  14688. if (!detail::write_data(strm, data.data(), data.size())) {
  14689. handle.error = Error::Write;
  14690. handle.response.reset();
  14691. return handle;
  14692. }
  14693. }
  14694. if (!req.body.empty()) {
  14695. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  14696. handle.error = Error::Write;
  14697. handle.response.reset();
  14698. return handle;
  14699. }
  14700. }
  14701. if (!read_response_line(strm, req, *handle.response) ||
  14702. !detail::read_headers(strm, handle.response->headers)) {
  14703. handle.error = Error::Read;
  14704. handle.response.reset();
  14705. return handle;
  14706. }
  14707. handle.body_reader_.stream = handle.stream_;
  14708. handle.body_reader_.payload_max_length = payload_max_length_;
  14709. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  14710. // header section, so none of its framing or coding headers apply.
  14711. if (req.method == "HEAD" ||
  14712. handle.response->status == StatusCode::NoContent_204 ||
  14713. handle.response->status == StatusCode::NotModified_304) {
  14714. handle.body_reader_.eof = true;
  14715. return handle;
  14716. }
  14717. // Same framing check as ClientImpl::process_request()
  14718. if (detail::has_conflicting_content_length(handle.response->headers)) {
  14719. handle.error = Error::Read;
  14720. handle.response.reset();
  14721. return handle;
  14722. }
  14723. if (handle.response->has_header("Content-Length")) {
  14724. bool is_invalid = false;
  14725. auto content_length = detail::get_header_value_u64(
  14726. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  14727. if (is_invalid) {
  14728. handle.error = Error::Read;
  14729. handle.response.reset();
  14730. return handle;
  14731. }
  14732. handle.body_reader_.has_content_length = true;
  14733. handle.body_reader_.content_length = content_length;
  14734. }
  14735. handle.body_reader_.chunked =
  14736. detail::is_chunked_transfer_encoding(handle.response->headers);
  14737. auto content_encoding = detail::get_combined_header_value(
  14738. handle.response->headers, "Content-Encoding");
  14739. if (decompress_ && !content_encoding.empty()) {
  14740. // Same policy as prepare_content_receiver(): reject a coding we know about
  14741. // but were not built with, pass an unrecognized one through as-is.
  14742. handle.decompressor_ = detail::create_decompressor(content_encoding);
  14743. if (!handle.decompressor_) {
  14744. if (detail::is_known_content_encoding(content_encoding)) {
  14745. handle.error = Error::UnsupportedContentEncoding;
  14746. handle.response.reset();
  14747. return handle;
  14748. }
  14749. } else if (!handle.decompressor_->is_valid()) {
  14750. handle.error = Error::Compression;
  14751. handle.response.reset();
  14752. return handle;
  14753. }
  14754. }
  14755. return handle;
  14756. }
  14757. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  14758. if (!is_valid() || !response) { return -1; }
  14759. auto n = decompressor_
  14760. ? read_with_decompression(buf, len)
  14761. : detail::read_body_content(stream_, body_reader_, buf, len);
  14762. if (n == 0) { parse_trailers_if_needed(); }
  14763. return n;
  14764. }
  14765. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  14766. size_t len) {
  14767. if (decompress_offset_ < decompress_buffer_.size()) {
  14768. auto available = decompress_buffer_.size() - decompress_offset_;
  14769. auto to_copy = (std::min)(len, available);
  14770. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  14771. decompress_offset_ += to_copy;
  14772. decompressed_bytes_read_ += to_copy;
  14773. return static_cast<ssize_t>(to_copy);
  14774. }
  14775. decompress_buffer_.clear();
  14776. decompress_offset_ = 0;
  14777. constexpr size_t kDecompressionBufferSize = 8192;
  14778. char compressed_buf[kDecompressionBufferSize];
  14779. while (true) {
  14780. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  14781. sizeof(compressed_buf));
  14782. if (n <= 0) { return n; }
  14783. auto exceeded = false;
  14784. bool decompress_ok = decompressor_->decompress(
  14785. compressed_buf, static_cast<size_t>(n),
  14786. [&](const char *data, size_t data_len) {
  14787. decompress_buffer_.append(data, data_len);
  14788. auto limit = body_reader_.payload_max_length;
  14789. exceeded =
  14790. limit > 0 &&
  14791. decompressed_bytes_read_ + decompress_buffer_.size() > limit;
  14792. return !exceeded;
  14793. });
  14794. if (!decompress_ok) {
  14795. body_reader_.last_error =
  14796. exceeded ? Error::ExceedMaxPayloadSize : Error::Read;
  14797. return -1;
  14798. }
  14799. if (!decompress_buffer_.empty()) { break; }
  14800. }
  14801. auto to_copy = (std::min)(len, decompress_buffer_.size());
  14802. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  14803. decompress_offset_ = to_copy;
  14804. decompressed_bytes_read_ += to_copy;
  14805. return static_cast<ssize_t>(to_copy);
  14806. }
  14807. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  14808. // The trailers follow the last chunk, so there are none before it
  14809. auto &decoder = body_reader_.chunked_decoder;
  14810. if (!response || trailers_parsed_ || !decoder || !decoder->finished) {
  14811. return;
  14812. }
  14813. trailers_parsed_ = true;
  14814. decoder->parse_trailers_into(response->trailers, response->headers);
  14815. }
  14816. namespace detail {
  14817. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  14818. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  14819. size_t &out_chunk_offset,
  14820. size_t &out_chunk_total) {
  14821. if (finished) { return 0; }
  14822. if (chunk_remaining == 0) {
  14823. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  14824. if (!lr.getline()) { return -1; }
  14825. // Everything below is bounded by eol rather than by the buffer's NUL, so
  14826. // the line terminator is never mistaken for line content.
  14827. const char *eol = lr.ptr() + lr.size();
  14828. if (lr.end_with_crlf()) {
  14829. eol -= 2;
  14830. } else if (eol != lr.ptr() && eol[-1] == '\n') {
  14831. // Only reachable under CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR, where
  14832. // getline() ends the line on a bare LF. That LF is the terminator, so it
  14833. // has to come off here or the check below would reject the line.
  14834. eol -= 1;
  14835. }
  14836. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  14837. const char *p = lr.ptr();
  14838. int v = 0;
  14839. if (p == eol || !is_hex(*p, v)) { return -1; }
  14840. size_t chunk_len = 0;
  14841. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  14842. for (; p < eol && is_hex(*p, v); ++p) {
  14843. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  14844. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  14845. }
  14846. while (p < eol && is_space_or_tab(*p)) {
  14847. ++p;
  14848. }
  14849. // RFC 9112 §7.1.1: only a chunk-ext may sit between the size and the line
  14850. // terminator, and it is built from tokens and quoted-strings, so it never
  14851. // holds a CR, LF or any other control character. getline() reads up to the
  14852. // CRLF, so a bare LF left in here would be swallowed as extension text
  14853. // while an intermediary that ends the line on it delimits the chunks
  14854. // differently, and the two disagree on where the body ends (request
  14855. // smuggling).
  14856. if (p < eol && *p != ';') { return -1; }
  14857. for (; p < eol; ++p) {
  14858. if (!is_space_or_tab(*p) && !fields::is_field_vchar(*p)) { return -1; }
  14859. }
  14860. // The bytes around the data are no payload, so they are counted on their
  14861. // own, as Go does: each chunk may spend 16 bytes and twice its data on
  14862. // them, which lets a stream send a byte at a time, and what goes past that
  14863. // in padding, leading zeros and extensions builds up to one header field.
  14864. overhead += lr.size() + 2;
  14865. overhead = overhead > 16 ? overhead - 16 : 0;
  14866. overhead = chunk_len > overhead / 2 ? 0 : overhead - 2 * chunk_len;
  14867. if (overhead > CPPHTTPLIB_HEADER_MAX_LENGTH) { return -1; }
  14868. if (chunk_len == 0) {
  14869. chunk_remaining = 0;
  14870. finished = true;
  14871. out_chunk_offset = 0;
  14872. out_chunk_total = 0;
  14873. return 0;
  14874. }
  14875. chunk_remaining = chunk_len;
  14876. last_chunk_total = chunk_remaining;
  14877. last_chunk_offset = 0;
  14878. }
  14879. auto to_read = (std::min)(chunk_remaining, len);
  14880. auto n = strm.read(buf, to_read);
  14881. if (n <= 0) { return -1; }
  14882. auto offset_before = last_chunk_offset;
  14883. last_chunk_offset += static_cast<size_t>(n);
  14884. chunk_remaining -= static_cast<size_t>(n);
  14885. out_chunk_offset = offset_before;
  14886. out_chunk_total = last_chunk_total;
  14887. if (chunk_remaining == 0) {
  14888. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  14889. if (!lr.getline()) { return -1; }
  14890. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  14891. }
  14892. return n;
  14893. }
  14894. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  14895. const Headers &src_headers) {
  14896. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  14897. if (!lr.getline()) { return false; }
  14898. return parse_trailers(lr, dest, src_headers);
  14899. }
  14900. // Only 301, 302, 303, 307 and 308 redirect. Any other 3xx, such as a 304, or
  14901. // a redirect without a Location, is a final response.
  14902. inline bool is_redirect(const Response &res) {
  14903. switch (res.status) {
  14904. case StatusCode::MovedPermanently_301:
  14905. case StatusCode::Found_302:
  14906. case StatusCode::SeeOther_303:
  14907. case StatusCode::TemporaryRedirect_307:
  14908. case StatusCode::PermanentRedirect_308:
  14909. return !res.get_header_value("Location").empty();
  14910. default: return false;
  14911. }
  14912. }
  14913. } // namespace detail
  14914. inline void
  14915. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  14916. handle.connection_->sock = socket_.sock;
  14917. #ifdef CPPHTTPLIB_SSL_ENABLED
  14918. handle.connection_->session = socket_.ssl;
  14919. socket_.ssl = nullptr;
  14920. #endif
  14921. socket_.sock = INVALID_SOCKET;
  14922. }
  14923. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2)
  14924. inline std::string ClientImpl::proxy_target_prefix() const {
  14925. if (is_ssl() || !is_proxy_enabled_for_host(host_)) { return std::string(); }
  14926. return "http://" + detail::make_host_and_port_string(host_, port_, false);
  14927. }
  14928. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  14929. Response &res, bool close_connection,
  14930. Error &error) {
  14931. if (req.path.empty()) {
  14932. error = Error::Connection;
  14933. return false;
  14934. }
  14935. auto req_save = req;
  14936. bool ret;
  14937. auto prefix = proxy_target_prefix();
  14938. if (!prefix.empty()) {
  14939. // The path follows the authority in absolute-form, so one that does not
  14940. // begin with '/' (e.g. "@evil.example/x") would name another host.
  14941. if (req.path[0] != '/') {
  14942. error = Error::Write;
  14943. return false;
  14944. }
  14945. auto req2 = req;
  14946. req2.path = prefix + req.path;
  14947. ret = process_request(strm, req2, res, close_connection, error);
  14948. req = std::move(req2);
  14949. req.path = req_save.path;
  14950. } else {
  14951. ret = process_request(strm, req, res, close_connection, error);
  14952. }
  14953. if (!ret) { return false; }
  14954. {
  14955. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  14956. // for this to be safe.
  14957. // This is safe to call because handle_request is only called by send_
  14958. // which locks the request mutex during the process. It would be a bug
  14959. // to call it from a different thread since it's a thread-safety issue
  14960. // to do these things to the socket if another thread is using the socket.
  14961. std::lock_guard<std::mutex> guard(socket_mutex_);
  14962. // Also when the request asked for it (e.g. a body that was never sent,
  14963. // or "Connection: close") or bytes follow the response (RFC 9112 9.2), so
  14964. // that a redirect or an auth retry below does not reuse the socket.
  14965. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  14966. strm.is_readable() ||
  14967. detail::has_header_token(res.headers, "Connection", "close") ||
  14968. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  14969. disconnect(/*gracefully=*/true);
  14970. }
  14971. }
  14972. if (follow_location_ && detail::is_redirect(res)) {
  14973. req = std::move(req_save);
  14974. // The client that followed the redirect has answered any challenge it
  14975. // could. Retrying below would sign another host's challenge and send it
  14976. // here.
  14977. return redirect(req, res, error);
  14978. }
  14979. #ifdef CPPHTTPLIB_SSL_ENABLED
  14980. if ((res.status == StatusCode::Unauthorized_401 ||
  14981. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  14982. req.authorization_count_ < 5) {
  14983. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  14984. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  14985. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  14986. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  14987. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  14988. return ret;
  14989. }
  14990. const auto &username =
  14991. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  14992. const auto &password =
  14993. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  14994. if (!username.empty() && !password.empty()) {
  14995. std::map<std::string, std::string> auth;
  14996. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  14997. Request new_req = req;
  14998. new_req.authorization_count_ += 1;
  14999. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  15000. : "Authorization");
  15001. new_req.headers.insert(detail::make_digest_authentication_header(
  15002. req, make_request_target(req), auth, new_req.authorization_count_,
  15003. detail::random_string(10), username, password, is_proxy));
  15004. Response new_res;
  15005. ret = send(new_req, new_res, error);
  15006. if (ret) { res = std::move(new_res); }
  15007. }
  15008. }
  15009. }
  15010. #endif
  15011. return ret;
  15012. }
  15013. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  15014. if (req.redirect_count_ == 0) {
  15015. error = Error::ExceedRedirectCount;
  15016. return false;
  15017. }
  15018. auto location = res.get_header_value("location");
  15019. if (location.empty()) { return false; }
  15020. auto next_url = detail::resolve_relative_location(location, req.path);
  15021. detail::UrlComponents uc;
  15022. if (!detail::parse_url(next_url, uc)) { return false; }
  15023. // Follow only http/https URLs and references starting with '/'
  15024. if (next_url[0] != '/' && uc.scheme != "http" && uc.scheme != "https") {
  15025. return false;
  15026. }
  15027. auto scheme = is_ssl() ? "https" : "http";
  15028. auto next_scheme = std::move(uc.scheme);
  15029. auto next_host = std::move(uc.host);
  15030. auto port_str = std::move(uc.port);
  15031. auto next_path = std::move(uc.path);
  15032. auto next_query = std::move(uc.query);
  15033. auto next_port = port_;
  15034. if (!port_str.empty()) {
  15035. if (!detail::parse_port(port_str, next_port)) { return false; }
  15036. } else if (!next_scheme.empty()) {
  15037. next_port = next_scheme == "https" ? 443 : 80;
  15038. }
  15039. if (next_scheme.empty()) { next_scheme = scheme; }
  15040. if (next_host.empty()) { next_host = host_; }
  15041. if (next_path.empty()) { next_path = "/"; }
  15042. // An absolute or absolute-path location can have dot segments too.
  15043. if (next_path[0] == '/') {
  15044. next_path = detail::remove_dot_segments(next_path);
  15045. }
  15046. auto path = std::move(next_path) + next_query;
  15047. // A Unix socket client sends "Host: localhost", so a Location naming
  15048. // localhost names this client too.
  15049. auto is_same_host = next_host == host_ ||
  15050. (address_family_ == AF_UNIX && next_host == "localhost");
  15051. // Same host redirect - use current client
  15052. if (next_scheme == scheme && is_same_host && next_port == port_) {
  15053. return detail::redirect(*this, req, res, path, location, error);
  15054. }
  15055. // Cross-host/scheme redirect - create new client with robust setup
  15056. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  15057. path, location, error);
  15058. }
  15059. // New method for robust redirect client creation
  15060. inline bool ClientImpl::create_redirect_client(
  15061. const std::string &scheme, const std::string &host, int port, Request &req,
  15062. Response &res, const std::string &path, const std::string &location,
  15063. Error &error) {
  15064. // Determine if we need SSL
  15065. auto need_ssl = (scheme == "https");
  15066. // Clean up request headers that are host/client specific
  15067. // Remove headers that should not be carried over to new host
  15068. auto headers_to_remove = std::vector<std::string>{
  15069. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  15070. for (const auto &header_name : headers_to_remove) {
  15071. auto it = req.headers.find(header_name);
  15072. while (it != req.headers.end()) {
  15073. it = req.headers.erase(it);
  15074. it = req.headers.find(header_name);
  15075. }
  15076. }
  15077. // Create appropriate client type and handle redirect
  15078. if (need_ssl) {
  15079. #ifdef CPPHTTPLIB_SSL_ENABLED
  15080. // Create SSL client for HTTPS redirect
  15081. SSLClient redirect_client(host, port);
  15082. // Setup basic client configuration first
  15083. setup_redirect_client(redirect_client);
  15084. redirect_client.enable_server_certificate_verification(
  15085. server_certificate_verification_);
  15086. redirect_client.enable_server_hostname_verification(
  15087. server_hostname_verification_);
  15088. redirect_client.system_ca_mode_ = system_ca_mode_;
  15089. // Transfer CA certificate to redirect client
  15090. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  15091. if (is_ssl()) {
  15092. auto &self = static_cast<SSLClient &>(*this);
  15093. // A store given to set_ca_cert_store() lives only in this client's
  15094. // context, which then holds all that is trusted.
  15095. if (self.ca_cert_store_set_) {
  15096. std::string pem;
  15097. {
  15098. std::lock_guard<std::mutex> guard(self.ctx_mutex_);
  15099. pem = detail::ca_certs_to_pem(self.ctx_);
  15100. }
  15101. redirect_client.load_ca_cert_store(pem.data(), pem.size());
  15102. redirect_client.ca_cert_store_set_ = true;
  15103. } else if (self.custom_ca_loaded_) {
  15104. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  15105. ca_cert_pem_.size());
  15106. }
  15107. redirect_client.set_session_verifier(self.session_verifier_);
  15108. if (self.server_certificate_verifier_) {
  15109. redirect_client.set_server_certificate_verifier(
  15110. self.server_certificate_verifier_);
  15111. }
  15112. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15113. redirect_client.enable_windows_cert_verification_ =
  15114. self.enable_windows_cert_verification_;
  15115. #endif
  15116. }
  15117. // Client certificates are set through constructor for SSLClient
  15118. // NOTE: SSLClient constructor already takes client_cert_path and
  15119. // client_key_path so we need to create it properly if client certs are
  15120. // needed
  15121. // Execute the redirect
  15122. return detail::redirect(redirect_client, req, res, path, location, error);
  15123. #else
  15124. // SSL not supported - set appropriate error
  15125. error = Error::SSLConnection;
  15126. return false;
  15127. #endif
  15128. } else {
  15129. // HTTP redirect
  15130. ClientImpl redirect_client(host, port);
  15131. // Setup client with robust configuration
  15132. setup_redirect_client(redirect_client);
  15133. // Execute the redirect
  15134. return detail::redirect(redirect_client, req, res, path, location, error);
  15135. }
  15136. }
  15137. // New method for robust client setup (based on basic_manual_redirect.cpp
  15138. // logic)
  15139. template <typename ClientType>
  15140. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  15141. // Copy basic settings first
  15142. client.set_connection_timeout(connection_timeout_sec_,
  15143. connection_timeout_usec_);
  15144. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  15145. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  15146. client.set_max_timeout(max_timeout_msec_);
  15147. if (has_payload_max_length_) {
  15148. client.set_payload_max_length(payload_max_length_);
  15149. }
  15150. client.set_keep_alive(keep_alive_);
  15151. client.set_follow_location(
  15152. true); // Enable redirects to handle multi-step redirects
  15153. client.set_path_encode(path_encode_);
  15154. client.set_compress(compress_);
  15155. client.set_decompress(decompress_);
  15156. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  15157. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  15158. // 15.4, credentials must not be forwarded when redirecting to a different
  15159. // host. This function is only called for cross-host redirects; same-host
  15160. // redirects are handled directly in ClientImpl::redirect().
  15161. // Copy the proxy configuration unconditionally; the per-target bypass is
  15162. // re-evaluated at send time, so a later hop to a non-bypassed host can
  15163. // still use the proxy.
  15164. client.no_proxy_entries_ = no_proxy_entries_;
  15165. if (!proxy_host_.empty() && proxy_port_ != -1) {
  15166. client.set_proxy(proxy_host_, proxy_port_);
  15167. if (!proxy_basic_auth_username_.empty() ||
  15168. !proxy_basic_auth_password_.empty()) {
  15169. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  15170. proxy_basic_auth_password_);
  15171. }
  15172. if (!proxy_bearer_token_auth_token_.empty()) {
  15173. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  15174. }
  15175. #ifdef CPPHTTPLIB_SSL_ENABLED
  15176. if (!proxy_digest_auth_username_.empty()) {
  15177. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  15178. proxy_digest_auth_password_);
  15179. }
  15180. #endif
  15181. }
  15182. // Copy network and socket settings
  15183. client.addr_map_ = addr_map_;
  15184. client.tunnel_addr_map_ = tunnel_addr_map_;
  15185. // A Unix socket client reaches every host through its own socket, as curl's
  15186. // --unix-socket does, unless the caller mapped that host elsewhere. The
  15187. // Location's host is never taken as a socket path.
  15188. if (address_family_ == AF_UNIX) {
  15189. auto &target = client.addr_map_[client.host()];
  15190. if (target.empty()) { target = detail::addr_map_target(addr_map_, host_); }
  15191. }
  15192. client.set_address_family(address_family_);
  15193. client.set_tcp_nodelay(tcp_nodelay_);
  15194. client.set_ipv6_v6only(ipv6_v6only_);
  15195. if (socket_options_) { client.set_socket_options(socket_options_); }
  15196. if (!interface_.empty()) { client.set_interface(interface_); }
  15197. // Copy logging and headers. Not the error logger: a failure comes back to
  15198. // this client's send(), which reports it with the caller's request.
  15199. if (logger_) { client.set_logger(logger_); }
  15200. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  15201. // Each new client should generate its own headers based on its target host
  15202. }
  15203. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  15204. const Request &req,
  15205. Error &error) const {
  15206. auto is_shutting_down = []() { return false; };
  15207. if (req.is_chunked_content_provider_) {
  15208. auto compressor = compress_ ? detail::create_compressor().first
  15209. : std::unique_ptr<detail::compressor>();
  15210. if (!compressor) {
  15211. compressor = detail::make_unique<detail::nocompressor>();
  15212. }
  15213. return detail::write_content_chunked(strm, req.content_provider_,
  15214. is_shutting_down, *compressor, error);
  15215. } else {
  15216. return detail::write_content_with_progress(
  15217. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  15218. req.upload_progress, error);
  15219. }
  15220. }
  15221. // What goes on the request line for req: its path, encoded and without the
  15222. // fragment, with `req.params` as the query when the path has none.
  15223. inline std::string ClientImpl::make_request_target(const Request &req) const {
  15224. auto target = detail::encode_request_target(req.path, path_encode_);
  15225. if (detail::query_of(req.path).empty() && !req.params.empty()) {
  15226. target = append_query_params(target, req.params);
  15227. }
  15228. return target;
  15229. }
  15230. inline void ClientImpl::add_credential_headers(Request &req) {
  15231. // A CONNECT request is read by the proxy; everything sent through the tunnel
  15232. // it opens is read by the origin. Each credential goes only to its own hop.
  15233. auto is_connect = req.method == "CONNECT";
  15234. if (!is_connect) {
  15235. detail::add_authorization_header(req, basic_auth_username_,
  15236. basic_auth_password_,
  15237. bearer_token_auth_token_, false);
  15238. }
  15239. // Proxy-Authorization is only sent when the proxy reads this message —
  15240. // otherwise NO_PROXY-matched requests, and requests inside a TLS tunnel,
  15241. // would leak proxy credentials to the destination server.
  15242. if (is_proxy_enabled_for_host(host_) && (!is_ssl() || is_connect)) {
  15243. detail::add_authorization_header(req, proxy_basic_auth_username_,
  15244. proxy_basic_auth_password_,
  15245. proxy_bearer_token_auth_token_, true);
  15246. }
  15247. }
  15248. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  15249. bool close_connection, Error &error,
  15250. bool skip_body, bool &rejected_locally) {
  15251. rejected_locally = false;
  15252. // Prepare additional headers
  15253. if (close_connection) {
  15254. if (!req.has_header("Connection")) {
  15255. req.set_header("Connection", "close");
  15256. }
  15257. }
  15258. std::string ct_for_defaults;
  15259. if (!req.has_header("Content-Type") && !req.body.empty()) {
  15260. ct_for_defaults = "text/plain";
  15261. }
  15262. prepare_default_headers(req, false, ct_for_defaults);
  15263. if (req.body.empty()) {
  15264. if (req.content_provider_) {
  15265. if (!req.is_chunked_content_provider_) {
  15266. if (!req.has_header("Content-Length")) {
  15267. auto length = std::to_string(req.content_length_);
  15268. req.set_header("Content-Length", length);
  15269. }
  15270. }
  15271. } else {
  15272. if (req.method == "POST" || req.method == "PUT" ||
  15273. req.method == "PATCH") {
  15274. req.set_header("Content-Length", "0");
  15275. }
  15276. }
  15277. }
  15278. add_credential_headers(req);
  15279. // Request line and headers
  15280. {
  15281. detail::BufferStream bstrm;
  15282. auto path_with_query = make_request_target(req);
  15283. // The query already came in through `req.path`; still populate
  15284. // `req.params` for handlers/users who read them.
  15285. auto query_part = detail::query_of(req.path);
  15286. if (!query_part.empty()) {
  15287. detail::parse_query_text(query_part, req.params);
  15288. }
  15289. // Write request line and headers
  15290. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  15291. // A rejected method (not a token, e.g. carrying CR/LF) or target (e.g.
  15292. // CR/LF in a caller-supplied path under set_path_encode(false)) must
  15293. // fail the request cleanly instead of emitting a request-line-less,
  15294. // header-injecting request.
  15295. error = Error::Write;
  15296. rejected_locally = true;
  15297. return false;
  15298. }
  15299. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  15300. error)) {
  15301. rejected_locally = true;
  15302. return false;
  15303. }
  15304. // Flush buffer
  15305. auto &data = bstrm.get_buffer();
  15306. if (!detail::write_data(strm, data.data(), data.size())) {
  15307. error = Error::Write;
  15308. return false;
  15309. }
  15310. }
  15311. // After sending request line and headers, wait briefly for an early server
  15312. // response (e.g. 4xx) and avoid sending a potentially large request body
  15313. // unnecessarily. This workaround is only enabled on Windows because Unix
  15314. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  15315. // buffering can accept large writes even when the peer already responded.
  15316. // Check the stream first (which covers SSL via `is_readable()`), then
  15317. // fall back to select on the socket. Only perform the wait for very large
  15318. // request bodies to avoid interfering with normal small requests and
  15319. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  15320. // response. Skip this check when using Expect: 100-continue, as the protocol
  15321. // handles early responses properly.
  15322. #if defined(_WIN32)
  15323. if (!skip_body &&
  15324. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  15325. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  15326. auto start = std::chrono::high_resolution_clock::now();
  15327. for (;;) {
  15328. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  15329. // from SSL internals. If the underlying socket is readable, assume an
  15330. // early response may be present.
  15331. auto sock = strm.socket();
  15332. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  15333. return false;
  15334. }
  15335. // Fallback to stream-level check for non-socket streams or when the
  15336. // socket isn't reporting readable. Avoid using `is_readable()` for
  15337. // SSL, since `SSL_pending()` may report buffered records that do not
  15338. // indicate a complete application-level response yet.
  15339. if (!is_ssl() && strm.is_readable()) { return false; }
  15340. auto now = std::chrono::high_resolution_clock::now();
  15341. auto elapsed =
  15342. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  15343. .count();
  15344. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  15345. break;
  15346. }
  15347. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  15348. }
  15349. }
  15350. #endif
  15351. // Body
  15352. if (skip_body) { return true; }
  15353. return write_request_body(strm, req, error);
  15354. }
  15355. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  15356. Error &error) {
  15357. if (req.body.empty()) {
  15358. return write_content_with_provider(strm, req, error);
  15359. }
  15360. if (req.upload_progress) {
  15361. auto body_size = req.body.size();
  15362. size_t written = 0;
  15363. auto data = req.body.data();
  15364. while (written < body_size) {
  15365. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  15366. if (!detail::write_data(strm, data + written, to_write)) {
  15367. error = Error::Write;
  15368. return false;
  15369. }
  15370. written += to_write;
  15371. if (!req.upload_progress(written, body_size)) {
  15372. error = Error::Canceled;
  15373. return false;
  15374. }
  15375. }
  15376. } else {
  15377. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  15378. error = Error::Write;
  15379. return false;
  15380. }
  15381. }
  15382. return true;
  15383. }
  15384. inline std::unique_ptr<Response>
  15385. ClientImpl::send_with_content_provider_and_receiver(
  15386. Request &req, const char *body, size_t content_length,
  15387. ContentProvider content_provider,
  15388. ContentProviderWithoutLength content_provider_without_length,
  15389. const std::string &content_type, ContentReceiver content_receiver,
  15390. Error &error) {
  15391. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  15392. auto enc = compress_
  15393. ? detail::create_compressor()
  15394. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  15395. nullptr, nullptr);
  15396. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  15397. // A compressed or chunked body is framed by the library, not the caller
  15398. if (enc.second || content_provider_without_length) {
  15399. req.headers.erase("Content-Length");
  15400. }
  15401. if (enc.first && !content_provider_without_length) {
  15402. auto &compressor = enc.first;
  15403. if (content_provider) {
  15404. auto ok = true;
  15405. auto finished = false;
  15406. size_t offset = 0;
  15407. DataSink data_sink;
  15408. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  15409. if (ok) {
  15410. auto last = offset + data_len == content_length;
  15411. auto ret = compressor->compress(
  15412. data, data_len, last,
  15413. [&](const char *compressed_data, size_t compressed_data_len) {
  15414. req.body.append(compressed_data, compressed_data_len);
  15415. return true;
  15416. });
  15417. if (ret) {
  15418. offset += data_len;
  15419. } else {
  15420. ok = false;
  15421. }
  15422. }
  15423. return ok;
  15424. };
  15425. // As in detail::write_content_with_progress(): the body is framed by
  15426. // content_length, so a provider that finishes early has truncated it.
  15427. // Stop and report that instead of calling the provider forever.
  15428. data_sink.done = [&]() { finished = true; };
  15429. while (ok && !finished && offset < content_length) {
  15430. if (!content_provider(offset, content_length - offset, data_sink)) {
  15431. error = Error::Canceled;
  15432. output_error_log(error, &req);
  15433. return nullptr;
  15434. }
  15435. }
  15436. // A short body here means either the provider stopped early or the
  15437. // compressor gave up. The branch below reports a failing compressor as
  15438. // Error::Compression, so keep the two distinguishable.
  15439. if (offset < content_length) {
  15440. error = ok ? Error::Write : Error::Compression;
  15441. output_error_log(error, &req);
  15442. return nullptr;
  15443. }
  15444. } else {
  15445. if (!compressor->compress(body, content_length, true,
  15446. [&](const char *data, size_t data_len) {
  15447. req.body.append(data, data_len);
  15448. return true;
  15449. })) {
  15450. error = Error::Compression;
  15451. output_error_log(error, &req);
  15452. return nullptr;
  15453. }
  15454. }
  15455. } else {
  15456. if (content_provider) {
  15457. req.content_length_ = content_length;
  15458. req.content_provider_ = std::move(content_provider);
  15459. req.is_chunked_content_provider_ = false;
  15460. } else if (content_provider_without_length) {
  15461. req.content_length_ = 0;
  15462. req.content_provider_ = detail::ContentProviderAdapter(
  15463. std::move(content_provider_without_length));
  15464. req.is_chunked_content_provider_ = true;
  15465. req.set_header("Transfer-Encoding", "chunked");
  15466. } else {
  15467. req.body.assign(body, content_length);
  15468. }
  15469. }
  15470. if (content_receiver) {
  15471. req.content_receiver =
  15472. [content_receiver](const char *data, size_t data_length,
  15473. size_t /*offset*/, size_t /*total_length*/) {
  15474. return content_receiver(data, data_length);
  15475. };
  15476. }
  15477. auto res = detail::make_unique<Response>();
  15478. return send(req, *res, error) ? std::move(res) : nullptr;
  15479. }
  15480. inline Result ClientImpl::send_with_content_provider_and_receiver(
  15481. const std::string &method, const std::string &path, const Headers &headers,
  15482. const char *body, size_t content_length, ContentProvider content_provider,
  15483. ContentProviderWithoutLength content_provider_without_length,
  15484. const std::string &content_type, ContentReceiver content_receiver,
  15485. UploadProgress progress) {
  15486. Request req;
  15487. req.method = method;
  15488. req.headers = headers;
  15489. req.path = path;
  15490. req.upload_progress = std::move(progress);
  15491. if (max_timeout_msec_ > 0) {
  15492. req.start_time_ = std::chrono::steady_clock::now();
  15493. }
  15494. auto error = Error::Success;
  15495. #ifdef CPPHTTPLIB_SSL_ENABLED
  15496. // Hold the request lock until the Result has read this request's TLS error
  15497. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  15498. #endif
  15499. auto res = send_with_content_provider_and_receiver(
  15500. req, body, content_length, std::move(content_provider),
  15501. std::move(content_provider_without_length), content_type,
  15502. std::move(content_receiver), error);
  15503. #ifdef CPPHTTPLIB_SSL_ENABLED
  15504. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  15505. last_backend_error_};
  15506. #else
  15507. return Result{std::move(res), error, std::move(req.headers)};
  15508. #endif
  15509. }
  15510. inline void ClientImpl::output_log(const Request &req,
  15511. const Response &res) const {
  15512. if (logger_) {
  15513. std::lock_guard<std::mutex> guard(logger_mutex_);
  15514. logger_(req, res);
  15515. }
  15516. }
  15517. inline void ClientImpl::output_error_log(const Error &err,
  15518. const Request *req) const {
  15519. if (error_logger_) {
  15520. std::lock_guard<std::mutex> guard(logger_mutex_);
  15521. error_logger_(err, req);
  15522. }
  15523. }
  15524. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  15525. Response &res, bool close_connection,
  15526. Error &error) {
  15527. // Auto-add Expect: 100-continue for large bodies
  15528. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  15529. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  15530. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  15531. req.set_header("Expect", "100-continue");
  15532. }
  15533. }
  15534. // Check for Expect: 100-continue
  15535. auto expect_100_continue =
  15536. detail::has_header_token(req.headers, "Expect", "100-continue");
  15537. // Send request (skip body if using Expect: 100-continue)
  15538. auto rejected_locally = false;
  15539. auto write_request_success =
  15540. write_request(strm, req, close_connection, error, expect_100_continue,
  15541. rejected_locally);
  15542. // A failed write normally still reads the response below, since the server
  15543. // may have answered early (e.g. 413/414) and closed while the body was being
  15544. // sent. A request rejected before any byte reached the socket gets no such
  15545. // response, and waiting for one would block until the read timeout.
  15546. if (rejected_locally) { return false; }
  15547. #ifdef CPPHTTPLIB_SSL_ENABLED
  15548. if (is_ssl() && !expect_100_continue) {
  15549. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  15550. if (!is_proxy_enabled) {
  15551. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  15552. error = Error::SSLPeerCouldBeClosed_;
  15553. return false;
  15554. }
  15555. }
  15556. }
  15557. #endif
  15558. // Handle Expect: 100-continue.
  15559. //
  15560. // Wait for an interim/early response by attempting to read the status line
  15561. // under a short timeout, instead of trusting raw socket readability. Over
  15562. // TLS, post-handshake records (e.g. session tickets) make the socket
  15563. // readable without any HTTP response being available; relying on
  15564. // `select_read` there caused the body to be withheld forever and the
  15565. // request to fail with `Read` (#2458). If no status line arrives within the
  15566. // timeout, send the body anyway (matching curl's behavior).
  15567. auto status_line_read = false;
  15568. if (expect_100_continue && write_request_success) {
  15569. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  15570. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  15571. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  15572. strm.set_read_timeout(sec, usec);
  15573. status_line_read = read_response_line(strm, req, res, false);
  15574. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  15575. }
  15576. if (!status_line_read) {
  15577. // No interim response within the timeout: send the body and handle the
  15578. // response as usual.
  15579. if (!write_request_body(strm, req, error)) { return false; }
  15580. expect_100_continue = false; // Switch to normal response handling
  15581. }
  15582. }
  15583. // Receive response and headers
  15584. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  15585. if ((!status_line_read &&
  15586. !read_response_line(strm, req, res, !expect_100_continue)) ||
  15587. !detail::read_headers(strm, res.headers)) {
  15588. if (write_request_success) { error = Error::Read; }
  15589. return false;
  15590. }
  15591. if (!write_request_success) { return false; }
  15592. // Handle Expect: 100-continue response
  15593. if (expect_100_continue) {
  15594. if (res.status == StatusCode::Continue_100) {
  15595. // Server accepted, send the body
  15596. if (!write_request_body(strm, req, error)) { return false; }
  15597. // Read the actual response
  15598. res.headers.clear();
  15599. res.body.clear();
  15600. if (!read_response_line(strm, req, res) ||
  15601. !detail::read_headers(strm, res.headers)) {
  15602. error = Error::Read;
  15603. return false;
  15604. }
  15605. } else {
  15606. // A final response came first, so the body this request declared was
  15607. // never sent, and the server may still be waiting for it. The
  15608. // connection cannot carry another request.
  15609. std::lock_guard<std::mutex> guard(socket_mutex_);
  15610. socket_should_be_closed_when_request_is_done_ = true;
  15611. }
  15612. }
  15613. // Body
  15614. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  15615. req.method != "CONNECT") {
  15616. // Reject ambiguous framing (RFC 9112 §6.3). Unlike a request, a response
  15617. // whose final transfer coding is not chunked is not ambiguous: its body
  15618. // runs until the server closes the connection, so it is not rejected.
  15619. // HEAD/204 are excluded above and a 304 carries no body.
  15620. if (res.status != StatusCode::NotModified_304) {
  15621. if (detail::has_conflicting_content_length(res.headers)) {
  15622. error = Error::Read;
  15623. return false;
  15624. }
  15625. if (detail::has_faulty_transfer_encoding(res)) {
  15626. std::lock_guard<std::mutex> guard(socket_mutex_);
  15627. socket_should_be_closed_when_request_is_done_ = true;
  15628. }
  15629. }
  15630. auto redirect = follow_location_ && detail::is_redirect(res);
  15631. if (req.response_handler && !redirect) {
  15632. if (!req.response_handler(res)) {
  15633. error = Error::Canceled;
  15634. return false;
  15635. }
  15636. }
  15637. auto out =
  15638. req.content_receiver
  15639. ? static_cast<ContentReceiverWithProgress>(
  15640. [&](const char *buf, size_t n, size_t off, size_t len) {
  15641. if (redirect) { return true; }
  15642. auto ret = req.content_receiver(buf, n, off, len);
  15643. if (!ret) { error = Error::Canceled; }
  15644. return ret;
  15645. })
  15646. : static_cast<ContentReceiverWithProgress>(
  15647. [&](const char *buf, size_t n, size_t /*off*/,
  15648. size_t /*len*/) {
  15649. assert(res.body.size() + n <= res.body.max_size());
  15650. if (payload_max_length_ > 0 &&
  15651. (res.body.size() >= payload_max_length_ ||
  15652. n > payload_max_length_ - res.body.size())) {
  15653. return false;
  15654. }
  15655. res.body.append(buf, n);
  15656. return true;
  15657. });
  15658. auto progress = [&](size_t current, size_t total) {
  15659. if (!req.download_progress || redirect) { return true; }
  15660. auto ret = req.download_progress(current, total);
  15661. if (!ret) { error = Error::Canceled; }
  15662. return ret;
  15663. };
  15664. if (res.has_header("Content-Length")) {
  15665. if (!req.content_receiver) {
  15666. auto len = res.get_header_value_u64("Content-Length");
  15667. if (len > res.body.max_size()) {
  15668. error = Error::Read;
  15669. return false;
  15670. }
  15671. // Content-Length is only the server's claim, so reserve no more than
  15672. // payload_max_length_ allows, nor more than 1 MiB before any of the
  15673. // body has arrived. A longer body grows as it is read.
  15674. auto reserve_len =
  15675. (std::min)(static_cast<size_t>(len), size_t(1024 * 1024));
  15676. if (payload_max_length_ > 0) {
  15677. reserve_len = (std::min)(reserve_len, payload_max_length_);
  15678. }
  15679. res.body.reserve(reserve_len);
  15680. }
  15681. }
  15682. if (res.status != StatusCode::NotModified_304) {
  15683. auto content_status = 0;
  15684. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  15685. ? (std::numeric_limits<size_t>::max)()
  15686. : payload_max_length_;
  15687. if (!detail::read_content(strm, res, max_length, content_status,
  15688. std::move(progress), std::move(out),
  15689. decompress_)) {
  15690. if (error != Error::Canceled) {
  15691. // Tell the caller apart from a plain read failure when the body was
  15692. // over the payload limit or could not be decoded because of its
  15693. // Content-Encoding.
  15694. switch (content_status) {
  15695. case StatusCode::PayloadTooLarge_413:
  15696. error = Error::ExceedMaxPayloadSize;
  15697. break;
  15698. case StatusCode::UnsupportedMediaType_415:
  15699. error = Error::UnsupportedContentEncoding;
  15700. break;
  15701. case StatusCode::InternalServerError_500:
  15702. error = Error::Compression;
  15703. break;
  15704. default: error = Error::Read; break;
  15705. }
  15706. }
  15707. return false;
  15708. }
  15709. }
  15710. }
  15711. // Log
  15712. output_log(req, res);
  15713. return true;
  15714. }
  15715. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  15716. const std::string &boundary, const UploadFormDataItems &items,
  15717. const FormDataProviderItems &provider_items) const {
  15718. size_t cur_item = 0;
  15719. size_t cur_start = 0;
  15720. // cur_item and cur_start are copied to within the std::function and
  15721. // maintain state between successive calls
  15722. return [&, cur_item, cur_start](size_t offset,
  15723. DataSink &sink) mutable -> bool {
  15724. if (!offset && !items.empty()) {
  15725. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  15726. return true;
  15727. } else if (cur_item < provider_items.size()) {
  15728. if (!cur_start) {
  15729. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  15730. provider_items[cur_item], boundary);
  15731. offset += begin.size();
  15732. cur_start = offset;
  15733. sink.os << begin;
  15734. }
  15735. DataSink cur_sink;
  15736. auto has_data = true;
  15737. cur_sink.write = sink.write;
  15738. // Forward is_writable so a provider item asking whether it may keep
  15739. // going gets the outer sink's answer rather than the default `true`.
  15740. cur_sink.is_writable = sink.is_writable;
  15741. cur_sink.done = [&]() { has_data = false; };
  15742. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  15743. return false;
  15744. }
  15745. if (!has_data) {
  15746. sink.os << detail::serialize_multipart_formdata_item_end();
  15747. cur_item++;
  15748. cur_start = 0;
  15749. }
  15750. return true;
  15751. } else {
  15752. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  15753. sink.done();
  15754. return true;
  15755. }
  15756. };
  15757. }
  15758. inline bool ClientImpl::process_socket(
  15759. const Socket &socket,
  15760. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15761. std::function<bool(Stream &strm)> callback) {
  15762. return detail::process_client_socket(
  15763. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  15764. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  15765. }
  15766. inline bool ClientImpl::is_ssl() const { return false; }
  15767. inline Result ClientImpl::Get(const std::string &path,
  15768. DownloadProgress progress) {
  15769. return Get(path, Headers(), std::move(progress));
  15770. }
  15771. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15772. DownloadProgress progress) {
  15773. return Get(path, params, Headers(), std::move(progress));
  15774. }
  15775. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15776. const Headers &headers,
  15777. DownloadProgress progress) {
  15778. if (params.empty()) { return Get(path, headers); }
  15779. std::string path_with_query = append_query_params(path, params);
  15780. return Get(path_with_query, headers, std::move(progress));
  15781. }
  15782. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  15783. DownloadProgress progress) {
  15784. Request req;
  15785. req.method = "GET";
  15786. req.path = path;
  15787. req.headers = headers;
  15788. req.download_progress = std::move(progress);
  15789. if (max_timeout_msec_ > 0) {
  15790. req.start_time_ = std::chrono::steady_clock::now();
  15791. }
  15792. return send_(std::move(req));
  15793. }
  15794. inline Result ClientImpl::Get(const std::string &path,
  15795. ContentReceiver content_receiver,
  15796. DownloadProgress progress) {
  15797. return Get(path, Headers(), nullptr, std::move(content_receiver),
  15798. std::move(progress));
  15799. }
  15800. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  15801. ContentReceiver content_receiver,
  15802. DownloadProgress progress) {
  15803. return Get(path, headers, nullptr, std::move(content_receiver),
  15804. std::move(progress));
  15805. }
  15806. inline Result ClientImpl::Get(const std::string &path,
  15807. ResponseHandler response_handler,
  15808. ContentReceiver content_receiver,
  15809. DownloadProgress progress) {
  15810. return Get(path, Headers(), std::move(response_handler),
  15811. std::move(content_receiver), std::move(progress));
  15812. }
  15813. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  15814. ResponseHandler response_handler,
  15815. ContentReceiver content_receiver,
  15816. DownloadProgress progress) {
  15817. Request req;
  15818. req.method = "GET";
  15819. req.path = path;
  15820. req.headers = headers;
  15821. req.response_handler = std::move(response_handler);
  15822. req.content_receiver =
  15823. [content_receiver](const char *data, size_t data_length,
  15824. size_t /*offset*/, size_t /*total_length*/) {
  15825. return content_receiver(data, data_length);
  15826. };
  15827. req.download_progress = std::move(progress);
  15828. if (max_timeout_msec_ > 0) {
  15829. req.start_time_ = std::chrono::steady_clock::now();
  15830. }
  15831. return send_(std::move(req));
  15832. }
  15833. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15834. const Headers &headers,
  15835. ContentReceiver content_receiver,
  15836. DownloadProgress progress) {
  15837. return Get(path, params, headers, nullptr, std::move(content_receiver),
  15838. std::move(progress));
  15839. }
  15840. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15841. const Headers &headers,
  15842. ResponseHandler response_handler,
  15843. ContentReceiver content_receiver,
  15844. DownloadProgress progress) {
  15845. if (params.empty()) {
  15846. return Get(path, headers, std::move(response_handler),
  15847. std::move(content_receiver), std::move(progress));
  15848. }
  15849. std::string path_with_query = append_query_params(path, params);
  15850. return Get(path_with_query, headers, std::move(response_handler),
  15851. std::move(content_receiver), std::move(progress));
  15852. }
  15853. inline Result ClientImpl::Head(const std::string &path) {
  15854. return Head(path, Headers());
  15855. }
  15856. inline Result ClientImpl::Head(const std::string &path,
  15857. const Headers &headers) {
  15858. Request req;
  15859. req.method = "HEAD";
  15860. req.headers = headers;
  15861. req.path = path;
  15862. if (max_timeout_msec_ > 0) {
  15863. req.start_time_ = std::chrono::steady_clock::now();
  15864. }
  15865. return send_(std::move(req));
  15866. }
  15867. inline Result ClientImpl::Post(const std::string &path) {
  15868. return Post(path, std::string(), std::string());
  15869. }
  15870. inline Result ClientImpl::Post(const std::string &path,
  15871. const Headers &headers) {
  15872. return Post(path, headers, nullptr, 0, std::string());
  15873. }
  15874. inline Result ClientImpl::Post(const std::string &path, const char *body,
  15875. size_t content_length,
  15876. const std::string &content_type,
  15877. UploadProgress progress) {
  15878. return Post(path, Headers(), body, content_length, content_type, progress);
  15879. }
  15880. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  15881. const std::string &content_type,
  15882. UploadProgress progress) {
  15883. return Post(path, Headers(), body, content_type, progress);
  15884. }
  15885. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  15886. return Post(path, Headers(), params);
  15887. }
  15888. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  15889. ContentProvider content_provider,
  15890. const std::string &content_type,
  15891. UploadProgress progress) {
  15892. return Post(path, Headers(), content_length, std::move(content_provider),
  15893. content_type, progress);
  15894. }
  15895. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  15896. ContentProvider content_provider,
  15897. const std::string &content_type,
  15898. ContentReceiver content_receiver,
  15899. UploadProgress progress) {
  15900. return Post(path, Headers(), content_length, std::move(content_provider),
  15901. content_type, std::move(content_receiver), progress);
  15902. }
  15903. inline Result ClientImpl::Post(const std::string &path,
  15904. ContentProviderWithoutLength content_provider,
  15905. const std::string &content_type,
  15906. UploadProgress progress) {
  15907. return Post(path, Headers(), std::move(content_provider), content_type,
  15908. progress);
  15909. }
  15910. inline Result ClientImpl::Post(const std::string &path,
  15911. ContentProviderWithoutLength content_provider,
  15912. const std::string &content_type,
  15913. ContentReceiver content_receiver,
  15914. UploadProgress progress) {
  15915. return Post(path, Headers(), std::move(content_provider), content_type,
  15916. std::move(content_receiver), progress);
  15917. }
  15918. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15919. const Params &params) {
  15920. auto query = detail::params_to_query_str(params);
  15921. return Post(path, headers, query, "application/x-www-form-urlencoded");
  15922. }
  15923. inline Result ClientImpl::Post(const std::string &path,
  15924. const UploadFormDataItems &items,
  15925. UploadProgress progress) {
  15926. return Post(path, Headers(), items, progress);
  15927. }
  15928. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15929. const UploadFormDataItems &items,
  15930. UploadProgress progress) {
  15931. const auto &boundary = detail::make_multipart_data_boundary();
  15932. const auto &content_type =
  15933. detail::serialize_multipart_formdata_get_content_type(boundary);
  15934. auto content_length = detail::get_multipart_content_length(items, boundary);
  15935. return Post(path, headers, content_length,
  15936. detail::make_multipart_content_provider(items, boundary),
  15937. content_type, progress);
  15938. }
  15939. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15940. const UploadFormDataItems &items,
  15941. const std::string &boundary,
  15942. UploadProgress progress) {
  15943. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  15944. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  15945. }
  15946. const auto &content_type =
  15947. detail::serialize_multipart_formdata_get_content_type(boundary);
  15948. auto content_length = detail::get_multipart_content_length(items, boundary);
  15949. return Post(path, headers, content_length,
  15950. detail::make_multipart_content_provider(items, boundary),
  15951. content_type, progress);
  15952. }
  15953. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15954. const char *body, size_t content_length,
  15955. const std::string &content_type,
  15956. UploadProgress progress) {
  15957. return send_with_content_provider_and_receiver(
  15958. "POST", path, headers, body, content_length, nullptr, nullptr,
  15959. content_type, nullptr, progress);
  15960. }
  15961. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15962. const std::string &body,
  15963. const std::string &content_type,
  15964. UploadProgress progress) {
  15965. return send_with_content_provider_and_receiver(
  15966. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  15967. content_type, nullptr, progress);
  15968. }
  15969. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15970. size_t content_length,
  15971. ContentProvider content_provider,
  15972. const std::string &content_type,
  15973. UploadProgress progress) {
  15974. return send_with_content_provider_and_receiver(
  15975. "POST", path, headers, nullptr, content_length,
  15976. std::move(content_provider), nullptr, content_type, nullptr, progress);
  15977. }
  15978. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15979. size_t content_length,
  15980. ContentProvider content_provider,
  15981. const std::string &content_type,
  15982. ContentReceiver content_receiver,
  15983. DownloadProgress progress) {
  15984. return send_with_content_provider_and_receiver(
  15985. "POST", path, headers, nullptr, content_length,
  15986. std::move(content_provider), nullptr, content_type,
  15987. std::move(content_receiver), std::move(progress));
  15988. }
  15989. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15990. ContentProviderWithoutLength content_provider,
  15991. const std::string &content_type,
  15992. UploadProgress progress) {
  15993. return send_with_content_provider_and_receiver(
  15994. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  15995. content_type, nullptr, progress);
  15996. }
  15997. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15998. ContentProviderWithoutLength content_provider,
  15999. const std::string &content_type,
  16000. ContentReceiver content_receiver,
  16001. DownloadProgress progress) {
  16002. return send_with_content_provider_and_receiver(
  16003. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16004. content_type, std::move(content_receiver), std::move(progress));
  16005. }
  16006. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  16007. const UploadFormDataItems &items,
  16008. const FormDataProviderItems &provider_items,
  16009. UploadProgress progress) {
  16010. const auto &boundary = detail::make_multipart_data_boundary();
  16011. const auto &content_type =
  16012. detail::serialize_multipart_formdata_get_content_type(boundary);
  16013. return send_with_content_provider_and_receiver(
  16014. "POST", path, headers, nullptr, 0, nullptr,
  16015. get_multipart_content_provider(boundary, items, provider_items),
  16016. content_type, nullptr, progress);
  16017. }
  16018. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  16019. const std::string &body,
  16020. const std::string &content_type,
  16021. ContentReceiver content_receiver,
  16022. DownloadProgress progress) {
  16023. Request req;
  16024. req.method = "POST";
  16025. req.path = path;
  16026. req.headers = headers;
  16027. req.body = body;
  16028. req.content_receiver =
  16029. [content_receiver](const char *data, size_t data_length,
  16030. size_t /*offset*/, size_t /*total_length*/) {
  16031. return content_receiver(data, data_length);
  16032. };
  16033. req.download_progress = std::move(progress);
  16034. if (max_timeout_msec_ > 0) {
  16035. req.start_time_ = std::chrono::steady_clock::now();
  16036. }
  16037. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16038. return send_(std::move(req));
  16039. }
  16040. inline Result ClientImpl::Put(const std::string &path) {
  16041. return Put(path, std::string(), std::string());
  16042. }
  16043. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  16044. return Put(path, headers, nullptr, 0, std::string());
  16045. }
  16046. inline Result ClientImpl::Put(const std::string &path, const char *body,
  16047. size_t content_length,
  16048. const std::string &content_type,
  16049. UploadProgress progress) {
  16050. return Put(path, Headers(), body, content_length, content_type, progress);
  16051. }
  16052. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  16053. const std::string &content_type,
  16054. UploadProgress progress) {
  16055. return Put(path, Headers(), body, content_type, progress);
  16056. }
  16057. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  16058. return Put(path, Headers(), params);
  16059. }
  16060. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  16061. ContentProvider content_provider,
  16062. const std::string &content_type,
  16063. UploadProgress progress) {
  16064. return Put(path, Headers(), content_length, std::move(content_provider),
  16065. content_type, progress);
  16066. }
  16067. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  16068. ContentProvider content_provider,
  16069. const std::string &content_type,
  16070. ContentReceiver content_receiver,
  16071. UploadProgress progress) {
  16072. return Put(path, Headers(), content_length, std::move(content_provider),
  16073. content_type, std::move(content_receiver), progress);
  16074. }
  16075. inline Result ClientImpl::Put(const std::string &path,
  16076. ContentProviderWithoutLength content_provider,
  16077. const std::string &content_type,
  16078. UploadProgress progress) {
  16079. return Put(path, Headers(), std::move(content_provider), content_type,
  16080. progress);
  16081. }
  16082. inline Result ClientImpl::Put(const std::string &path,
  16083. ContentProviderWithoutLength content_provider,
  16084. const std::string &content_type,
  16085. ContentReceiver content_receiver,
  16086. UploadProgress progress) {
  16087. return Put(path, Headers(), std::move(content_provider), content_type,
  16088. std::move(content_receiver), progress);
  16089. }
  16090. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16091. const Params &params) {
  16092. auto query = detail::params_to_query_str(params);
  16093. return Put(path, headers, query, "application/x-www-form-urlencoded");
  16094. }
  16095. inline Result ClientImpl::Put(const std::string &path,
  16096. const UploadFormDataItems &items,
  16097. UploadProgress progress) {
  16098. return Put(path, Headers(), items, progress);
  16099. }
  16100. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16101. const UploadFormDataItems &items,
  16102. UploadProgress progress) {
  16103. const auto &boundary = detail::make_multipart_data_boundary();
  16104. const auto &content_type =
  16105. detail::serialize_multipart_formdata_get_content_type(boundary);
  16106. auto content_length = detail::get_multipart_content_length(items, boundary);
  16107. return Put(path, headers, content_length,
  16108. detail::make_multipart_content_provider(items, boundary),
  16109. content_type, progress);
  16110. }
  16111. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16112. const UploadFormDataItems &items,
  16113. const std::string &boundary,
  16114. UploadProgress progress) {
  16115. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  16116. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  16117. }
  16118. const auto &content_type =
  16119. detail::serialize_multipart_formdata_get_content_type(boundary);
  16120. auto content_length = detail::get_multipart_content_length(items, boundary);
  16121. return Put(path, headers, content_length,
  16122. detail::make_multipart_content_provider(items, boundary),
  16123. content_type, progress);
  16124. }
  16125. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16126. const char *body, size_t content_length,
  16127. const std::string &content_type,
  16128. UploadProgress progress) {
  16129. return send_with_content_provider_and_receiver(
  16130. "PUT", path, headers, body, content_length, nullptr, nullptr,
  16131. content_type, nullptr, progress);
  16132. }
  16133. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16134. const std::string &body,
  16135. const std::string &content_type,
  16136. UploadProgress progress) {
  16137. return send_with_content_provider_and_receiver(
  16138. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  16139. content_type, nullptr, progress);
  16140. }
  16141. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16142. size_t content_length,
  16143. ContentProvider content_provider,
  16144. const std::string &content_type,
  16145. UploadProgress progress) {
  16146. return send_with_content_provider_and_receiver(
  16147. "PUT", path, headers, nullptr, content_length,
  16148. std::move(content_provider), nullptr, content_type, nullptr, progress);
  16149. }
  16150. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16151. size_t content_length,
  16152. ContentProvider content_provider,
  16153. const std::string &content_type,
  16154. ContentReceiver content_receiver,
  16155. UploadProgress progress) {
  16156. return send_with_content_provider_and_receiver(
  16157. "PUT", path, headers, nullptr, content_length,
  16158. std::move(content_provider), nullptr, content_type,
  16159. std::move(content_receiver), progress);
  16160. }
  16161. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16162. ContentProviderWithoutLength content_provider,
  16163. const std::string &content_type,
  16164. UploadProgress progress) {
  16165. return send_with_content_provider_and_receiver(
  16166. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16167. content_type, nullptr, progress);
  16168. }
  16169. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16170. ContentProviderWithoutLength content_provider,
  16171. const std::string &content_type,
  16172. ContentReceiver content_receiver,
  16173. UploadProgress progress) {
  16174. return send_with_content_provider_and_receiver(
  16175. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16176. content_type, std::move(content_receiver), progress);
  16177. }
  16178. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16179. const UploadFormDataItems &items,
  16180. const FormDataProviderItems &provider_items,
  16181. UploadProgress progress) {
  16182. const auto &boundary = detail::make_multipart_data_boundary();
  16183. const auto &content_type =
  16184. detail::serialize_multipart_formdata_get_content_type(boundary);
  16185. return send_with_content_provider_and_receiver(
  16186. "PUT", path, headers, nullptr, 0, nullptr,
  16187. get_multipart_content_provider(boundary, items, provider_items),
  16188. content_type, nullptr, progress);
  16189. }
  16190. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16191. const std::string &body,
  16192. const std::string &content_type,
  16193. ContentReceiver content_receiver,
  16194. DownloadProgress progress) {
  16195. Request req;
  16196. req.method = "PUT";
  16197. req.path = path;
  16198. req.headers = headers;
  16199. req.body = body;
  16200. req.content_receiver =
  16201. [content_receiver](const char *data, size_t data_length,
  16202. size_t /*offset*/, size_t /*total_length*/) {
  16203. return content_receiver(data, data_length);
  16204. };
  16205. req.download_progress = std::move(progress);
  16206. if (max_timeout_msec_ > 0) {
  16207. req.start_time_ = std::chrono::steady_clock::now();
  16208. }
  16209. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16210. return send_(std::move(req));
  16211. }
  16212. inline Result ClientImpl::Patch(const std::string &path) {
  16213. return Patch(path, std::string(), std::string());
  16214. }
  16215. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16216. UploadProgress progress) {
  16217. return Patch(path, headers, nullptr, 0, std::string(), progress);
  16218. }
  16219. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  16220. size_t content_length,
  16221. const std::string &content_type,
  16222. UploadProgress progress) {
  16223. return Patch(path, Headers(), body, content_length, content_type, progress);
  16224. }
  16225. inline Result ClientImpl::Patch(const std::string &path,
  16226. const std::string &body,
  16227. const std::string &content_type,
  16228. UploadProgress progress) {
  16229. return Patch(path, Headers(), body, content_type, progress);
  16230. }
  16231. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  16232. return Patch(path, Headers(), params);
  16233. }
  16234. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  16235. ContentProvider content_provider,
  16236. const std::string &content_type,
  16237. UploadProgress progress) {
  16238. return Patch(path, Headers(), content_length, std::move(content_provider),
  16239. content_type, progress);
  16240. }
  16241. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  16242. ContentProvider content_provider,
  16243. const std::string &content_type,
  16244. ContentReceiver content_receiver,
  16245. UploadProgress progress) {
  16246. return Patch(path, Headers(), content_length, std::move(content_provider),
  16247. content_type, std::move(content_receiver), progress);
  16248. }
  16249. inline Result ClientImpl::Patch(const std::string &path,
  16250. ContentProviderWithoutLength content_provider,
  16251. const std::string &content_type,
  16252. UploadProgress progress) {
  16253. return Patch(path, Headers(), std::move(content_provider), content_type,
  16254. progress);
  16255. }
  16256. inline Result ClientImpl::Patch(const std::string &path,
  16257. ContentProviderWithoutLength content_provider,
  16258. const std::string &content_type,
  16259. ContentReceiver content_receiver,
  16260. UploadProgress progress) {
  16261. return Patch(path, Headers(), std::move(content_provider), content_type,
  16262. std::move(content_receiver), progress);
  16263. }
  16264. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16265. const Params &params) {
  16266. auto query = detail::params_to_query_str(params);
  16267. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  16268. }
  16269. inline Result ClientImpl::Patch(const std::string &path,
  16270. const UploadFormDataItems &items,
  16271. UploadProgress progress) {
  16272. return Patch(path, Headers(), items, progress);
  16273. }
  16274. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16275. const UploadFormDataItems &items,
  16276. UploadProgress progress) {
  16277. const auto &boundary = detail::make_multipart_data_boundary();
  16278. const auto &content_type =
  16279. detail::serialize_multipart_formdata_get_content_type(boundary);
  16280. auto content_length = detail::get_multipart_content_length(items, boundary);
  16281. return Patch(path, headers, content_length,
  16282. detail::make_multipart_content_provider(items, boundary),
  16283. content_type, progress);
  16284. }
  16285. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16286. const UploadFormDataItems &items,
  16287. const std::string &boundary,
  16288. UploadProgress progress) {
  16289. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  16290. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  16291. }
  16292. const auto &content_type =
  16293. detail::serialize_multipart_formdata_get_content_type(boundary);
  16294. auto content_length = detail::get_multipart_content_length(items, boundary);
  16295. return Patch(path, headers, content_length,
  16296. detail::make_multipart_content_provider(items, boundary),
  16297. content_type, progress);
  16298. }
  16299. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16300. const char *body, size_t content_length,
  16301. const std::string &content_type,
  16302. UploadProgress progress) {
  16303. return send_with_content_provider_and_receiver(
  16304. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  16305. content_type, nullptr, progress);
  16306. }
  16307. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16308. const std::string &body,
  16309. const std::string &content_type,
  16310. UploadProgress progress) {
  16311. return send_with_content_provider_and_receiver(
  16312. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  16313. content_type, nullptr, progress);
  16314. }
  16315. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16316. size_t content_length,
  16317. ContentProvider content_provider,
  16318. const std::string &content_type,
  16319. UploadProgress progress) {
  16320. return send_with_content_provider_and_receiver(
  16321. "PATCH", path, headers, nullptr, content_length,
  16322. std::move(content_provider), nullptr, content_type, nullptr, progress);
  16323. }
  16324. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16325. size_t content_length,
  16326. ContentProvider content_provider,
  16327. const std::string &content_type,
  16328. ContentReceiver content_receiver,
  16329. UploadProgress progress) {
  16330. return send_with_content_provider_and_receiver(
  16331. "PATCH", path, headers, nullptr, content_length,
  16332. std::move(content_provider), nullptr, content_type,
  16333. std::move(content_receiver), progress);
  16334. }
  16335. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16336. ContentProviderWithoutLength content_provider,
  16337. const std::string &content_type,
  16338. UploadProgress progress) {
  16339. return send_with_content_provider_and_receiver(
  16340. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16341. content_type, nullptr, progress);
  16342. }
  16343. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16344. ContentProviderWithoutLength content_provider,
  16345. const std::string &content_type,
  16346. ContentReceiver content_receiver,
  16347. UploadProgress progress) {
  16348. return send_with_content_provider_and_receiver(
  16349. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16350. content_type, std::move(content_receiver), progress);
  16351. }
  16352. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16353. const UploadFormDataItems &items,
  16354. const FormDataProviderItems &provider_items,
  16355. UploadProgress progress) {
  16356. const auto &boundary = detail::make_multipart_data_boundary();
  16357. const auto &content_type =
  16358. detail::serialize_multipart_formdata_get_content_type(boundary);
  16359. return send_with_content_provider_and_receiver(
  16360. "PATCH", path, headers, nullptr, 0, nullptr,
  16361. get_multipart_content_provider(boundary, items, provider_items),
  16362. content_type, nullptr, progress);
  16363. }
  16364. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16365. const std::string &body,
  16366. const std::string &content_type,
  16367. ContentReceiver content_receiver,
  16368. DownloadProgress progress) {
  16369. Request req;
  16370. req.method = "PATCH";
  16371. req.path = path;
  16372. req.headers = headers;
  16373. req.body = body;
  16374. req.content_receiver =
  16375. [content_receiver](const char *data, size_t data_length,
  16376. size_t /*offset*/, size_t /*total_length*/) {
  16377. return content_receiver(data, data_length);
  16378. };
  16379. req.download_progress = std::move(progress);
  16380. if (max_timeout_msec_ > 0) {
  16381. req.start_time_ = std::chrono::steady_clock::now();
  16382. }
  16383. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16384. return send_(std::move(req));
  16385. }
  16386. inline Result ClientImpl::Delete(const std::string &path,
  16387. DownloadProgress progress) {
  16388. return Delete(path, Headers(), std::string(), std::string(), progress);
  16389. }
  16390. inline Result ClientImpl::Delete(const std::string &path,
  16391. const Headers &headers,
  16392. DownloadProgress progress) {
  16393. return Delete(path, headers, std::string(), std::string(), progress);
  16394. }
  16395. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  16396. size_t content_length,
  16397. const std::string &content_type,
  16398. DownloadProgress progress) {
  16399. return Delete(path, Headers(), body, content_length, content_type, progress);
  16400. }
  16401. inline Result ClientImpl::Delete(const std::string &path,
  16402. const std::string &body,
  16403. const std::string &content_type,
  16404. DownloadProgress progress) {
  16405. return Delete(path, Headers(), body.data(), body.size(), content_type,
  16406. progress);
  16407. }
  16408. inline Result ClientImpl::Delete(const std::string &path,
  16409. const Headers &headers,
  16410. const std::string &body,
  16411. const std::string &content_type,
  16412. DownloadProgress progress) {
  16413. return Delete(path, headers, body.data(), body.size(), content_type,
  16414. progress);
  16415. }
  16416. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  16417. DownloadProgress progress) {
  16418. return Delete(path, Headers(), params, progress);
  16419. }
  16420. inline Result ClientImpl::Delete(const std::string &path,
  16421. const Headers &headers, const Params &params,
  16422. DownloadProgress progress) {
  16423. auto query = detail::params_to_query_str(params);
  16424. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  16425. progress);
  16426. }
  16427. inline Result ClientImpl::Delete(const std::string &path,
  16428. const Headers &headers, const char *body,
  16429. size_t content_length,
  16430. const std::string &content_type,
  16431. DownloadProgress progress) {
  16432. Request req;
  16433. req.method = "DELETE";
  16434. req.headers = headers;
  16435. req.path = path;
  16436. req.download_progress = std::move(progress);
  16437. if (max_timeout_msec_ > 0) {
  16438. req.start_time_ = std::chrono::steady_clock::now();
  16439. }
  16440. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16441. req.body.assign(body, content_length);
  16442. return send_(std::move(req));
  16443. }
  16444. inline Result ClientImpl::Options(const std::string &path) {
  16445. return Options(path, Headers());
  16446. }
  16447. inline Result ClientImpl::Options(const std::string &path,
  16448. const Headers &headers) {
  16449. Request req;
  16450. req.method = "OPTIONS";
  16451. req.headers = headers;
  16452. req.path = path;
  16453. if (max_timeout_msec_ > 0) {
  16454. req.start_time_ = std::chrono::steady_clock::now();
  16455. }
  16456. return send_(std::move(req));
  16457. }
  16458. inline void ClientImpl::stop() {
  16459. std::lock_guard<std::mutex> guard(socket_mutex_);
  16460. stop_requested_ = true;
  16461. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  16462. // do is to shutdown_socket, so that threads using this socket suddenly
  16463. // discover they can't read/write any more and error out. Everything else
  16464. // (closing the socket, shutting ssl down) is unsafe because these actions
  16465. // are not thread-safe.
  16466. if (socket_requests_in_flight_ > 0) {
  16467. shutdown_socket(socket_);
  16468. // Aside from that, we set a flag for the socket to be closed when we're
  16469. // done.
  16470. socket_should_be_closed_when_request_is_done_ = true;
  16471. return;
  16472. }
  16473. disconnect(/*gracefully=*/true);
  16474. }
  16475. inline std::string ClientImpl::host() const { return host_; }
  16476. inline int ClientImpl::port() const { return port_; }
  16477. inline size_t ClientImpl::is_socket_open() const {
  16478. std::lock_guard<std::mutex> guard(socket_mutex_);
  16479. return socket_.is_open();
  16480. }
  16481. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  16482. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  16483. connection_timeout_sec_ = sec;
  16484. connection_timeout_usec_ = usec;
  16485. }
  16486. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  16487. read_timeout_sec_ = sec;
  16488. read_timeout_usec_ = usec;
  16489. }
  16490. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  16491. write_timeout_sec_ = sec;
  16492. write_timeout_usec_ = usec;
  16493. }
  16494. inline void ClientImpl::set_max_timeout(time_t msec) {
  16495. max_timeout_msec_ = msec;
  16496. }
  16497. inline void ClientImpl::set_basic_auth(const std::string &username,
  16498. const std::string &password) {
  16499. basic_auth_username_ = username;
  16500. basic_auth_password_ = password;
  16501. }
  16502. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  16503. bearer_token_auth_token_ = token;
  16504. }
  16505. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  16506. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  16507. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  16508. inline void
  16509. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  16510. set_direct_hostname_addr_map(std::move(addr_map));
  16511. }
  16512. inline void ClientImpl::set_direct_hostname_addr_map(
  16513. std::map<std::string, std::string> addr_map) {
  16514. addr_map_ = std::move(addr_map);
  16515. }
  16516. inline void ClientImpl::set_tunnel_hostname_addr_map(
  16517. std::map<std::string, std::string> addr_map) {
  16518. tunnel_addr_map_ = std::move(addr_map);
  16519. }
  16520. inline void ClientImpl::set_default_headers(Headers headers) {
  16521. default_headers_ = std::move(headers);
  16522. }
  16523. inline void ClientImpl::set_header_writer(
  16524. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  16525. header_writer_ = writer;
  16526. }
  16527. inline void ClientImpl::set_address_family(int family) {
  16528. address_family_ = family;
  16529. }
  16530. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  16531. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  16532. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  16533. socket_options_ = std::move(socket_options);
  16534. }
  16535. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  16536. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  16537. inline void ClientImpl::set_payload_max_length(size_t length) {
  16538. payload_max_length_ = length;
  16539. has_payload_max_length_ = true;
  16540. }
  16541. inline void ClientImpl::set_interface(const std::string &intf) {
  16542. interface_ = intf;
  16543. }
  16544. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  16545. proxy_host_ = host;
  16546. proxy_port_ = port;
  16547. std::lock_guard<std::mutex> guard(socket_mutex_);
  16548. disconnect(/*gracefully=*/true);
  16549. }
  16550. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  16551. const std::string &password) {
  16552. proxy_basic_auth_username_ = username;
  16553. proxy_basic_auth_password_ = password;
  16554. }
  16555. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  16556. proxy_bearer_token_auth_token_ = token;
  16557. }
  16558. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  16559. no_proxy_entries_ = detail::parse_no_proxy_entries(patterns);
  16560. std::lock_guard<std::mutex> guard(socket_mutex_);
  16561. disconnect(/*gracefully=*/true);
  16562. }
  16563. #ifdef CPPHTTPLIB_SSL_ENABLED
  16564. inline void ClientImpl::set_digest_auth(const std::string &username,
  16565. const std::string &password) {
  16566. digest_auth_username_ = username;
  16567. digest_auth_password_ = password;
  16568. }
  16569. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  16570. const std::string &ca_cert_dir_path) {
  16571. ca_cert_file_path_ = ca_cert_file_path;
  16572. ca_cert_dir_path_ = ca_cert_dir_path;
  16573. }
  16574. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  16575. const std::string &password) {
  16576. proxy_digest_auth_username_ = username;
  16577. proxy_digest_auth_password_ = password;
  16578. }
  16579. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  16580. if (server_certificate_verification_ == enabled) { return; }
  16581. server_certificate_verification_ = enabled;
  16582. tls_settings_changed();
  16583. }
  16584. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  16585. if (server_hostname_verification_ == enabled) { return; }
  16586. server_hostname_verification_ = enabled;
  16587. tls_settings_changed();
  16588. }
  16589. inline void ClientImpl::enable_system_ca(bool enabled) {
  16590. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  16591. }
  16592. #endif
  16593. inline void ClientImpl::set_logger(Logger logger) {
  16594. logger_ = std::move(logger);
  16595. }
  16596. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  16597. error_logger_ = std::move(error_logger);
  16598. }
  16599. /*
  16600. * SSL/TLS Common Implementation
  16601. */
  16602. inline ClientConnection::~ClientConnection() {
  16603. #ifdef CPPHTTPLIB_SSL_ENABLED
  16604. if (session) {
  16605. tls::shutdown(session, true);
  16606. tls::free_session(session);
  16607. session = nullptr;
  16608. }
  16609. #endif
  16610. if (sock != INVALID_SOCKET) {
  16611. detail::close_socket(sock);
  16612. sock = INVALID_SOCKET;
  16613. }
  16614. }
  16615. // Universal client implementation
  16616. inline Client::Client(const std::string &scheme_host_port)
  16617. : Client(scheme_host_port, std::string(), std::string()) {}
  16618. inline Client::Client(const std::string &scheme_host_port,
  16619. const std::string &client_cert_path,
  16620. const std::string &client_key_path) {
  16621. detail::UrlComponents uc;
  16622. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  16623. auto &scheme = uc.scheme;
  16624. #ifdef CPPHTTPLIB_SSL_ENABLED
  16625. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  16626. #else
  16627. if (!scheme.empty() && scheme != "http") {
  16628. #endif
  16629. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  16630. std::string msg = "'" + scheme + "' scheme is not supported.";
  16631. throw std::invalid_argument(msg);
  16632. #endif
  16633. cli_ = detail::make_unique<detail::InvalidClientImpl>();
  16634. return;
  16635. }
  16636. auto is_ssl = scheme == "https";
  16637. auto host = std::move(uc.host);
  16638. auto port = is_ssl ? 443 : 80;
  16639. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) {
  16640. cli_ = detail::make_unique<detail::InvalidClientImpl>();
  16641. return;
  16642. }
  16643. if (is_ssl) {
  16644. #ifdef CPPHTTPLIB_SSL_ENABLED
  16645. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  16646. client_key_path);
  16647. is_ssl_ = is_ssl;
  16648. #endif
  16649. } else {
  16650. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  16651. client_key_path);
  16652. }
  16653. } else if (scheme_host_port.compare(0, 2, "//") == 0 ||
  16654. scheme_host_port.find("://") < scheme_host_port.find('/')) {
  16655. // A URL, but not one this client can use, such as one with userinfo. A
  16656. // Unix socket path may have "//" further on.
  16657. cli_ = detail::make_unique<detail::InvalidClientImpl>();
  16658. } else {
  16659. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  16660. // if port param below changes.
  16661. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  16662. client_cert_path, client_key_path);
  16663. }
  16664. }
  16665. inline Client::Client(const std::string &host, int port)
  16666. : Client(host, port, std::string(), std::string()) {}
  16667. inline Client::Client(const std::string &host, int port,
  16668. const std::string &client_cert_path,
  16669. const std::string &client_key_path)
  16670. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  16671. client_key_path)) {}
  16672. inline Client::~Client() = default;
  16673. inline bool Client::is_valid() const {
  16674. return cli_ != nullptr && cli_->is_valid();
  16675. }
  16676. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  16677. return cli_->Get(path, std::move(progress));
  16678. }
  16679. inline Result Client::Get(const std::string &path, const Headers &headers,
  16680. DownloadProgress progress) {
  16681. return cli_->Get(path, headers, std::move(progress));
  16682. }
  16683. inline Result Client::Get(const std::string &path,
  16684. ContentReceiver content_receiver,
  16685. DownloadProgress progress) {
  16686. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  16687. }
  16688. inline Result Client::Get(const std::string &path, const Headers &headers,
  16689. ContentReceiver content_receiver,
  16690. DownloadProgress progress) {
  16691. return cli_->Get(path, headers, std::move(content_receiver),
  16692. std::move(progress));
  16693. }
  16694. inline Result Client::Get(const std::string &path,
  16695. ResponseHandler response_handler,
  16696. ContentReceiver content_receiver,
  16697. DownloadProgress progress) {
  16698. return cli_->Get(path, std::move(response_handler),
  16699. std::move(content_receiver), std::move(progress));
  16700. }
  16701. inline Result Client::Get(const std::string &path, const Headers &headers,
  16702. ResponseHandler response_handler,
  16703. ContentReceiver content_receiver,
  16704. DownloadProgress progress) {
  16705. return cli_->Get(path, headers, std::move(response_handler),
  16706. std::move(content_receiver), std::move(progress));
  16707. }
  16708. inline Result Client::Get(const std::string &path, const Params &params,
  16709. DownloadProgress progress) {
  16710. return cli_->Get(path, params, std::move(progress));
  16711. }
  16712. inline Result Client::Get(const std::string &path, const Params &params,
  16713. const Headers &headers, DownloadProgress progress) {
  16714. return cli_->Get(path, params, headers, std::move(progress));
  16715. }
  16716. inline Result Client::Get(const std::string &path, const Params &params,
  16717. const Headers &headers,
  16718. ContentReceiver content_receiver,
  16719. DownloadProgress progress) {
  16720. return cli_->Get(path, params, headers, std::move(content_receiver),
  16721. std::move(progress));
  16722. }
  16723. inline Result Client::Get(const std::string &path, const Params &params,
  16724. const Headers &headers,
  16725. ResponseHandler response_handler,
  16726. ContentReceiver content_receiver,
  16727. DownloadProgress progress) {
  16728. return cli_->Get(path, params, headers, std::move(response_handler),
  16729. std::move(content_receiver), std::move(progress));
  16730. }
  16731. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  16732. inline Result Client::Head(const std::string &path, const Headers &headers) {
  16733. return cli_->Head(path, headers);
  16734. }
  16735. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  16736. inline Result Client::Post(const std::string &path, const Headers &headers) {
  16737. return cli_->Post(path, headers);
  16738. }
  16739. inline Result Client::Post(const std::string &path, const char *body,
  16740. size_t content_length,
  16741. const std::string &content_type,
  16742. UploadProgress progress) {
  16743. return cli_->Post(path, body, content_length, content_type, progress);
  16744. }
  16745. inline Result Client::Post(const std::string &path, const Headers &headers,
  16746. const char *body, size_t content_length,
  16747. const std::string &content_type,
  16748. UploadProgress progress) {
  16749. return cli_->Post(path, headers, body, content_length, content_type,
  16750. progress);
  16751. }
  16752. inline Result Client::Post(const std::string &path, const std::string &body,
  16753. const std::string &content_type,
  16754. UploadProgress progress) {
  16755. return cli_->Post(path, body, content_type, progress);
  16756. }
  16757. inline Result Client::Post(const std::string &path, const Headers &headers,
  16758. const std::string &body,
  16759. const std::string &content_type,
  16760. UploadProgress progress) {
  16761. return cli_->Post(path, headers, body, content_type, progress);
  16762. }
  16763. inline Result Client::Post(const std::string &path, size_t content_length,
  16764. ContentProvider content_provider,
  16765. const std::string &content_type,
  16766. UploadProgress progress) {
  16767. return cli_->Post(path, content_length, std::move(content_provider),
  16768. content_type, progress);
  16769. }
  16770. inline Result Client::Post(const std::string &path, size_t content_length,
  16771. ContentProvider content_provider,
  16772. const std::string &content_type,
  16773. ContentReceiver content_receiver,
  16774. UploadProgress progress) {
  16775. return cli_->Post(path, content_length, std::move(content_provider),
  16776. content_type, std::move(content_receiver), progress);
  16777. }
  16778. inline Result Client::Post(const std::string &path,
  16779. ContentProviderWithoutLength content_provider,
  16780. const std::string &content_type,
  16781. UploadProgress progress) {
  16782. return cli_->Post(path, std::move(content_provider), content_type, progress);
  16783. }
  16784. inline Result Client::Post(const std::string &path,
  16785. ContentProviderWithoutLength content_provider,
  16786. const std::string &content_type,
  16787. ContentReceiver content_receiver,
  16788. UploadProgress progress) {
  16789. return cli_->Post(path, std::move(content_provider), content_type,
  16790. std::move(content_receiver), progress);
  16791. }
  16792. inline Result Client::Post(const std::string &path, const Headers &headers,
  16793. size_t content_length,
  16794. ContentProvider content_provider,
  16795. const std::string &content_type,
  16796. UploadProgress progress) {
  16797. return cli_->Post(path, headers, content_length, std::move(content_provider),
  16798. content_type, progress);
  16799. }
  16800. inline Result Client::Post(const std::string &path, const Headers &headers,
  16801. size_t content_length,
  16802. ContentProvider content_provider,
  16803. const std::string &content_type,
  16804. ContentReceiver content_receiver,
  16805. DownloadProgress progress) {
  16806. return cli_->Post(path, headers, content_length, std::move(content_provider),
  16807. content_type, std::move(content_receiver), progress);
  16808. }
  16809. inline Result Client::Post(const std::string &path, const Headers &headers,
  16810. ContentProviderWithoutLength content_provider,
  16811. const std::string &content_type,
  16812. UploadProgress progress) {
  16813. return cli_->Post(path, headers, std::move(content_provider), content_type,
  16814. progress);
  16815. }
  16816. inline Result Client::Post(const std::string &path, const Headers &headers,
  16817. ContentProviderWithoutLength content_provider,
  16818. const std::string &content_type,
  16819. ContentReceiver content_receiver,
  16820. DownloadProgress progress) {
  16821. return cli_->Post(path, headers, std::move(content_provider), content_type,
  16822. std::move(content_receiver), progress);
  16823. }
  16824. inline Result Client::Post(const std::string &path, const Params &params) {
  16825. return cli_->Post(path, params);
  16826. }
  16827. inline Result Client::Post(const std::string &path, const Headers &headers,
  16828. const Params &params) {
  16829. return cli_->Post(path, headers, params);
  16830. }
  16831. inline Result Client::Post(const std::string &path,
  16832. const UploadFormDataItems &items,
  16833. UploadProgress progress) {
  16834. return cli_->Post(path, items, progress);
  16835. }
  16836. inline Result Client::Post(const std::string &path, const Headers &headers,
  16837. const UploadFormDataItems &items,
  16838. UploadProgress progress) {
  16839. return cli_->Post(path, headers, items, progress);
  16840. }
  16841. inline Result Client::Post(const std::string &path, const Headers &headers,
  16842. const UploadFormDataItems &items,
  16843. const std::string &boundary,
  16844. UploadProgress progress) {
  16845. return cli_->Post(path, headers, items, boundary, progress);
  16846. }
  16847. inline Result Client::Post(const std::string &path, const Headers &headers,
  16848. const UploadFormDataItems &items,
  16849. const FormDataProviderItems &provider_items,
  16850. UploadProgress progress) {
  16851. return cli_->Post(path, headers, items, provider_items, progress);
  16852. }
  16853. inline Result Client::Post(const std::string &path, const Headers &headers,
  16854. const std::string &body,
  16855. const std::string &content_type,
  16856. ContentReceiver content_receiver,
  16857. DownloadProgress progress) {
  16858. return cli_->Post(path, headers, body, content_type,
  16859. std::move(content_receiver), progress);
  16860. }
  16861. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  16862. inline Result Client::Put(const std::string &path, const Headers &headers) {
  16863. return cli_->Put(path, headers);
  16864. }
  16865. inline Result Client::Put(const std::string &path, const char *body,
  16866. size_t content_length,
  16867. const std::string &content_type,
  16868. UploadProgress progress) {
  16869. return cli_->Put(path, body, content_length, content_type, progress);
  16870. }
  16871. inline Result Client::Put(const std::string &path, const Headers &headers,
  16872. const char *body, size_t content_length,
  16873. const std::string &content_type,
  16874. UploadProgress progress) {
  16875. return cli_->Put(path, headers, body, content_length, content_type, progress);
  16876. }
  16877. inline Result Client::Put(const std::string &path, const std::string &body,
  16878. const std::string &content_type,
  16879. UploadProgress progress) {
  16880. return cli_->Put(path, body, content_type, progress);
  16881. }
  16882. inline Result Client::Put(const std::string &path, const Headers &headers,
  16883. const std::string &body,
  16884. const std::string &content_type,
  16885. UploadProgress progress) {
  16886. return cli_->Put(path, headers, body, content_type, progress);
  16887. }
  16888. inline Result Client::Put(const std::string &path, size_t content_length,
  16889. ContentProvider content_provider,
  16890. const std::string &content_type,
  16891. UploadProgress progress) {
  16892. return cli_->Put(path, content_length, std::move(content_provider),
  16893. content_type, progress);
  16894. }
  16895. inline Result Client::Put(const std::string &path, size_t content_length,
  16896. ContentProvider content_provider,
  16897. const std::string &content_type,
  16898. ContentReceiver content_receiver,
  16899. UploadProgress progress) {
  16900. return cli_->Put(path, content_length, std::move(content_provider),
  16901. content_type, std::move(content_receiver), progress);
  16902. }
  16903. inline Result Client::Put(const std::string &path,
  16904. ContentProviderWithoutLength content_provider,
  16905. const std::string &content_type,
  16906. UploadProgress progress) {
  16907. return cli_->Put(path, std::move(content_provider), content_type, progress);
  16908. }
  16909. inline Result Client::Put(const std::string &path,
  16910. ContentProviderWithoutLength content_provider,
  16911. const std::string &content_type,
  16912. ContentReceiver content_receiver,
  16913. UploadProgress progress) {
  16914. return cli_->Put(path, std::move(content_provider), content_type,
  16915. std::move(content_receiver), progress);
  16916. }
  16917. inline Result Client::Put(const std::string &path, const Headers &headers,
  16918. size_t content_length,
  16919. ContentProvider content_provider,
  16920. const std::string &content_type,
  16921. UploadProgress progress) {
  16922. return cli_->Put(path, headers, content_length, std::move(content_provider),
  16923. content_type, progress);
  16924. }
  16925. inline Result Client::Put(const std::string &path, const Headers &headers,
  16926. size_t content_length,
  16927. ContentProvider content_provider,
  16928. const std::string &content_type,
  16929. ContentReceiver content_receiver,
  16930. UploadProgress progress) {
  16931. return cli_->Put(path, headers, content_length, std::move(content_provider),
  16932. content_type, std::move(content_receiver), progress);
  16933. }
  16934. inline Result Client::Put(const std::string &path, const Headers &headers,
  16935. ContentProviderWithoutLength content_provider,
  16936. const std::string &content_type,
  16937. UploadProgress progress) {
  16938. return cli_->Put(path, headers, std::move(content_provider), content_type,
  16939. progress);
  16940. }
  16941. inline Result Client::Put(const std::string &path, const Headers &headers,
  16942. ContentProviderWithoutLength content_provider,
  16943. const std::string &content_type,
  16944. ContentReceiver content_receiver,
  16945. UploadProgress progress) {
  16946. return cli_->Put(path, headers, std::move(content_provider), content_type,
  16947. std::move(content_receiver), progress);
  16948. }
  16949. inline Result Client::Put(const std::string &path, const Params &params) {
  16950. return cli_->Put(path, params);
  16951. }
  16952. inline Result Client::Put(const std::string &path, const Headers &headers,
  16953. const Params &params) {
  16954. return cli_->Put(path, headers, params);
  16955. }
  16956. inline Result Client::Put(const std::string &path,
  16957. const UploadFormDataItems &items,
  16958. UploadProgress progress) {
  16959. return cli_->Put(path, items, progress);
  16960. }
  16961. inline Result Client::Put(const std::string &path, const Headers &headers,
  16962. const UploadFormDataItems &items,
  16963. UploadProgress progress) {
  16964. return cli_->Put(path, headers, items, progress);
  16965. }
  16966. inline Result Client::Put(const std::string &path, const Headers &headers,
  16967. const UploadFormDataItems &items,
  16968. const std::string &boundary,
  16969. UploadProgress progress) {
  16970. return cli_->Put(path, headers, items, boundary, progress);
  16971. }
  16972. inline Result Client::Put(const std::string &path, const Headers &headers,
  16973. const UploadFormDataItems &items,
  16974. const FormDataProviderItems &provider_items,
  16975. UploadProgress progress) {
  16976. return cli_->Put(path, headers, items, provider_items, progress);
  16977. }
  16978. inline Result Client::Put(const std::string &path, const Headers &headers,
  16979. const std::string &body,
  16980. const std::string &content_type,
  16981. ContentReceiver content_receiver,
  16982. DownloadProgress progress) {
  16983. return cli_->Put(path, headers, body, content_type, content_receiver,
  16984. progress);
  16985. }
  16986. inline Result Client::Patch(const std::string &path) {
  16987. return cli_->Patch(path);
  16988. }
  16989. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  16990. return cli_->Patch(path, headers);
  16991. }
  16992. inline Result Client::Patch(const std::string &path, const char *body,
  16993. size_t content_length,
  16994. const std::string &content_type,
  16995. UploadProgress progress) {
  16996. return cli_->Patch(path, body, content_length, content_type, progress);
  16997. }
  16998. inline Result Client::Patch(const std::string &path, const Headers &headers,
  16999. const char *body, size_t content_length,
  17000. const std::string &content_type,
  17001. UploadProgress progress) {
  17002. return cli_->Patch(path, headers, body, content_length, content_type,
  17003. progress);
  17004. }
  17005. inline Result Client::Patch(const std::string &path, const std::string &body,
  17006. const std::string &content_type,
  17007. UploadProgress progress) {
  17008. return cli_->Patch(path, body, content_type, progress);
  17009. }
  17010. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17011. const std::string &body,
  17012. const std::string &content_type,
  17013. UploadProgress progress) {
  17014. return cli_->Patch(path, headers, body, content_type, progress);
  17015. }
  17016. inline Result Client::Patch(const std::string &path, size_t content_length,
  17017. ContentProvider content_provider,
  17018. const std::string &content_type,
  17019. UploadProgress progress) {
  17020. return cli_->Patch(path, content_length, std::move(content_provider),
  17021. content_type, progress);
  17022. }
  17023. inline Result Client::Patch(const std::string &path, size_t content_length,
  17024. ContentProvider content_provider,
  17025. const std::string &content_type,
  17026. ContentReceiver content_receiver,
  17027. UploadProgress progress) {
  17028. return cli_->Patch(path, content_length, std::move(content_provider),
  17029. content_type, std::move(content_receiver), progress);
  17030. }
  17031. inline Result Client::Patch(const std::string &path,
  17032. ContentProviderWithoutLength content_provider,
  17033. const std::string &content_type,
  17034. UploadProgress progress) {
  17035. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  17036. }
  17037. inline Result Client::Patch(const std::string &path,
  17038. ContentProviderWithoutLength content_provider,
  17039. const std::string &content_type,
  17040. ContentReceiver content_receiver,
  17041. UploadProgress progress) {
  17042. return cli_->Patch(path, std::move(content_provider), content_type,
  17043. std::move(content_receiver), progress);
  17044. }
  17045. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17046. size_t content_length,
  17047. ContentProvider content_provider,
  17048. const std::string &content_type,
  17049. UploadProgress progress) {
  17050. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  17051. content_type, progress);
  17052. }
  17053. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17054. size_t content_length,
  17055. ContentProvider content_provider,
  17056. const std::string &content_type,
  17057. ContentReceiver content_receiver,
  17058. UploadProgress progress) {
  17059. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  17060. content_type, std::move(content_receiver), progress);
  17061. }
  17062. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17063. ContentProviderWithoutLength content_provider,
  17064. const std::string &content_type,
  17065. UploadProgress progress) {
  17066. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  17067. progress);
  17068. }
  17069. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17070. ContentProviderWithoutLength content_provider,
  17071. const std::string &content_type,
  17072. ContentReceiver content_receiver,
  17073. UploadProgress progress) {
  17074. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  17075. std::move(content_receiver), progress);
  17076. }
  17077. inline Result Client::Patch(const std::string &path, const Params &params) {
  17078. return cli_->Patch(path, params);
  17079. }
  17080. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17081. const Params &params) {
  17082. return cli_->Patch(path, headers, params);
  17083. }
  17084. inline Result Client::Patch(const std::string &path,
  17085. const UploadFormDataItems &items,
  17086. UploadProgress progress) {
  17087. return cli_->Patch(path, items, progress);
  17088. }
  17089. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17090. const UploadFormDataItems &items,
  17091. UploadProgress progress) {
  17092. return cli_->Patch(path, headers, items, progress);
  17093. }
  17094. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17095. const UploadFormDataItems &items,
  17096. const std::string &boundary,
  17097. UploadProgress progress) {
  17098. return cli_->Patch(path, headers, items, boundary, progress);
  17099. }
  17100. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17101. const UploadFormDataItems &items,
  17102. const FormDataProviderItems &provider_items,
  17103. UploadProgress progress) {
  17104. return cli_->Patch(path, headers, items, provider_items, progress);
  17105. }
  17106. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17107. const std::string &body,
  17108. const std::string &content_type,
  17109. ContentReceiver content_receiver,
  17110. DownloadProgress progress) {
  17111. return cli_->Patch(path, headers, body, content_type, content_receiver,
  17112. progress);
  17113. }
  17114. inline Result Client::Delete(const std::string &path,
  17115. DownloadProgress progress) {
  17116. return cli_->Delete(path, progress);
  17117. }
  17118. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17119. DownloadProgress progress) {
  17120. return cli_->Delete(path, headers, progress);
  17121. }
  17122. inline Result Client::Delete(const std::string &path, const char *body,
  17123. size_t content_length,
  17124. const std::string &content_type,
  17125. DownloadProgress progress) {
  17126. return cli_->Delete(path, body, content_length, content_type, progress);
  17127. }
  17128. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17129. const char *body, size_t content_length,
  17130. const std::string &content_type,
  17131. DownloadProgress progress) {
  17132. return cli_->Delete(path, headers, body, content_length, content_type,
  17133. progress);
  17134. }
  17135. inline Result Client::Delete(const std::string &path, const std::string &body,
  17136. const std::string &content_type,
  17137. DownloadProgress progress) {
  17138. return cli_->Delete(path, body, content_type, progress);
  17139. }
  17140. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17141. const std::string &body,
  17142. const std::string &content_type,
  17143. DownloadProgress progress) {
  17144. return cli_->Delete(path, headers, body, content_type, progress);
  17145. }
  17146. inline Result Client::Delete(const std::string &path, const Params &params,
  17147. DownloadProgress progress) {
  17148. return cli_->Delete(path, params, progress);
  17149. }
  17150. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17151. const Params &params, DownloadProgress progress) {
  17152. return cli_->Delete(path, headers, params, progress);
  17153. }
  17154. inline Result Client::Options(const std::string &path) {
  17155. return cli_->Options(path);
  17156. }
  17157. inline Result Client::Options(const std::string &path, const Headers &headers) {
  17158. return cli_->Options(path, headers);
  17159. }
  17160. inline ClientImpl::StreamHandle
  17161. Client::open_stream(const std::string &method, const std::string &path,
  17162. const Params &params, const Headers &headers,
  17163. const std::string &body, const std::string &content_type) {
  17164. return cli_->open_stream(method, path, params, headers, body, content_type);
  17165. }
  17166. inline bool Client::send(Request &req, Response &res, Error &error) {
  17167. return cli_->send(req, res, error);
  17168. }
  17169. inline Result Client::send(const Request &req) { return cli_->send(req); }
  17170. inline void Client::stop() { cli_->stop(); }
  17171. inline std::string Client::host() const { return cli_->host(); }
  17172. inline int Client::port() const { return cli_->port(); }
  17173. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  17174. inline socket_t Client::socket() const { return cli_->socket(); }
  17175. inline void
  17176. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  17177. cli_->set_direct_hostname_addr_map(std::move(addr_map));
  17178. }
  17179. inline void Client::set_direct_hostname_addr_map(
  17180. std::map<std::string, std::string> addr_map) {
  17181. cli_->set_direct_hostname_addr_map(std::move(addr_map));
  17182. }
  17183. inline void Client::set_tunnel_hostname_addr_map(
  17184. std::map<std::string, std::string> addr_map) {
  17185. cli_->set_tunnel_hostname_addr_map(std::move(addr_map));
  17186. }
  17187. inline void Client::set_default_headers(Headers headers) {
  17188. cli_->set_default_headers(std::move(headers));
  17189. }
  17190. inline void Client::set_header_writer(
  17191. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  17192. cli_->set_header_writer(writer);
  17193. }
  17194. inline void Client::set_address_family(int family) {
  17195. cli_->set_address_family(family);
  17196. }
  17197. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  17198. inline void Client::set_socket_options(SocketOptions socket_options) {
  17199. cli_->set_socket_options(std::move(socket_options));
  17200. }
  17201. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  17202. cli_->set_connection_timeout(sec, usec);
  17203. }
  17204. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  17205. cli_->set_read_timeout(sec, usec);
  17206. }
  17207. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  17208. cli_->set_write_timeout(sec, usec);
  17209. }
  17210. inline void Client::set_basic_auth(const std::string &username,
  17211. const std::string &password) {
  17212. cli_->set_basic_auth(username, password);
  17213. }
  17214. inline void Client::set_bearer_token_auth(const std::string &token) {
  17215. cli_->set_bearer_token_auth(token);
  17216. }
  17217. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  17218. inline void Client::set_follow_location(bool on) {
  17219. cli_->set_follow_location(on);
  17220. }
  17221. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  17222. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  17223. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  17224. inline void Client::set_payload_max_length(size_t length) {
  17225. cli_->set_payload_max_length(length);
  17226. }
  17227. inline void Client::set_interface(const std::string &intf) {
  17228. cli_->set_interface(intf);
  17229. }
  17230. inline void Client::set_proxy(const std::string &host, int port) {
  17231. cli_->set_proxy(host, port);
  17232. }
  17233. inline void Client::set_proxy_basic_auth(const std::string &username,
  17234. const std::string &password) {
  17235. cli_->set_proxy_basic_auth(username, password);
  17236. }
  17237. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  17238. cli_->set_proxy_bearer_token_auth(token);
  17239. }
  17240. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  17241. cli_->set_no_proxy(patterns);
  17242. }
  17243. inline void Client::set_logger(Logger logger) {
  17244. cli_->set_logger(std::move(logger));
  17245. }
  17246. inline void Client::set_error_logger(ErrorLogger error_logger) {
  17247. cli_->set_error_logger(std::move(error_logger));
  17248. }
  17249. /*
  17250. * Group 6: SSL Server and Client implementation
  17251. */
  17252. #ifdef CPPHTTPLIB_SSL_ENABLED
  17253. // SSL HTTP server implementation
  17254. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  17255. const char *client_ca_cert_file_path,
  17256. const char *client_ca_cert_dir_path,
  17257. const char *private_key_password) {
  17258. using namespace tls;
  17259. ctx_ = create_server_context();
  17260. if (!ctx_) { return; }
  17261. // Load server certificate and private key
  17262. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  17263. private_key_password)) {
  17264. last_ssl_error_ = static_cast<int>(get_error());
  17265. free_context(ctx_);
  17266. ctx_ = nullptr;
  17267. return;
  17268. }
  17269. // Load client CA certificates for client authentication
  17270. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  17271. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  17272. client_ca_cert_dir_path)) {
  17273. last_ssl_error_ = static_cast<int>(get_error());
  17274. free_context(ctx_);
  17275. ctx_ = nullptr;
  17276. return;
  17277. }
  17278. // Enable client certificate verification
  17279. set_verify_client(ctx_, true);
  17280. }
  17281. }
  17282. inline SSLServer::SSLServer(const PemMemory &pem) {
  17283. using namespace tls;
  17284. ctx_ = create_server_context();
  17285. if (ctx_) {
  17286. std::string cert_buf, key_buf;
  17287. if (!set_server_cert_pem(
  17288. ctx_, detail::pem_c_str(pem.cert_pem, pem.cert_pem_len, cert_buf),
  17289. detail::pem_c_str(pem.key_pem, pem.key_pem_len, key_buf),
  17290. pem.private_key_password)) {
  17291. last_ssl_error_ = static_cast<int>(get_error());
  17292. free_context(ctx_);
  17293. ctx_ = nullptr;
  17294. } else if (pem.client_ca_pem) {
  17295. auto ca_len = pem.client_ca_pem_len ? pem.client_ca_pem_len
  17296. : strlen(pem.client_ca_pem);
  17297. if (!load_ca_pem(ctx_, pem.client_ca_pem, ca_len)) {
  17298. last_ssl_error_ = static_cast<int>(get_error());
  17299. free_context(ctx_);
  17300. ctx_ = nullptr;
  17301. } else {
  17302. set_verify_client(ctx_, true);
  17303. }
  17304. }
  17305. }
  17306. }
  17307. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  17308. using namespace tls;
  17309. ctx_ = create_server_context();
  17310. if (ctx_) {
  17311. if (!setup_callback(ctx_)) {
  17312. free_context(ctx_);
  17313. ctx_ = nullptr;
  17314. }
  17315. }
  17316. }
  17317. inline SSLServer::~SSLServer() {
  17318. if (ctx_) { tls::free_context(ctx_); }
  17319. }
  17320. inline bool SSLServer::is_valid() const {
  17321. return ctx_ != nullptr && Server::is_valid();
  17322. }
  17323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17324. namespace detail {
  17325. // Before these, SSL_free_buffers() could free a buffer that a record whose
  17326. // body has not arrived yet still uses (CVE-2024-4741). `version` is
  17327. // OpenSSL_version_num().
  17328. inline bool ssl_free_buffers_is_safe(unsigned long version) {
  17329. if (version >= 0x30400000UL) { return true; }
  17330. if (version >= 0x30300000UL) { return version >= 0x30300010UL; } // 3.3.1
  17331. if (version >= 0x30200000UL) { return version >= 0x30200020UL; } // 3.2.2
  17332. if (version >= 0x30100000UL) { return version >= 0x30100060UL; } // 3.1.6
  17333. return version >= 0x300000e0UL; // 3.0.14
  17334. }
  17335. } // namespace detail
  17336. #endif
  17337. // A connection that keep-alive parking keeps for SSLServer. The worker that
  17338. // first resumes it runs the handshake, so one that has not sent its
  17339. // ClientHello yet waits in the event loop like an idle connection.
  17340. struct SSLServer::TlsConnection final : Server::KeepAliveConnection {
  17341. TlsConnection(socket_t s, SSLServer &server)
  17342. : KeepAliveConnection(s, server), ssl_svr(server) {}
  17343. ~TlsConnection() override { tls::free_session(session); }
  17344. bool open() override {
  17345. // A handshake would hold up the stop() that is under way.
  17346. if (ssl_svr.is_stopping()) { return false; }
  17347. session = ssl_svr.start_session(sock);
  17348. if (!session) { return false; }
  17349. // The handshake has read what the event loop saw, so a client that sends
  17350. // nothing after it is parked instead of being waited for.
  17351. turn.woken = false;
  17352. return true;
  17353. }
  17354. // The session, not the stream, holds what a pipelined request has left.
  17355. bool serve() override {
  17356. detail::SSLSocketStream strm(
  17357. sock, session, ssl_svr.read_timeout_sec_, ssl_svr.read_timeout_usec_,
  17358. ssl_svr.write_timeout_sec_, ssl_svr.write_timeout_usec_);
  17359. return serve_on(strm, [this](Request &req) { req.ssl = session; });
  17360. }
  17361. void release_buffers() override {
  17362. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  17363. !defined(LIBRESSL_VERSION_NUMBER)
  17364. // The record buffers are most of an idle session's memory, and the next
  17365. // read makes new ones. The library that runs decides whether that is safe.
  17366. static const auto safe =
  17367. detail::ssl_free_buffers_is_safe(OpenSSL_version_num());
  17368. if (safe) { SSL_free_buffers(static_cast<SSL *>(session)); }
  17369. #endif
  17370. }
  17371. void shut_down(bool graceful) override { tls::shutdown(session, graceful); }
  17372. SSLServer &ssl_svr;
  17373. tls::session_t session = nullptr;
  17374. };
  17375. inline std::shared_ptr<Server::KeepAliveConnection>
  17376. SSLServer::new_keep_alive_connection(socket_t sock) {
  17377. return std::make_shared<TlsConnection>(sock, *this);
  17378. }
  17379. inline tls::session_t SSLServer::start_session(socket_t sock) {
  17380. using namespace tls;
  17381. session_t session = nullptr;
  17382. {
  17383. std::unique_lock<std::mutex> lock(ctx_mutex_);
  17384. ctx_cv_.wait(lock, [&] { return updates_pending_ == 0; });
  17385. session = create_session(static_cast<ctx_t>(ctx_), sock);
  17386. if (session) { handshakes_in_progress_++; }
  17387. }
  17388. if (!session) {
  17389. last_ssl_error_ = static_cast<int>(get_error());
  17390. return nullptr;
  17391. }
  17392. // Frees the session on all paths but success (including exceptions)
  17393. auto accepted = false;
  17394. auto cleanup = detail::scope_exit([&] {
  17395. if (!accepted) { free_session(session); }
  17396. });
  17397. // Perform TLS accept handshake with timeout
  17398. TlsError tls_err;
  17399. {
  17400. auto handshake_left = detail::scope_exit([&] {
  17401. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17402. if (--handshakes_in_progress_ == 0) { ctx_cv_.notify_all(); }
  17403. });
  17404. accepted =
  17405. accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  17406. &tls_err, [this]() { return is_stopping(); });
  17407. }
  17408. if (!accepted) {
  17409. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17410. // Map TlsError to legacy ssl_error for backward compatibility
  17411. if (tls_err.code == ErrorCode::WantRead) {
  17412. last_ssl_error_ = SSL_ERROR_WANT_READ;
  17413. } else if (tls_err.code == ErrorCode::WantWrite) {
  17414. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  17415. } else {
  17416. last_ssl_error_ = SSL_ERROR_SSL;
  17417. }
  17418. #else
  17419. last_ssl_error_ = static_cast<int>(get_error());
  17420. #endif
  17421. return nullptr;
  17422. }
  17423. return session;
  17424. }
  17425. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  17426. auto session = start_session(sock);
  17427. if (!session) {
  17428. detail::shutdown_socket(sock);
  17429. detail::close_socket(sock);
  17430. return false;
  17431. }
  17432. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  17433. bool ret = false;
  17434. bool websocket_upgraded = false;
  17435. auto cleanup = detail::scope_exit([&] {
  17436. tls::shutdown(session, !websocket_upgraded && ret);
  17437. tls::free_session(session);
  17438. detail::drain_and_close_socket(sock);
  17439. });
  17440. std::string remote_addr;
  17441. int remote_port = 0;
  17442. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  17443. std::string local_addr;
  17444. int local_port = 0;
  17445. detail::get_local_ip_and_port(sock, local_addr, local_port);
  17446. ret = serve_guarded([&]() {
  17447. return detail::process_server_socket_ssl(
  17448. svr_sock_, session, sock, keep_alive_max_count_,
  17449. keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
  17450. write_timeout_sec_, write_timeout_usec_,
  17451. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  17452. return process_request(
  17453. strm, remote_addr, remote_port, local_addr, local_port,
  17454. close_connection, connection_closed,
  17455. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  17456. });
  17457. });
  17458. return ret;
  17459. }
  17460. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  17461. const char *key_pem,
  17462. const char *client_ca_pem,
  17463. const char *password) {
  17464. if (!ctx_) { return false; }
  17465. std::unique_lock<std::mutex> lock(ctx_mutex_);
  17466. updates_pending_++;
  17467. auto se = detail::scope_exit([&] {
  17468. if (--updates_pending_ == 0) { ctx_cv_.notify_all(); }
  17469. });
  17470. ctx_cv_.wait(lock, [&] { return handshakes_in_progress_ == 0; });
  17471. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  17472. return false;
  17473. }
  17474. if (client_ca_pem) {
  17475. if (!tls::update_server_client_ca(ctx_, client_ca_pem)) { return false; }
  17476. // As in the constructors, a client CA makes client certificates required
  17477. tls::set_verify_client(ctx_, true);
  17478. }
  17479. return true;
  17480. }
  17481. // SSL HTTP client implementation
  17482. inline SSLClient::~SSLClient() {
  17483. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  17484. // base function rather than the derived function once we get to the
  17485. // base class destructor, and won't free the SSL (causing a leak).
  17486. // This must happen before the context is freed below: some backends
  17487. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  17488. // context, so freeing the context first leaves close_notify reading
  17489. // freed memory.
  17490. shutdown_ssl_impl(socket_, true);
  17491. if (ctx_) {
  17492. tls::free_context(ctx_);
  17493. ctx_ = nullptr;
  17494. }
  17495. }
  17496. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  17497. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  17498. shutdown_ssl_impl(socket, shutdown_gracefully);
  17499. }
  17500. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  17501. bool shutdown_gracefully) {
  17502. if (socket.sock == INVALID_SOCKET) {
  17503. assert(socket.ssl == nullptr);
  17504. return;
  17505. }
  17506. if (socket.ssl) {
  17507. tls::shutdown(socket.ssl, shutdown_gracefully);
  17508. {
  17509. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17510. tls::free_session(socket.ssl);
  17511. }
  17512. socket.ssl = nullptr;
  17513. }
  17514. assert(socket.ssl == nullptr);
  17515. }
  17516. inline bool SSLClient::process_socket(
  17517. const Socket &socket,
  17518. std::chrono::time_point<std::chrono::steady_clock> start_time,
  17519. std::function<bool(Stream &strm)> callback) {
  17520. assert(socket.ssl);
  17521. return detail::process_client_socket_ssl(
  17522. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  17523. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  17524. [&](detail::SSLSocketStream &strm) {
  17525. auto ret = callback(strm);
  17526. // A request that failed after the handshake reports Error::Read or
  17527. // Error::Write; keep the TLS error behind it, such as a fatal alert
  17528. // from the server, for Result::ssl_error() and ssl_backend_error()
  17529. const auto &tls_error = strm.tls_error();
  17530. if (!ret && tls_error.code != tls::ErrorCode::Success) {
  17531. last_ssl_error_ = static_cast<int>(tls_error.code);
  17532. last_backend_error_ = tls_error.backend_code;
  17533. }
  17534. return ret;
  17535. });
  17536. }
  17537. inline bool SSLClient::is_ssl() const { return true; }
  17538. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  17539. if (!is_valid()) {
  17540. error = Error::SSLConnection;
  17541. return false;
  17542. }
  17543. return ClientImpl::create_and_connect_socket(socket, error);
  17544. }
  17545. inline bool SSLClient::setup_proxy_connection(
  17546. Socket &socket,
  17547. std::chrono::time_point<std::chrono::steady_clock> start_time,
  17548. Response &res, bool &success, Error &error) {
  17549. if (!is_proxy_enabled_for_host(host_)) { return true; }
  17550. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  17551. return false;
  17552. }
  17553. if (!initialize_ssl(socket, error)) {
  17554. shutdown_socket(socket);
  17555. close_socket(socket);
  17556. success = false;
  17557. return false;
  17558. }
  17559. return true;
  17560. }
  17561. // Assumes that socket is a connection being opened, which no other thread uses
  17562. inline bool SSLClient::connect_with_proxy(
  17563. Socket &socket,
  17564. std::chrono::time_point<std::chrono::steady_clock> start_time,
  17565. Response &res, bool &success, Error &error) {
  17566. success = true;
  17567. auto connect_target =
  17568. detail::make_connect_request_target(tunnel_addr_map_, host_, port_);
  17569. auto retargeted = connect_target !=
  17570. detail::make_host_and_port_string_always_port(host_, port_);
  17571. Response proxy_res;
  17572. if (!detail::process_client_socket(
  17573. socket.sock, read_timeout_sec_, read_timeout_usec_,
  17574. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  17575. start_time, [&](Stream &strm) {
  17576. strm.set_read_interrupt(stop_interrupt());
  17577. Request req2;
  17578. req2.method = "CONNECT";
  17579. req2.path = connect_target;
  17580. if (retargeted) { req2.set_header("Host", connect_target); }
  17581. if (max_timeout_msec_ > 0) {
  17582. req2.start_time_ = std::chrono::steady_clock::now();
  17583. }
  17584. return process_request(strm, req2, proxy_res, false, error);
  17585. })) {
  17586. // Thread-safe to close everything because we are assuming there are no
  17587. // requests in flight
  17588. shutdown_ssl(socket, true);
  17589. shutdown_socket(socket);
  17590. close_socket(socket);
  17591. success = false;
  17592. return false;
  17593. }
  17594. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  17595. if (!proxy_digest_auth_username_.empty() &&
  17596. !proxy_digest_auth_password_.empty()) {
  17597. std::map<std::string, std::string> auth;
  17598. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  17599. // Close the current socket and create a new one for the authenticated
  17600. // request
  17601. shutdown_ssl(socket, true);
  17602. shutdown_socket(socket);
  17603. close_socket(socket);
  17604. // Create a new socket for the authenticated CONNECT request
  17605. if (!ensure_socket_connection(socket, error)) {
  17606. success = false;
  17607. return false;
  17608. }
  17609. proxy_res = Response();
  17610. if (!detail::process_client_socket(
  17611. socket.sock, read_timeout_sec_, read_timeout_usec_,
  17612. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  17613. start_time, [&](Stream &strm) {
  17614. strm.set_read_interrupt(stop_interrupt());
  17615. Request req3;
  17616. req3.method = "CONNECT";
  17617. req3.path = connect_target;
  17618. if (retargeted) { req3.set_header("Host", connect_target); }
  17619. req3.headers.insert(detail::make_digest_authentication_header(
  17620. req3, make_request_target(req3), auth, 1,
  17621. detail::random_string(10), proxy_digest_auth_username_,
  17622. proxy_digest_auth_password_, true));
  17623. if (max_timeout_msec_ > 0) {
  17624. req3.start_time_ = std::chrono::steady_clock::now();
  17625. }
  17626. return process_request(strm, req3, proxy_res, false, error);
  17627. })) {
  17628. // Thread-safe to close everything because we are assuming there are
  17629. // no requests in flight
  17630. shutdown_ssl(socket, true);
  17631. shutdown_socket(socket);
  17632. close_socket(socket);
  17633. success = false;
  17634. return false;
  17635. }
  17636. }
  17637. }
  17638. }
  17639. // If status code is not 200, proxy request is failed.
  17640. // Set error to ProxyConnection. A 407 is returned as the response of the
  17641. // request, so the caller sees the proxy asks for credentials; any other
  17642. // status would read as the answer of the origin, which it never reached.
  17643. if (proxy_res.status != StatusCode::OK_200) {
  17644. error = Error::ProxyConnection;
  17645. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  17646. res = std::move(proxy_res);
  17647. } else {
  17648. success = false;
  17649. }
  17650. // Thread-safe to close everything because we are assuming there are
  17651. // no requests in flight
  17652. shutdown_ssl(socket, true);
  17653. shutdown_socket(socket);
  17654. close_socket(socket);
  17655. return false;
  17656. }
  17657. return true;
  17658. }
  17659. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  17660. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  17661. if (is_proxy_enabled_for_host(host_)) { return true; }
  17662. if (!initialize_ssl(socket, error)) {
  17663. shutdown_socket(socket);
  17664. close_socket(socket);
  17665. return false;
  17666. }
  17667. return true;
  17668. }
  17669. // SSL HTTP client implementation
  17670. inline SSLClient::SSLClient(const std::string &host)
  17671. : SSLClient(host, 443, std::string(), std::string()) {}
  17672. inline SSLClient::SSLClient(const std::string &host, int port)
  17673. : SSLClient(host, port, std::string(), std::string()) {}
  17674. inline void SSLClient::init_ctx() {
  17675. ctx_ = tls::create_client_context();
  17676. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  17677. }
  17678. inline void SSLClient::reset_ctx_on_error() {
  17679. last_backend_error_ = tls::get_error();
  17680. tls::free_context(ctx_);
  17681. ctx_ = nullptr;
  17682. }
  17683. inline SSLClient::SSLClient(const std::string &host, int port,
  17684. const std::string &client_cert_path,
  17685. const std::string &client_key_path,
  17686. const std::string &private_key_password)
  17687. : ClientImpl(host, port, client_cert_path, client_key_path) {
  17688. init_ctx();
  17689. if (!ctx_) { return; }
  17690. if (!client_cert_path.empty() && !client_key_path.empty()) {
  17691. const char *password =
  17692. private_key_password.empty() ? nullptr : private_key_password.c_str();
  17693. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  17694. client_key_path.c_str(), password)) {
  17695. reset_ctx_on_error();
  17696. }
  17697. }
  17698. }
  17699. inline SSLClient::SSLClient(const std::string &host, int port,
  17700. const PemMemory &pem)
  17701. : ClientImpl(host, port) {
  17702. init_ctx();
  17703. if (!ctx_) { return; }
  17704. if (pem.cert_pem && pem.key_pem) {
  17705. std::string cert_buf, key_buf;
  17706. if (!tls::set_client_cert_pem(
  17707. ctx_, detail::pem_c_str(pem.cert_pem, pem.cert_pem_len, cert_buf),
  17708. detail::pem_c_str(pem.key_pem, pem.key_pem_len, key_buf),
  17709. pem.private_key_password)) {
  17710. reset_ctx_on_error();
  17711. }
  17712. }
  17713. }
  17714. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  17715. if (ca_cert_store && ctx_) {
  17716. // set_ca_store takes ownership of ca_cert_store
  17717. tls::set_ca_store(ctx_, ca_cert_store);
  17718. ca_cert_store_set_ = true;
  17719. } else if (ca_cert_store) {
  17720. tls::free_ca_store(ca_cert_store);
  17721. }
  17722. custom_ca_loaded_ = true;
  17723. tls_settings_changed();
  17724. }
  17725. inline void
  17726. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  17727. if (!ctx_) { return; }
  17728. server_certificate_verifier_ = verifier;
  17729. {
  17730. // Under the lock that creating a session from ctx_ takes
  17731. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17732. tls::set_verify_callback(ctx_, std::move(verifier));
  17733. }
  17734. tls_settings_changed();
  17735. }
  17736. inline void SSLClient::set_session_verifier(
  17737. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  17738. session_verifier_ = std::move(verifier);
  17739. tls_settings_changed();
  17740. }
  17741. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  17742. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  17743. if (enable_windows_cert_verification_ == enabled) { return; }
  17744. enable_windows_cert_verification_ = enabled;
  17745. tls_settings_changed();
  17746. }
  17747. #endif
  17748. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  17749. std::size_t size) {
  17750. if (ctx_ && ca_cert && size > 0) {
  17751. // Every PEM loaded, for redirect transfer
  17752. if (!ca_cert_pem_.empty() && ca_cert_pem_.back() != '\n') {
  17753. ca_cert_pem_ += '\n';
  17754. }
  17755. ca_cert_pem_.append(ca_cert, size);
  17756. tls::load_ca_pem(ctx_, ca_cert, size);
  17757. }
  17758. custom_ca_loaded_ = true;
  17759. tls_settings_changed();
  17760. }
  17761. inline bool SSLClient::load_certs() {
  17762. auto ret = true;
  17763. // call_once rather than the plain flag WebSocketClient::create_stream() uses:
  17764. // one client is shared across concurrent requests here.
  17765. std::call_once(initialize_cert_, [&]() {
  17766. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17767. ret = detail::load_client_ca_config(ctx_, ca_cert_file_path_,
  17768. ca_cert_dir_path_, custom_ca_loaded_,
  17769. system_ca_mode_, last_backend_error_);
  17770. });
  17771. return ret;
  17772. }
  17773. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  17774. // Load CA certificates if server verification is enabled
  17775. if (server_certificate_verification_) {
  17776. if (!load_certs()) {
  17777. error = Error::SSLLoadingCerts;
  17778. return false;
  17779. }
  17780. }
  17781. detail::ClientTlsSessionOptions options;
  17782. options.server_hostname_verification = server_hostname_verification_;
  17783. options.session_verifier = session_verifier_;
  17784. options.interrupted = stop_interrupt();
  17785. options.ctx_mutex = &ctx_mutex_;
  17786. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  17787. options.windows_cert_verification = detail::use_windows_cert_verification(
  17788. enable_windows_cert_verification_, ca_cert_file_path_, ca_cert_dir_path_,
  17789. custom_ca_loaded_, system_ca_mode_);
  17790. // Only a verifier set through set_server_certificate_verifier() is seen
  17791. // here, not one installed with tls::set_verify_callback() directly.
  17792. options.server_certificate_verifier_set =
  17793. static_cast<bool>(server_certificate_verifier_);
  17794. #endif
  17795. tls::session_t session = nullptr;
  17796. // Use scope_exit to ensure session is freed on error paths
  17797. bool success = false;
  17798. auto session_guard = detail::scope_exit([&] {
  17799. if (!success) { tls::free_session(session); }
  17800. });
  17801. detail::ClientTlsSessionError tls_error;
  17802. if (!detail::setup_client_tls_session(
  17803. host_, ctx_, session, socket.sock, server_certificate_verification_,
  17804. connection_timeout_sec_, connection_timeout_usec_, &tls_error,
  17805. options)) {
  17806. error = tls_error.error;
  17807. last_ssl_error_ = tls_error.ssl_error;
  17808. last_backend_error_ = tls_error.backend_error;
  17809. return false;
  17810. }
  17811. success = true;
  17812. socket.ssl = session;
  17813. return true;
  17814. }
  17815. inline void Client::set_digest_auth(const std::string &username,
  17816. const std::string &password) {
  17817. cli_->set_digest_auth(username, password);
  17818. }
  17819. inline void Client::set_proxy_digest_auth(const std::string &username,
  17820. const std::string &password) {
  17821. cli_->set_proxy_digest_auth(username, password);
  17822. }
  17823. inline void Client::enable_server_certificate_verification(bool enabled) {
  17824. cli_->enable_server_certificate_verification(enabled);
  17825. }
  17826. inline void Client::enable_server_hostname_verification(bool enabled) {
  17827. cli_->enable_server_hostname_verification(enabled);
  17828. }
  17829. inline void Client::enable_system_ca(bool enabled) {
  17830. cli_->enable_system_ca(enabled);
  17831. }
  17832. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  17833. inline void Client::enable_windows_certificate_verification(bool enabled) {
  17834. if (is_ssl_) {
  17835. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  17836. enabled);
  17837. }
  17838. }
  17839. #endif
  17840. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  17841. const std::string &ca_cert_dir_path) {
  17842. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  17843. }
  17844. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  17845. if (is_ssl_) {
  17846. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  17847. } else if (ca_cert_store) {
  17848. tls::free_ca_store(ca_cert_store);
  17849. }
  17850. }
  17851. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  17852. if (is_ssl_) {
  17853. // Use the PEM-based path so the CA data is retained for redirect transfer
  17854. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  17855. }
  17856. }
  17857. inline void
  17858. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  17859. if (is_ssl_) {
  17860. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  17861. std::move(verifier));
  17862. }
  17863. }
  17864. inline void Client::set_session_verifier(
  17865. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  17866. if (is_ssl_) {
  17867. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  17868. }
  17869. }
  17870. inline tls::ctx_t Client::tls_context() const {
  17871. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  17872. return nullptr;
  17873. }
  17874. #endif // CPPHTTPLIB_SSL_ENABLED
  17875. /*
  17876. * Group 7: TLS abstraction layer - Common API
  17877. */
  17878. #ifdef CPPHTTPLIB_SSL_ENABLED
  17879. namespace tls {
  17880. // Helper for PeerCert construction
  17881. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  17882. return PeerCert(get_peer_cert(session));
  17883. }
  17884. namespace impl {
  17885. // set_verify_callback() can replace a callback while handshakes on other
  17886. // threads run it, so they share it, and take their reference under this lock.
  17887. inline std::mutex &verify_callback_mutex() {
  17888. static std::mutex mutex;
  17889. return mutex;
  17890. }
  17891. // The TLS libraries are C, so an exception from a verify callback must not
  17892. // unwind through them. It rejects the certificate instead.
  17893. inline bool run_verify_callback(const VerifyCallback &callback,
  17894. const VerifyContext &ctx) {
  17895. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17896. return callback(ctx);
  17897. #else
  17898. try {
  17899. return callback(ctx);
  17900. } catch (...) { return false; }
  17901. #endif
  17902. }
  17903. // Check if a string is an IPv4 address
  17904. inline bool is_ipv4_address(const std::string &str) {
  17905. int dots = 0;
  17906. for (char c : str) {
  17907. if (c == '.') {
  17908. dots++;
  17909. } else if (!detail::is_ascii_digit(c)) {
  17910. return false;
  17911. }
  17912. }
  17913. return dots == 3;
  17914. }
  17915. // Parse IPv4 address string to bytes
  17916. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  17917. const char *p = str.c_str();
  17918. for (int i = 0; i < 4; i++) {
  17919. if (i > 0) {
  17920. if (*p != '.') { return false; }
  17921. p++;
  17922. }
  17923. int val = 0;
  17924. int digits = 0;
  17925. while (detail::is_ascii_digit(*p)) {
  17926. val = val * 10 + (*p - '0');
  17927. if (val > 255) { return false; }
  17928. p++;
  17929. digits++;
  17930. }
  17931. if (digits == 0) { return false; }
  17932. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  17933. if (digits > 1 && *(p - digits) == '0') { return false; }
  17934. out[i] = static_cast<unsigned char>(val);
  17935. }
  17936. return *p == '\0';
  17937. }
  17938. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  17939. // `out` must have room for at least 16 bytes. Returns the address length
  17940. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  17941. // literal. Used to match a host against iPAddress SANs the same way the
  17942. // OpenSSL backend does via X509_check_ip.
  17943. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  17944. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  17945. struct in6_addr addr6 = {};
  17946. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  17947. memcpy(out, &addr6, 16);
  17948. return 16;
  17949. }
  17950. return 0;
  17951. }
  17952. #ifdef _WIN32
  17953. // Enumerate Windows system certificates and call callback with DER data
  17954. template <typename Callback>
  17955. inline bool enumerate_windows_system_certs(Callback cb) {
  17956. bool loaded = false;
  17957. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  17958. for (auto store_name : store_names) {
  17959. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  17960. if (hStore) {
  17961. PCCERT_CONTEXT pContext = nullptr;
  17962. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  17963. nullptr) {
  17964. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  17965. loaded = true;
  17966. }
  17967. }
  17968. CertCloseStore(hStore, 0);
  17969. }
  17970. }
  17971. return loaded;
  17972. }
  17973. #endif
  17974. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  17975. // The trust a certificate's Trust Settings give it for SSL server
  17976. // verification (SecTrustSettings.h). An empty array trusts it as a root.
  17977. // Otherwise the first usage-constraints dictionary that applies decides: one
  17978. // naming a policy other than SSL, a host name or an application does not
  17979. // apply, and a result left out means TrustRoot. Keychain Access writes "Never
  17980. // Trust" as kSecTrustSettingsResultDeny.
  17981. inline SecTrustSettingsResult
  17982. macos_ssl_trust_settings_result(CFArrayRef trust_settings) {
  17983. auto count = CFArrayGetCount(trust_settings);
  17984. if (count == 0) { return kSecTrustSettingsResultTrustRoot; }
  17985. for (CFIndex i = 0; i < count; i++) {
  17986. auto value = CFArrayGetValueAtIndex(trust_settings, i);
  17987. if (!value || CFGetTypeID(value) != CFDictionaryGetTypeID()) { continue; }
  17988. auto constraint = static_cast<CFDictionaryRef>(value);
  17989. auto policy_value =
  17990. CFDictionaryGetValue(constraint, kSecTrustSettingsPolicy);
  17991. if (policy_value) {
  17992. auto policy = static_cast<SecPolicyRef>(const_cast<void *>(policy_value));
  17993. auto is_ssl = false;
  17994. if (auto properties = SecPolicyCopyProperties(policy)) {
  17995. auto oid = CFDictionaryGetValue(properties, kSecPolicyOid);
  17996. is_ssl = oid && CFEqual(oid, kSecPolicyAppleSSL);
  17997. CFRelease(properties);
  17998. }
  17999. if (!is_ssl) { continue; }
  18000. }
  18001. if (CFDictionaryContainsKey(constraint, kSecTrustSettingsPolicyString) ||
  18002. CFDictionaryContainsKey(constraint, kSecTrustSettingsApplication)) {
  18003. continue;
  18004. }
  18005. auto result = kSecTrustSettingsResultTrustRoot;
  18006. auto number = static_cast<CFNumberRef>(
  18007. CFDictionaryGetValue(constraint, kSecTrustSettingsResult));
  18008. if (number) {
  18009. SInt32 number_value = 0;
  18010. if (!CFNumberGetValue(number, kCFNumberSInt32Type, &number_value)) {
  18011. continue;
  18012. }
  18013. result = static_cast<SecTrustSettingsResult>(number_value);
  18014. }
  18015. if (result == kSecTrustSettingsResultTrustRoot ||
  18016. result == kSecTrustSettingsResultTrustAsRoot ||
  18017. result == kSecTrustSettingsResultDeny) {
  18018. return result;
  18019. }
  18020. }
  18021. return kSecTrustSettingsResultUnspecified;
  18022. }
  18023. // Enumerate the macOS Keychain certificates trusted for SSL and call callback
  18024. // with DER data. A certificate with Trust Settings is not trusted just by
  18025. // having them: the settings say whether it is, and a per-user setting
  18026. // overrides the admin domain's, which overrides the system domain's (whose
  18027. // roots are all trusted). So a system root the user set to "Never Trust" is
  18028. // left out, as is one trusted only for S/MIME or code signing.
  18029. template <typename Callback>
  18030. inline bool enumerate_macos_keychain_certs(Callback cb) {
  18031. const SecTrustSettingsDomain domains[] = {
  18032. kSecTrustSettingsDomainUser,
  18033. kSecTrustSettingsDomainAdmin,
  18034. kSecTrustSettingsDomainSystem,
  18035. };
  18036. std::set<std::string> decided;
  18037. std::vector<std::string> trusted;
  18038. for (auto domain : domains) {
  18039. CFArrayRef certs = nullptr;
  18040. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  18041. if (status != errSecSuccess || !certs) {
  18042. if (certs) CFRelease(certs);
  18043. continue;
  18044. }
  18045. CFIndex count = CFArrayGetCount(certs);
  18046. for (CFIndex i = 0; i < count; i++) {
  18047. SecCertificateRef cert =
  18048. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  18049. CFDataRef data = SecCertificateCopyData(cert);
  18050. if (!data) { continue; }
  18051. std::string der(reinterpret_cast<const char *>(CFDataGetBytePtr(data)),
  18052. static_cast<size_t>(CFDataGetLength(data)));
  18053. CFRelease(data);
  18054. // Decided by a domain that overrides this one
  18055. if (decided.find(der) != decided.end()) { continue; }
  18056. auto result = kSecTrustSettingsResultTrustRoot;
  18057. if (domain != kSecTrustSettingsDomainSystem) {
  18058. result = kSecTrustSettingsResultUnspecified;
  18059. CFArrayRef trust_settings = nullptr;
  18060. if (SecTrustSettingsCopyTrustSettings(cert, domain, &trust_settings) ==
  18061. errSecSuccess &&
  18062. trust_settings) {
  18063. result = macos_ssl_trust_settings_result(trust_settings);
  18064. }
  18065. if (trust_settings) CFRelease(trust_settings);
  18066. }
  18067. // Neither trusted nor distrusted here; a domain below may decide
  18068. if (result == kSecTrustSettingsResultUnspecified) { continue; }
  18069. decided.insert(der);
  18070. if (result == kSecTrustSettingsResultTrustRoot ||
  18071. result == kSecTrustSettingsResultTrustAsRoot) {
  18072. trusted.push_back(std::move(der));
  18073. }
  18074. }
  18075. CFRelease(certs);
  18076. }
  18077. bool loaded = false;
  18078. for (const auto &der : trusted) {
  18079. if (cb(reinterpret_cast<const unsigned char *>(der.data()), der.size())) {
  18080. loaded = true;
  18081. }
  18082. }
  18083. return loaded;
  18084. }
  18085. #endif
  18086. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  18087. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  18088. // Common CA certificate file paths on Linux/Unix
  18089. inline const char **system_ca_paths() {
  18090. static const char *paths[] = {
  18091. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  18092. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  18093. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  18094. "/etc/pki/tls/cacert.pem", // OpenELEC
  18095. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  18096. nullptr};
  18097. return paths;
  18098. }
  18099. // Common CA certificate directory paths on Linux/Unix
  18100. inline const char **system_ca_dirs() {
  18101. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  18102. "/etc/pki/tls/certs", // RHEL/CentOS
  18103. "/usr/share/ca-certificates", // Other
  18104. nullptr};
  18105. return dirs;
  18106. }
  18107. #endif
  18108. } // namespace impl
  18109. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  18110. const char *ca_dir) {
  18111. if (!ctx) { return false; }
  18112. bool success = true;
  18113. if (ca_file && *ca_file) {
  18114. if (!load_ca_file(ctx, ca_file)) { success = false; }
  18115. }
  18116. if (ca_dir && *ca_dir) {
  18117. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  18118. }
  18119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18120. // Set CA list for client certificate request (CertificateRequest message)
  18121. if (ca_file && *ca_file) {
  18122. auto list = SSL_load_client_CA_file(ca_file);
  18123. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  18124. }
  18125. #endif
  18126. return success;
  18127. }
  18128. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18129. const char *password) {
  18130. return set_client_cert_pem(ctx, cert, key, password);
  18131. }
  18132. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  18133. const char *key_path, const char *password) {
  18134. return set_client_cert_file(ctx, cert_path, key_path, password);
  18135. }
  18136. // PeerCert implementation
  18137. inline PeerCert::PeerCert() = default;
  18138. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  18139. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  18140. other.cert_ = nullptr;
  18141. }
  18142. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  18143. if (this != &other) {
  18144. if (cert_) { free_cert(cert_); }
  18145. cert_ = other.cert_;
  18146. other.cert_ = nullptr;
  18147. }
  18148. return *this;
  18149. }
  18150. inline PeerCert::~PeerCert() {
  18151. if (cert_) { free_cert(cert_); }
  18152. }
  18153. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  18154. inline std::string PeerCert::subject_cn() const {
  18155. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  18156. }
  18157. inline std::string PeerCert::issuer_name() const {
  18158. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  18159. }
  18160. inline bool PeerCert::check_hostname(const char *hostname) const {
  18161. return cert_ ? verify_hostname(cert_, hostname) : false;
  18162. }
  18163. inline std::vector<SanEntry> PeerCert::sans() const {
  18164. std::vector<SanEntry> result;
  18165. if (cert_) { get_cert_sans(cert_, result); }
  18166. return result;
  18167. }
  18168. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  18169. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  18170. }
  18171. inline std::string PeerCert::serial() const {
  18172. return cert_ ? get_cert_serial(cert_) : std::string();
  18173. }
  18174. // VerifyContext method implementations
  18175. inline std::string VerifyContext::subject_cn() const {
  18176. return cert ? get_cert_subject_cn(cert) : std::string();
  18177. }
  18178. inline std::string VerifyContext::issuer_name() const {
  18179. return cert ? get_cert_issuer_name(cert) : std::string();
  18180. }
  18181. inline bool VerifyContext::check_hostname(const char *hostname) const {
  18182. return cert ? verify_hostname(cert, hostname) : false;
  18183. }
  18184. inline std::vector<SanEntry> VerifyContext::sans() const {
  18185. std::vector<SanEntry> result;
  18186. if (cert) { get_cert_sans(cert, result); }
  18187. return result;
  18188. }
  18189. inline bool VerifyContext::validity(time_t &not_before,
  18190. time_t &not_after) const {
  18191. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  18192. }
  18193. inline std::string VerifyContext::serial() const {
  18194. return cert ? get_cert_serial(cert) : std::string();
  18195. }
  18196. // TlsError static method implementation
  18197. inline std::string TlsError::verify_error_to_string(long error_code) {
  18198. return verify_error_string(error_code);
  18199. }
  18200. } // namespace tls
  18201. // Request::peer_cert() implementation
  18202. inline tls::PeerCert Request::peer_cert() const {
  18203. return tls::get_peer_cert_from_session(ssl);
  18204. }
  18205. // Request::sni() implementation
  18206. inline std::string Request::sni() const {
  18207. if (!ssl) { return std::string(); }
  18208. const char *s = tls::get_sni(ssl);
  18209. return s ? std::string(s) : std::string();
  18210. }
  18211. #endif // CPPHTTPLIB_SSL_ENABLED
  18212. /*
  18213. * Group 8: TLS abstraction layer - OpenSSL backend
  18214. */
  18215. /*
  18216. * OpenSSL Backend Implementation
  18217. */
  18218. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18219. namespace tls {
  18220. namespace impl {
  18221. // Helper to map OpenSSL SSL_get_error to ErrorCode
  18222. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  18223. switch (ssl_error) {
  18224. case SSL_ERROR_NONE: return ErrorCode::Success;
  18225. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  18226. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  18227. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  18228. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  18229. case SSL_ERROR_SSL:
  18230. default: return ErrorCode::Fatal;
  18231. }
  18232. }
  18233. // Fills in a failed SSL_connect(). One that the server certificate's
  18234. // verification stopped reports the verify result, as the other backends and
  18235. // a check after the handshake do.
  18236. inline void fill_connect_error(SSL *ssl, int ret, TlsError &err) {
  18237. auto ssl_err = SSL_get_error(ssl, ret);
  18238. auto error = ERR_get_error();
  18239. err.code = map_ssl_error(ssl_err, err.sys_errno);
  18240. err.backend_code = error;
  18241. if (ssl_err != SSL_ERROR_SSL || ERR_GET_LIB(error) != ERR_LIB_SSL ||
  18242. ERR_GET_REASON(error) != SSL_R_CERTIFICATE_VERIFY_FAILED) {
  18243. return;
  18244. }
  18245. // A certificate only a verify callback turned down carries no verdict of
  18246. // its own, and fails as any other handshake does
  18247. auto verify_result = SSL_get_verify_result(ssl);
  18248. if (verify_result == X509_V_OK || verify_result == X509_V_ERR_UNSPECIFIED) {
  18249. return;
  18250. }
  18251. err.code = verify_result == X509_V_ERR_HOSTNAME_MISMATCH
  18252. ? ErrorCode::HostnameMismatch
  18253. : ErrorCode::CertVerifyFailed;
  18254. err.backend_code = static_cast<uint64_t>(verify_result);
  18255. }
  18256. // Helper: Create client CA list from PEM string
  18257. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  18258. // Caller takes ownership of returned list
  18259. inline STACK_OF(X509_NAME) *
  18260. create_client_ca_list_from_pem(const char *ca_pem) {
  18261. if (!ca_pem) { return nullptr; }
  18262. auto ca_list = sk_X509_NAME_new_null();
  18263. if (!ca_list) { return nullptr; }
  18264. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  18265. if (!bio) {
  18266. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  18267. return nullptr;
  18268. }
  18269. X509 *cert = nullptr;
  18270. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  18271. nullptr) {
  18272. const X509_NAME *name = X509_get_subject_name(cert);
  18273. if (name) {
  18274. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  18275. }
  18276. X509_free(cert);
  18277. }
  18278. BIO_free(bio);
  18279. return ca_list;
  18280. }
  18281. inline void free_verify_callback(void * /*parent*/, void *ptr,
  18282. CRYPTO_EX_DATA * /*ad*/, int /*idx*/,
  18283. long /*argl*/, void * /*argp*/) {
  18284. delete static_cast<std::shared_ptr<VerifyCallback> *>(ptr);
  18285. }
  18286. // The SSL_CTX owns its verify callback, so each client or server sees only
  18287. // its own, on whichever thread runs the handshake.
  18288. inline int verify_callback_index() {
  18289. static const auto index = SSL_CTX_get_ex_new_index(
  18290. 0, nullptr, nullptr, nullptr, free_verify_callback);
  18291. return index;
  18292. }
  18293. // OpenSSL verify callback wrapper
  18294. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  18295. // Get SSL object from X509_STORE_CTX
  18296. auto ssl = static_cast<SSL *>(
  18297. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  18298. if (!ssl) { return preverify_ok; }
  18299. std::shared_ptr<VerifyCallback> callback;
  18300. {
  18301. std::lock_guard<std::mutex> guard(verify_callback_mutex());
  18302. auto stored = static_cast<std::shared_ptr<VerifyCallback> *>(
  18303. SSL_CTX_get_ex_data(SSL_get_SSL_CTX(ssl), verify_callback_index()));
  18304. if (stored) { callback = *stored; }
  18305. }
  18306. if (!callback) { return preverify_ok; }
  18307. // Get current certificate and depth
  18308. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  18309. int depth = X509_STORE_CTX_get_error_depth(ctx);
  18310. int error = X509_STORE_CTX_get_error(ctx);
  18311. // Build context
  18312. VerifyContext verify_ctx;
  18313. verify_ctx.session = static_cast<session_t>(ssl);
  18314. verify_ctx.cert = static_cast<cert_t>(cert);
  18315. verify_ctx.depth = depth;
  18316. verify_ctx.preverify_ok = (preverify_ok != 0);
  18317. verify_ctx.error_code = error;
  18318. verify_ctx.error_string =
  18319. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  18320. auto accepted = run_verify_callback(*callback, verify_ctx);
  18321. // A client verifying the server during the handshake, which is what
  18322. // set_verify_client(ctx, true) asks for there, keeps the built-in verdict
  18323. if (!SSL_is_server(ssl) &&
  18324. (SSL_get_verify_mode(ssl) & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  18325. accepted = accepted && preverify_ok;
  18326. }
  18327. return accepted ? 1 : 0;
  18328. }
  18329. // Sets the verify mode from whether the peer's certificate is required and
  18330. // whether a verify callback is set.
  18331. inline void apply_verify_mode(SSL_CTX *ssl_ctx, bool require) {
  18332. auto has_callback =
  18333. SSL_CTX_get_ex_data(ssl_ctx, verify_callback_index()) != nullptr;
  18334. auto mode = require ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  18335. : (has_callback ? SSL_VERIFY_PEER : SSL_VERIFY_NONE);
  18336. SSL_CTX_set_verify(ssl_ctx, mode,
  18337. has_callback ? openssl_verify_callback : nullptr);
  18338. }
  18339. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  18340. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  18341. // that must be released with release_store_objects
  18342. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  18343. OPENSSL_VERSION_NUMBER >= 0x30300000L
  18344. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  18345. #endif
  18346. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  18347. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  18348. return X509_STORE_get1_objects(store);
  18349. #else
  18350. return X509_STORE_get0_objects(store);
  18351. #endif
  18352. }
  18353. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  18354. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  18355. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  18356. #else
  18357. (void)objs; // get0 variant returns an internal pointer; nothing to free
  18358. #endif
  18359. }
  18360. } // namespace impl
  18361. inline ctx_t create_client_context() {
  18362. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  18363. if (ctx) {
  18364. // Disable auto-retry to properly handle non-blocking I/O
  18365. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  18366. // Set minimum TLS version
  18367. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  18368. }
  18369. return static_cast<ctx_t>(ctx);
  18370. }
  18371. inline void free_context(ctx_t ctx) {
  18372. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  18373. }
  18374. inline bool set_min_version(ctx_t ctx, Version version) {
  18375. if (!ctx) return false;
  18376. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  18377. static_cast<uint16_t>(version)) == 1;
  18378. }
  18379. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  18380. if (!ctx || !pem || len == 0) return false;
  18381. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18382. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18383. if (!store) return false;
  18384. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  18385. if (!bio) return false;
  18386. bool ok = true;
  18387. X509 *cert = nullptr;
  18388. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  18389. nullptr) {
  18390. if (X509_STORE_add_cert(store, cert) != 1) {
  18391. // Ignore duplicate errors
  18392. auto err = ERR_peek_last_error();
  18393. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  18394. ok = false;
  18395. }
  18396. }
  18397. X509_free(cert);
  18398. if (!ok) break;
  18399. }
  18400. BIO_free(bio);
  18401. // Clear any "no more certificates" errors
  18402. ERR_clear_error();
  18403. return ok;
  18404. }
  18405. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  18406. if (!ctx || !file_path) return false;
  18407. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  18408. nullptr) == 1;
  18409. }
  18410. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  18411. if (!ctx || !dir_path) return false;
  18412. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  18413. dir_path) == 1;
  18414. }
  18415. inline bool load_system_certs(ctx_t ctx) {
  18416. if (!ctx) return false;
  18417. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18418. #ifdef _WIN32
  18419. // Windows: Load from system certificate store (ROOT and CA)
  18420. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18421. if (!store) return false;
  18422. bool loaded_any = false;
  18423. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  18424. for (auto store_name : store_names) {
  18425. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  18426. if (!hStore) continue;
  18427. PCCERT_CONTEXT pContext = nullptr;
  18428. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  18429. nullptr) {
  18430. const unsigned char *data = pContext->pbCertEncoded;
  18431. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  18432. if (x509) {
  18433. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  18434. X509_free(x509);
  18435. }
  18436. }
  18437. CertCloseStore(hStore, 0);
  18438. }
  18439. return loaded_any;
  18440. #elif defined(__APPLE__)
  18441. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  18442. // macOS: Load from Keychain
  18443. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18444. if (!store) return false;
  18445. auto loaded_any = impl::enumerate_macos_keychain_certs(
  18446. [&](const unsigned char *data, size_t len) {
  18447. auto x509 = d2i_X509(nullptr, &data, static_cast<long>(len));
  18448. if (!x509) { return false; }
  18449. auto added = X509_STORE_add_cert(store, x509) == 1;
  18450. X509_free(x509);
  18451. return added;
  18452. });
  18453. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  18454. #else
  18455. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  18456. #endif
  18457. #else
  18458. // Other Unix: use default verify paths
  18459. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  18460. #endif
  18461. }
  18462. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18463. const char *password) {
  18464. if (!ctx || !cert || !key) return false;
  18465. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18466. // Load certificate
  18467. auto cert_bio = BIO_new_mem_buf(cert, -1);
  18468. if (!cert_bio) return false;
  18469. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  18470. BIO_free(cert_bio);
  18471. if (!x509) return false;
  18472. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  18473. X509_free(x509);
  18474. if (!cert_ok) return false;
  18475. // Load private key
  18476. auto key_bio = BIO_new_mem_buf(key, -1);
  18477. if (!key_bio) return false;
  18478. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  18479. password ? const_cast<char *>(password)
  18480. : nullptr);
  18481. BIO_free(key_bio);
  18482. if (!pkey) return false;
  18483. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  18484. EVP_PKEY_free(pkey);
  18485. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  18486. }
  18487. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  18488. const char *key_path, const char *password) {
  18489. if (!ctx || !cert_path || !key_path) return false;
  18490. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18491. if (password && password[0] != '\0') {
  18492. SSL_CTX_set_default_passwd_cb_userdata(
  18493. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  18494. }
  18495. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  18496. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  18497. }
  18498. inline ctx_t create_server_context() {
  18499. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18500. if (ctx) {
  18501. // No renegotiation, as on the other backends: it would run a handshake
  18502. // that SSLServer::update_certs_pem() does not wait for
  18503. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  18504. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
  18505. SSL_OP_NO_RENEGOTIATION);
  18506. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  18507. // Without one, a client resuming its session is sent a fatal alert once
  18508. // client certificates are verified.
  18509. static const unsigned char sid_ctx[] = "cpp-httplib";
  18510. SSL_CTX_set_session_id_context(ctx, sid_ctx, sizeof(sid_ctx) - 1);
  18511. }
  18512. return static_cast<ctx_t>(ctx);
  18513. }
  18514. inline void set_verify_client(ctx_t ctx, bool require) {
  18515. if (!ctx) return;
  18516. impl::apply_verify_mode(static_cast<SSL_CTX *>(ctx), require);
  18517. }
  18518. inline session_t create_session(ctx_t ctx, socket_t sock) {
  18519. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  18520. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18521. SSL *ssl = SSL_new(ssl_ctx);
  18522. if (!ssl) return nullptr;
  18523. // Disable auto-retry for proper non-blocking I/O handling
  18524. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  18525. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  18526. if (!bio) {
  18527. SSL_free(ssl);
  18528. return nullptr;
  18529. }
  18530. SSL_set_bio(ssl, bio, bio);
  18531. return static_cast<session_t>(ssl);
  18532. }
  18533. inline void free_session(session_t session) {
  18534. if (session) { SSL_free(static_cast<SSL *>(session)); }
  18535. }
  18536. inline bool set_sni(session_t session, const char *hostname,
  18537. bool verify_hostname) {
  18538. if (!session || !hostname) return false;
  18539. auto ssl = static_cast<SSL *>(session);
  18540. // The handshake's chain verification then checks the name as well
  18541. if (verify_hostname) {
  18542. auto param = SSL_get0_param(ssl);
  18543. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
  18544. if (X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname)) != 1) {
  18545. return false;
  18546. }
  18547. }
  18548. #if defined(OPENSSL_IS_BORINGSSL)
  18549. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  18550. #else
  18551. // Direct call instead of macro to suppress -Wold-style-cast warning
  18552. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  18553. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  18554. #endif
  18555. }
  18556. inline TlsError connect(session_t session) {
  18557. if (!session) { return TlsError(); }
  18558. auto ssl = static_cast<SSL *>(session);
  18559. auto ret = SSL_connect(ssl);
  18560. TlsError err;
  18561. if (ret == 1) {
  18562. err.code = ErrorCode::Success;
  18563. } else {
  18564. impl::fill_connect_error(ssl, ret, err);
  18565. }
  18566. return err;
  18567. }
  18568. inline TlsError accept(session_t session) {
  18569. if (!session) { return TlsError(); }
  18570. auto ssl = static_cast<SSL *>(session);
  18571. auto ret = SSL_accept(ssl);
  18572. TlsError err;
  18573. if (ret == 1) {
  18574. err.code = ErrorCode::Success;
  18575. } else {
  18576. auto ssl_err = SSL_get_error(ssl, ret);
  18577. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  18578. err.backend_code = ERR_get_error();
  18579. }
  18580. return err;
  18581. }
  18582. inline bool connect_nonblocking(session_t session, socket_t sock,
  18583. time_t timeout_sec, time_t timeout_usec,
  18584. TlsError *err,
  18585. const std::function<bool()> &interrupted) {
  18586. if (!session) {
  18587. if (err) { err->code = ErrorCode::Fatal; }
  18588. return false;
  18589. }
  18590. auto ssl = static_cast<SSL *>(session);
  18591. auto bio = SSL_get_rbio(ssl);
  18592. // Set non-blocking mode for handshake
  18593. detail::set_nonblocking(sock, true);
  18594. if (bio) { BIO_set_nbio(bio, 1); }
  18595. auto cleanup = detail::scope_exit([&]() {
  18596. // Restore blocking mode after handshake
  18597. if (bio) { BIO_set_nbio(bio, 0); }
  18598. detail::set_nonblocking(sock, false);
  18599. });
  18600. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  18601. auto res = 0;
  18602. while ((res = SSL_connect(ssl)) != 1) {
  18603. auto ssl_err = SSL_get_error(ssl, res);
  18604. switch (ssl_err) {
  18605. case SSL_ERROR_WANT_READ:
  18606. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  18607. continue;
  18608. }
  18609. break;
  18610. case SSL_ERROR_WANT_WRITE:
  18611. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  18612. continue;
  18613. }
  18614. break;
  18615. default: break;
  18616. }
  18617. if (err) { impl::fill_connect_error(ssl, res, *err); }
  18618. return false;
  18619. }
  18620. if (err) { err->code = ErrorCode::Success; }
  18621. return true;
  18622. }
  18623. inline bool accept_nonblocking(session_t session, socket_t sock,
  18624. time_t timeout_sec, time_t timeout_usec,
  18625. TlsError *err,
  18626. const std::function<bool()> &interrupted) {
  18627. if (!session) {
  18628. if (err) { err->code = ErrorCode::Fatal; }
  18629. return false;
  18630. }
  18631. auto ssl = static_cast<SSL *>(session);
  18632. auto bio = SSL_get_rbio(ssl);
  18633. // Set non-blocking mode for handshake
  18634. detail::set_nonblocking(sock, true);
  18635. if (bio) { BIO_set_nbio(bio, 1); }
  18636. auto cleanup = detail::scope_exit([&]() {
  18637. // Restore blocking mode after handshake
  18638. if (bio) { BIO_set_nbio(bio, 0); }
  18639. detail::set_nonblocking(sock, false);
  18640. });
  18641. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  18642. auto res = 0;
  18643. while ((res = SSL_accept(ssl)) != 1) {
  18644. auto ssl_err = SSL_get_error(ssl, res);
  18645. switch (ssl_err) {
  18646. case SSL_ERROR_WANT_READ:
  18647. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  18648. continue;
  18649. }
  18650. break;
  18651. case SSL_ERROR_WANT_WRITE:
  18652. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  18653. continue;
  18654. }
  18655. break;
  18656. default: break;
  18657. }
  18658. if (err) {
  18659. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  18660. err->backend_code = ERR_get_error();
  18661. }
  18662. return false;
  18663. }
  18664. if (err) { err->code = ErrorCode::Success; }
  18665. return true;
  18666. }
  18667. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  18668. if (!session || !buf) {
  18669. err.code = ErrorCode::Fatal;
  18670. return -1;
  18671. }
  18672. auto ssl = static_cast<SSL *>(session);
  18673. constexpr auto max_len =
  18674. static_cast<size_t>((std::numeric_limits<int>::max)());
  18675. if (len > max_len) { len = max_len; }
  18676. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  18677. if (ret > 0) {
  18678. err.code = ErrorCode::Success;
  18679. return ret;
  18680. }
  18681. auto ssl_err = SSL_get_error(ssl, ret);
  18682. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  18683. if (err.code == ErrorCode::PeerClosed) {
  18684. return 0;
  18685. } // Gracefully handle the peer closed state.
  18686. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  18687. return -1;
  18688. }
  18689. inline ssize_t write(session_t session, const void *buf, size_t len,
  18690. TlsError &err) {
  18691. if (!session || !buf) {
  18692. err.code = ErrorCode::Fatal;
  18693. return -1;
  18694. }
  18695. auto ssl = static_cast<SSL *>(session);
  18696. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  18697. if (ret > 0) {
  18698. err.code = ErrorCode::Success;
  18699. return ret;
  18700. }
  18701. auto ssl_err = SSL_get_error(ssl, ret);
  18702. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  18703. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  18704. return -1;
  18705. }
  18706. inline int pending(const_session_t session) {
  18707. if (!session) return 0;
  18708. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  18709. }
  18710. inline void shutdown(session_t session, bool graceful) {
  18711. if (!session) return;
  18712. auto ssl = static_cast<SSL *>(session);
  18713. if (graceful) {
  18714. // Send close_notify without waiting for the peer's. The connection is
  18715. // closed right after this, so a unidirectional shutdown is enough, and an
  18716. // idle peer that never answers would otherwise hold this thread until the
  18717. // read timeout. The other backends do not wait either.
  18718. SSL_shutdown(ssl);
  18719. }
  18720. }
  18721. inline bool is_peer_closed(session_t session, socket_t sock) {
  18722. if (!session) return true;
  18723. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  18724. detail::set_nonblocking(sock, true);
  18725. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18726. auto ssl = static_cast<SSL *>(session);
  18727. char buf;
  18728. auto ret = SSL_peek(ssl, &buf, 1);
  18729. if (ret > 0) return false;
  18730. auto err = SSL_get_error(ssl, ret);
  18731. return err == SSL_ERROR_ZERO_RETURN;
  18732. }
  18733. inline cert_t get_peer_cert(const_session_t session) {
  18734. if (!session) return nullptr;
  18735. return static_cast<cert_t>(SSL_get1_peer_certificate(
  18736. static_cast<SSL *>(const_cast<void *>(session))));
  18737. }
  18738. inline size_t get_peer_certs(const_session_t session,
  18739. std::vector<cert_t> &certs) {
  18740. certs.clear();
  18741. if (!session) { return 0; }
  18742. auto ssl = static_cast<const SSL *>(session);
  18743. // On the server side, the chain leaves out the peer's own certificate
  18744. if (SSL_is_server(ssl)) {
  18745. if (auto leaf = get_peer_cert(session)) { certs.push_back(leaf); }
  18746. }
  18747. if (auto sk = SSL_get_peer_cert_chain(ssl)) {
  18748. auto count = sk_X509_num(sk);
  18749. for (decltype(count) i = 0; i < count; i++) {
  18750. auto x509 = sk_X509_value(sk, i);
  18751. X509_up_ref(x509);
  18752. certs.push_back(static_cast<cert_t>(x509));
  18753. }
  18754. }
  18755. return certs.size();
  18756. }
  18757. inline void free_cert(cert_t cert) {
  18758. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  18759. }
  18760. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18761. if (!cert || !hostname) return false;
  18762. auto x509 = static_cast<X509 *>(cert);
  18763. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  18764. if (detail::is_ip_address(hostname)) {
  18765. return X509_check_ip_asc(x509, hostname, 0) == 1;
  18766. }
  18767. return X509_check_host(x509, hostname, strlen(hostname),
  18768. X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, nullptr) == 1;
  18769. }
  18770. inline uint64_t hostname_mismatch_code() {
  18771. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  18772. }
  18773. inline long get_verify_result(const_session_t session) {
  18774. if (!session) return X509_V_ERR_UNSPECIFIED;
  18775. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  18776. }
  18777. inline std::string get_cert_subject_cn(cert_t cert) {
  18778. if (!cert) return "";
  18779. auto x509 = static_cast<X509 *>(cert);
  18780. auto subject_name = X509_get_subject_name(x509);
  18781. if (!subject_name) return "";
  18782. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  18783. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  18784. if (idx < 0) return "";
  18785. auto entry = X509_NAME_get_entry(subject_name, idx);
  18786. if (!entry) return "";
  18787. auto data = X509_NAME_ENTRY_get_data(entry);
  18788. if (!data) return "";
  18789. return std::string(
  18790. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  18791. static_cast<size_t>(ASN1_STRING_length(data)));
  18792. }
  18793. inline std::string get_cert_issuer_name(cert_t cert) {
  18794. if (!cert) return "";
  18795. auto x509 = static_cast<X509 *>(cert);
  18796. auto issuer_name = X509_get_issuer_name(x509);
  18797. if (!issuer_name) return "";
  18798. char buf[256];
  18799. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  18800. return std::string(buf);
  18801. }
  18802. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  18803. sans.clear();
  18804. if (!cert) return false;
  18805. auto x509 = static_cast<X509 *>(cert);
  18806. auto names = static_cast<GENERAL_NAMES *>(
  18807. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18808. if (!names) return true; // No SANs is valid
  18809. auto count = sk_GENERAL_NAME_num(names);
  18810. for (decltype(count) i = 0; i < count; i++) {
  18811. auto gen = sk_GENERAL_NAME_value(names, i);
  18812. if (!gen) continue;
  18813. SanEntry entry;
  18814. switch (gen->type) {
  18815. case GEN_DNS:
  18816. entry.type = SanType::DNS;
  18817. if (gen->d.dNSName) {
  18818. entry.value = std::string(
  18819. reinterpret_cast<const char *>(
  18820. ASN1_STRING_get0_data(gen->d.dNSName)),
  18821. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  18822. }
  18823. break;
  18824. case GEN_IPADD:
  18825. entry.type = SanType::IP;
  18826. if (gen->d.iPAddress) {
  18827. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  18828. auto len = ASN1_STRING_length(gen->d.iPAddress);
  18829. if (len == 4) {
  18830. // IPv4
  18831. char buf[INET_ADDRSTRLEN];
  18832. inet_ntop(AF_INET, data, buf, sizeof(buf));
  18833. entry.value = buf;
  18834. } else if (len == 16) {
  18835. // IPv6
  18836. char buf[INET6_ADDRSTRLEN];
  18837. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  18838. entry.value = buf;
  18839. }
  18840. }
  18841. break;
  18842. case GEN_EMAIL:
  18843. entry.type = SanType::EMAIL;
  18844. if (gen->d.rfc822Name) {
  18845. entry.value = std::string(
  18846. reinterpret_cast<const char *>(
  18847. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  18848. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  18849. }
  18850. break;
  18851. case GEN_URI:
  18852. entry.type = SanType::URI;
  18853. if (gen->d.uniformResourceIdentifier) {
  18854. entry.value = std::string(
  18855. reinterpret_cast<const char *>(
  18856. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  18857. static_cast<size_t>(
  18858. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  18859. }
  18860. break;
  18861. default: entry.type = SanType::OTHER; break;
  18862. }
  18863. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  18864. }
  18865. GENERAL_NAMES_free(names);
  18866. return true;
  18867. }
  18868. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  18869. time_t &not_after) {
  18870. if (!cert) return false;
  18871. auto x509 = static_cast<X509 *>(cert);
  18872. auto nb = X509_get0_notBefore(x509);
  18873. auto na = X509_get0_notAfter(x509);
  18874. if (!nb || !na) return false;
  18875. ASN1_TIME *epoch = ASN1_TIME_new();
  18876. if (!epoch) return false;
  18877. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  18878. if (!ASN1_TIME_set(epoch, 0)) return false;
  18879. int pday, psec;
  18880. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  18881. not_before = 86400 * (time_t)pday + psec;
  18882. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  18883. not_after = 86400 * (time_t)pday + psec;
  18884. return true;
  18885. }
  18886. inline std::string get_cert_serial(cert_t cert) {
  18887. if (!cert) return "";
  18888. auto x509 = static_cast<X509 *>(cert);
  18889. auto serial = X509_get_serialNumber(x509);
  18890. if (!serial) return "";
  18891. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  18892. if (!bn) return "";
  18893. auto hex = BN_bn2hex(bn);
  18894. BN_free(bn);
  18895. if (!hex) return "";
  18896. std::string result(hex);
  18897. OPENSSL_free(hex);
  18898. return result;
  18899. }
  18900. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  18901. if (!cert) return false;
  18902. auto x509 = static_cast<X509 *>(cert);
  18903. auto len = i2d_X509(x509, nullptr);
  18904. if (len < 0) return false;
  18905. der.resize(static_cast<size_t>(len));
  18906. auto p = der.data();
  18907. i2d_X509(x509, &p);
  18908. return true;
  18909. }
  18910. inline const char *get_sni(const_session_t session) {
  18911. if (!session) return nullptr;
  18912. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  18913. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  18914. }
  18915. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  18916. inline uint64_t get_error() { return ERR_get_error(); }
  18917. inline std::string error_string(uint64_t code) {
  18918. char buf[256];
  18919. ERR_error_string_n(static_cast<decltype(ERR_get_error())>(code), buf,
  18920. sizeof(buf));
  18921. return std::string(buf);
  18922. }
  18923. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  18924. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  18925. if (!mem) { return nullptr; }
  18926. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  18927. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  18928. if (!inf) { return nullptr; }
  18929. auto store = X509_STORE_new();
  18930. if (store) {
  18931. auto count = sk_X509_INFO_num(inf);
  18932. for (decltype(count) i = 0; i < count; i++) {
  18933. auto itmp = sk_X509_INFO_value(inf, i);
  18934. if (!itmp) { continue; }
  18935. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  18936. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  18937. }
  18938. }
  18939. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  18940. return static_cast<ca_store_t>(store);
  18941. }
  18942. inline void free_ca_store(ca_store_t store) {
  18943. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  18944. }
  18945. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18946. if (!ctx || !store) { return false; }
  18947. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18948. auto x509_store = static_cast<X509_STORE *>(store);
  18949. // Check if same store is already set
  18950. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  18951. // SSL_CTX_set_cert_store takes ownership and frees the old store
  18952. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  18953. return true;
  18954. }
  18955. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  18956. certs.clear();
  18957. if (!ctx) { return 0; }
  18958. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18959. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18960. if (!store) { return 0; }
  18961. auto objs = impl::get_store_objects(store);
  18962. if (!objs) { return 0; }
  18963. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  18964. auto count = sk_X509_OBJECT_num(objs);
  18965. for (decltype(count) i = 0; i < count; i++) {
  18966. auto obj = sk_X509_OBJECT_value(objs, i);
  18967. if (!obj) { continue; }
  18968. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  18969. auto x509 = X509_OBJECT_get0_X509(obj);
  18970. if (x509) {
  18971. // Increment reference count so caller can free it
  18972. X509_up_ref(x509);
  18973. certs.push_back(static_cast<cert_t>(x509));
  18974. }
  18975. }
  18976. }
  18977. return certs.size();
  18978. }
  18979. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  18980. std::vector<std::string> names;
  18981. if (!ctx) { return names; }
  18982. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18983. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18984. if (!store) { return names; }
  18985. auto objs = impl::get_store_objects(store);
  18986. if (!objs) { return names; }
  18987. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  18988. auto count = sk_X509_OBJECT_num(objs);
  18989. for (decltype(count) i = 0; i < count; i++) {
  18990. auto obj = sk_X509_OBJECT_value(objs, i);
  18991. if (!obj) { continue; }
  18992. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  18993. auto x509 = X509_OBJECT_get0_X509(obj);
  18994. if (x509) {
  18995. auto subject = X509_get_subject_name(x509);
  18996. if (subject) {
  18997. char buf[512];
  18998. X509_NAME_oneline(subject, buf, sizeof(buf));
  18999. names.push_back(buf);
  19000. }
  19001. }
  19002. }
  19003. }
  19004. return names;
  19005. }
  19006. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  19007. const char *key_pem, const char *password) {
  19008. if (!ctx || !cert_pem || !key_pem) { return false; }
  19009. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  19010. // Load certificate from PEM
  19011. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  19012. if (!cert_bio) { return false; }
  19013. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  19014. BIO_free(cert_bio);
  19015. if (!cert) { return false; }
  19016. // Load private key from PEM
  19017. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  19018. if (!key_bio) {
  19019. X509_free(cert);
  19020. return false;
  19021. }
  19022. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  19023. password ? const_cast<char *>(password)
  19024. : nullptr);
  19025. BIO_free(key_bio);
  19026. if (!key) {
  19027. X509_free(cert);
  19028. return false;
  19029. }
  19030. // Update certificate and key
  19031. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  19032. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  19033. X509_free(cert);
  19034. EVP_PKEY_free(key);
  19035. return ret;
  19036. }
  19037. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  19038. if (!ctx || !ca_pem) { return false; }
  19039. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  19040. // Create new X509_STORE from PEM
  19041. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  19042. if (!store) { return false; }
  19043. // A resumed session is not verified again, so the ticket keys from before
  19044. // go, or a client verified under the old CAs could go on resuming.
  19045. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  19046. unsigned char ticket_keys[48];
  19047. #else
  19048. unsigned char ticket_keys[80];
  19049. #endif
  19050. if (RAND_bytes(ticket_keys, sizeof(ticket_keys)) != 1 ||
  19051. SSL_CTX_set_tlsext_ticket_keys(ssl_ctx, ticket_keys,
  19052. sizeof(ticket_keys)) != 1) {
  19053. free_ca_store(store);
  19054. return false;
  19055. }
  19056. // SSL_CTX_set_cert_store takes ownership
  19057. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  19058. // Set client CA list for client certificate request
  19059. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  19060. if (ca_list) {
  19061. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  19062. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  19063. }
  19064. // The cached sessions go for the same reason.
  19065. #if OPENSSL_VERSION_NUMBER >= 0x30400000L
  19066. SSL_CTX_flush_sessions_ex(ssl_ctx, (std::numeric_limits<time_t>::max)());
  19067. #else
  19068. SSL_CTX_flush_sessions(ssl_ctx, (std::numeric_limits<long>::max)());
  19069. #endif
  19070. return true;
  19071. }
  19072. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  19073. if (!ctx) { return false; }
  19074. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  19075. auto index = impl::verify_callback_index();
  19076. if (index < 0) { return false; }
  19077. std::shared_ptr<VerifyCallback> *stored = nullptr;
  19078. if (callback) {
  19079. stored = new std::shared_ptr<VerifyCallback>(
  19080. std::make_shared<VerifyCallback>(std::move(callback)));
  19081. }
  19082. std::shared_ptr<VerifyCallback> *previous = nullptr;
  19083. {
  19084. std::lock_guard<std::mutex> guard(impl::verify_callback_mutex());
  19085. previous = static_cast<std::shared_ptr<VerifyCallback> *>(
  19086. SSL_CTX_get_ex_data(ssl_ctx, index));
  19087. if (SSL_CTX_set_ex_data(ssl_ctx, index, stored) != 1) {
  19088. delete stored;
  19089. return false;
  19090. }
  19091. }
  19092. // A handshake running the previous callback keeps it until it returns.
  19093. delete previous;
  19094. // A resumed handshake shows no certificate to run the callback on.
  19095. if (stored) {
  19096. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
  19097. SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
  19098. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER)
  19099. // TLS 1.3 tickets, which SSL_OP_NO_TICKET leaves on
  19100. SSL_CTX_set_num_tickets(ssl_ctx, 0);
  19101. #endif
  19102. }
  19103. // Keep requiring the peer's certificate if set_verify_client() asked for it
  19104. auto require =
  19105. (SSL_CTX_get_verify_mode(ssl_ctx) & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0;
  19106. impl::apply_verify_mode(ssl_ctx, require);
  19107. return true;
  19108. }
  19109. inline long get_verify_error(const_session_t session) {
  19110. if (!session) { return -1; }
  19111. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  19112. return SSL_get_verify_result(ssl);
  19113. }
  19114. inline std::string verify_error_string(long error_code) {
  19115. if (error_code == X509_V_OK) { return ""; }
  19116. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  19117. return str ? str : "unknown error";
  19118. }
  19119. } // namespace tls
  19120. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  19121. /*
  19122. * Group 9: TLS abstraction layer - Mbed TLS backend
  19123. */
  19124. /*
  19125. * Mbed TLS Backend Implementation
  19126. */
  19127. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19128. namespace tls {
  19129. namespace impl {
  19130. // Mbed TLS session wrapper
  19131. struct MbedTlsSession {
  19132. mbedtls_ssl_context ssl;
  19133. socket_t sock = INVALID_SOCKET;
  19134. std::string hostname; // For client: set via set_sni
  19135. std::string sni_hostname; // For server: received from client via SNI callback
  19136. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  19137. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  19138. // (e.g. a response that arrived while this side was still in its post-write
  19139. // check), the byte is pushed back here and served by the next read().
  19140. unsigned char peeked_byte = 0;
  19141. bool has_peeked_byte = false;
  19142. // Set by set_sni() when the caller disabled hostname verification, so the
  19143. // verify callback can clear the CN/SAN mismatch flag while still enforcing
  19144. // the rest of the chain (Mbed TLS ties SNI and identity checking together;
  19145. // OpenSSL and wolfSSL keep them independent).
  19146. bool suppress_hostname_mismatch = false;
  19147. // Copied from the owning MbedTlsContext at creation, so a handshake only
  19148. // ever runs the callback of its own context.
  19149. VerifyCallback verify_callback;
  19150. bool is_server = false;
  19151. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  19152. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  19153. MbedTlsSession(const MbedTlsSession &) = delete;
  19154. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  19155. };
  19156. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  19157. // queue)
  19158. inline int &mbedtls_last_error() {
  19159. static thread_local int err = 0;
  19160. return err;
  19161. }
  19162. // Helper to map Mbed TLS error to ErrorCode
  19163. inline ErrorCode map_mbedtls_error(int ret, int &out_errno,
  19164. uint32_t verify_flags) {
  19165. if (ret == 0) { return ErrorCode::Success; }
  19166. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  19167. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  19168. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  19169. return ErrorCode::PeerClosed;
  19170. }
  19171. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  19172. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  19173. out_errno = errno;
  19174. return ErrorCode::SyscallError;
  19175. }
  19176. if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
  19177. // EOF without close_notify
  19178. out_errno = 0;
  19179. return ErrorCode::SyscallError;
  19180. }
  19181. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  19182. // Unlike OpenSSL/wolfSSL, Mbed TLS folds the CN/SAN identity check into
  19183. // the handshake's chain verification (see set_sni()); a mismatch there
  19184. // is reported the same way as any other verify_flags bit. Report it as
  19185. // HostnameMismatch, matching the other backends and the post-handshake
  19186. // identity check below, but only when naming is the sole problem -
  19187. // if the chain itself is also untrusted/expired/etc., that takes
  19188. // priority over the naming detail.
  19189. if (verify_flags == static_cast<uint32_t>(hostname_mismatch_code())) {
  19190. return ErrorCode::HostnameMismatch;
  19191. }
  19192. return ErrorCode::CertVerifyFailed;
  19193. }
  19194. return ErrorCode::Fatal;
  19195. }
  19196. // Populates a TlsError from a failed (non-zero) mbedtls_ssl_handshake()
  19197. // return value, including the verify-flags-dependent HostnameMismatch
  19198. // mapping; shared by connect() and connect_nonblocking() so the
  19199. // backend_code policy for that mapping only lives in one place.
  19200. inline void fill_mbedtls_tls_error(TlsError &err, mbedtls_ssl_context &ssl,
  19201. int ret) {
  19202. auto verify_flags = mbedtls_ssl_get_verify_result(&ssl);
  19203. err.code = map_mbedtls_error(ret, err.sys_errno, verify_flags);
  19204. err.backend_code = err.code == ErrorCode::HostnameMismatch
  19205. ? static_cast<uint64_t>(verify_flags)
  19206. : static_cast<uint64_t>(-ret);
  19207. }
  19208. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  19209. // non-fatal notification delivered between records, not an error and not
  19210. // application data, so I/O calls that see it should just be retried. Kept in
  19211. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  19212. // splitting the closing brace across an #if.
  19213. inline bool mbedtls_is_session_ticket(int ret) {
  19214. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  19215. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  19216. #else
  19217. (void)ret;
  19218. return false;
  19219. #endif
  19220. }
  19221. // BIO-like send callback for Mbed TLS
  19222. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  19223. size_t len) {
  19224. auto sock = *static_cast<socket_t *>(ctx);
  19225. #ifdef _WIN32
  19226. auto ret =
  19227. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  19228. if (ret == SOCKET_ERROR) {
  19229. int err = WSAGetLastError();
  19230. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  19231. return MBEDTLS_ERR_NET_SEND_FAILED;
  19232. }
  19233. #else
  19234. auto ret = send(sock, buf, len, 0);
  19235. if (ret < 0) {
  19236. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  19237. return MBEDTLS_ERR_SSL_WANT_WRITE;
  19238. }
  19239. return MBEDTLS_ERR_NET_SEND_FAILED;
  19240. }
  19241. #endif
  19242. return static_cast<int>(ret);
  19243. }
  19244. // BIO-like recv callback for Mbed TLS
  19245. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  19246. auto sock = *static_cast<socket_t *>(ctx);
  19247. #ifdef _WIN32
  19248. auto ret =
  19249. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  19250. if (ret == SOCKET_ERROR) {
  19251. int err = WSAGetLastError();
  19252. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  19253. return MBEDTLS_ERR_NET_RECV_FAILED;
  19254. }
  19255. #else
  19256. auto ret = recv(sock, buf, len, 0);
  19257. if (ret < 0) {
  19258. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  19259. return MBEDTLS_ERR_SSL_WANT_READ;
  19260. }
  19261. return MBEDTLS_ERR_NET_RECV_FAILED;
  19262. }
  19263. #endif
  19264. // EOF is MBEDTLS_ERR_SSL_CONN_EOF; only a close_notify is a clean end
  19265. return static_cast<int>(ret);
  19266. }
  19267. // MbedTlsContext constructor/destructor implementations
  19268. inline MbedTlsContext::MbedTlsContext() {
  19269. mbedtls_ssl_config_init(&conf);
  19270. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19271. mbedtls_entropy_init(&entropy);
  19272. mbedtls_ctr_drbg_init(&ctr_drbg);
  19273. #endif
  19274. mbedtls_x509_crt_init(&ca_chain);
  19275. mbedtls_x509_crt_init(&own_cert);
  19276. mbedtls_pk_init(&own_key);
  19277. }
  19278. inline MbedTlsContext::~MbedTlsContext() {
  19279. mbedtls_pk_free(&own_key);
  19280. mbedtls_x509_crt_free(&own_cert);
  19281. mbedtls_x509_crt_free(&ca_chain);
  19282. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19283. mbedtls_ctr_drbg_free(&ctr_drbg);
  19284. mbedtls_entropy_free(&entropy);
  19285. #endif
  19286. mbedtls_ssl_config_free(&conf);
  19287. }
  19288. // Thread-local storage for SNI captured during handshake
  19289. // This is needed because the SNI callback doesn't have a way to pass
  19290. // session-specific data before the session is fully set up
  19291. inline std::string &mbedpending_sni() {
  19292. static thread_local std::string sni;
  19293. return sni;
  19294. }
  19295. // SNI callback for Mbed TLS server to capture client's SNI hostname
  19296. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  19297. const unsigned char *name, size_t name_len) {
  19298. (void)p_ctx;
  19299. (void)ssl;
  19300. // Store SNI name in thread-local storage
  19301. // It will be retrieved and stored in the session after handshake
  19302. if (name && name_len > 0) {
  19303. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  19304. } else {
  19305. mbedpending_sni().clear();
  19306. }
  19307. return 0; // Accept any SNI
  19308. }
  19309. inline void mbedtls_clear_cn_mismatch(uint32_t *flags) {
  19310. *flags &= ~static_cast<uint32_t>(hostname_mismatch_code());
  19311. }
  19312. // MbedTLS verify callback wrapper
  19313. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  19314. int cert_depth, uint32_t *flags) {
  19315. // data points to the MbedTlsSession
  19316. auto *session = static_cast<MbedTlsSession *>(data);
  19317. // set_sni() disabled hostname verification for this session: ignore the
  19318. // CN/SAN mismatch flag, as the OpenSSL/wolfSSL backends do. The final
  19319. // pass/fail decision still comes from the remaining flags (and, below, from
  19320. // the user's own verify callback).
  19321. if (session->suppress_hostname_mismatch) { mbedtls_clear_cn_mismatch(flags); }
  19322. const auto &callback = session->verify_callback;
  19323. if (!callback) { return 0; } // Continue with default verification
  19324. // Build context
  19325. VerifyContext verify_ctx;
  19326. verify_ctx.session = static_cast<session_t>(session);
  19327. verify_ctx.cert = static_cast<cert_t>(crt);
  19328. verify_ctx.depth = cert_depth;
  19329. verify_ctx.preverify_ok = (*flags == 0);
  19330. verify_ctx.error_code = static_cast<long>(*flags);
  19331. // Convert Mbed TLS flags to error string
  19332. static thread_local char error_buf[256];
  19333. if (*flags != 0) {
  19334. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  19335. verify_ctx.error_string = error_buf;
  19336. } else {
  19337. verify_ctx.error_string = nullptr;
  19338. }
  19339. bool accepted = run_verify_callback(callback, verify_ctx);
  19340. if (accepted) {
  19341. // Overrides the built-in verification only on a server, as on OpenSSL and
  19342. // wolfSSL, whose clients check the verify result after the handshake
  19343. if (session->is_server) { *flags = 0; }
  19344. return 0;
  19345. }
  19346. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  19347. }
  19348. // Sets the authentication mode from whether the peer's certificate is required
  19349. // and whether a verify callback is set. OPTIONAL lets the callback run even if
  19350. // verification is not required (matching OpenSSL's SSL_VERIFY_PEER).
  19351. inline void apply_verify_mode(MbedTlsContext &mctx) {
  19352. auto mode = MBEDTLS_SSL_VERIFY_NONE;
  19353. if (mctx.verify_client) {
  19354. mode = MBEDTLS_SSL_VERIFY_REQUIRED;
  19355. } else if (mctx.verify_callback) {
  19356. mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
  19357. }
  19358. mbedtls_ssl_conf_authmode(&mctx.conf, mode);
  19359. }
  19360. } // namespace impl
  19361. inline ctx_t create_client_context() {
  19362. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  19363. if (!ctx) { return nullptr; }
  19364. ctx->is_server = false;
  19365. #ifdef CPPHTTPLIB_MBEDTLS_V4
  19366. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  19367. if (!detail::ensure_mbedtls_psa_crypto()) {
  19368. delete ctx;
  19369. return nullptr;
  19370. }
  19371. int ret;
  19372. #else
  19373. // Seed the random number generator
  19374. const char *pers = "httplib_client";
  19375. int ret = mbedtls_ctr_drbg_seed(
  19376. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  19377. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  19378. if (ret != 0) {
  19379. impl::mbedtls_last_error() = ret;
  19380. delete ctx;
  19381. return nullptr;
  19382. }
  19383. #endif
  19384. // Set up SSL config for client
  19385. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  19386. MBEDTLS_SSL_TRANSPORT_STREAM,
  19387. MBEDTLS_SSL_PRESET_DEFAULT);
  19388. if (ret != 0) {
  19389. impl::mbedtls_last_error() = ret;
  19390. delete ctx;
  19391. return nullptr;
  19392. }
  19393. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19394. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  19395. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  19396. #endif
  19397. // Default: verify peer certificate
  19398. ctx->verify_client = true;
  19399. impl::apply_verify_mode(*ctx);
  19400. // Set minimum TLS version to 1.2
  19401. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19402. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19403. #else
  19404. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19405. MBEDTLS_SSL_MINOR_VERSION_3);
  19406. #endif
  19407. return static_cast<ctx_t>(ctx);
  19408. }
  19409. inline ctx_t create_server_context() {
  19410. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  19411. if (!ctx) { return nullptr; }
  19412. ctx->is_server = true;
  19413. #ifdef CPPHTTPLIB_MBEDTLS_V4
  19414. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  19415. if (!detail::ensure_mbedtls_psa_crypto()) {
  19416. delete ctx;
  19417. return nullptr;
  19418. }
  19419. int ret;
  19420. #else
  19421. // Seed the random number generator
  19422. const char *pers = "httplib_server";
  19423. int ret = mbedtls_ctr_drbg_seed(
  19424. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  19425. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  19426. if (ret != 0) {
  19427. impl::mbedtls_last_error() = ret;
  19428. delete ctx;
  19429. return nullptr;
  19430. }
  19431. #endif
  19432. // Set up SSL config for server
  19433. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  19434. MBEDTLS_SSL_TRANSPORT_STREAM,
  19435. MBEDTLS_SSL_PRESET_DEFAULT);
  19436. if (ret != 0) {
  19437. impl::mbedtls_last_error() = ret;
  19438. delete ctx;
  19439. return nullptr;
  19440. }
  19441. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19442. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  19443. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  19444. #endif
  19445. // Default: don't verify client
  19446. impl::apply_verify_mode(*ctx);
  19447. // Set minimum TLS version to 1.2
  19448. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19449. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19450. #else
  19451. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19452. MBEDTLS_SSL_MINOR_VERSION_3);
  19453. #endif
  19454. // Set SNI callback to capture client's SNI hostname
  19455. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  19456. return static_cast<ctx_t>(ctx);
  19457. }
  19458. inline void free_context(ctx_t ctx) {
  19459. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  19460. }
  19461. inline bool set_min_version(ctx_t ctx, Version version) {
  19462. if (!ctx) { return false; }
  19463. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19464. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19465. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  19466. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  19467. if (version >= Version::TLS1_3) {
  19468. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  19469. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  19470. #endif
  19471. }
  19472. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  19473. #else
  19474. // Mbed TLS 2.x uses major/minor version numbers
  19475. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  19476. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  19477. if (version >= Version::TLS1_3) {
  19478. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  19479. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  19480. #else
  19481. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  19482. #endif
  19483. }
  19484. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  19485. #endif
  19486. return true;
  19487. }
  19488. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  19489. if (!ctx || !pem) { return false; }
  19490. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19491. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  19492. // Add null terminator if not present
  19493. std::string pem_str(pem, len);
  19494. int ret = mbedtls_x509_crt_parse(
  19495. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  19496. pem_str.size() + 1);
  19497. if (ret != 0) {
  19498. impl::mbedtls_last_error() = ret;
  19499. return false;
  19500. }
  19501. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19502. return true;
  19503. }
  19504. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  19505. if (!ctx || !file_path) { return false; }
  19506. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19507. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  19508. if (ret != 0) {
  19509. impl::mbedtls_last_error() = ret;
  19510. return false;
  19511. }
  19512. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19513. return true;
  19514. }
  19515. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  19516. if (!ctx || !dir_path) { return false; }
  19517. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19518. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  19519. if (ret < 0) { // Returns number of certs on success, negative on error
  19520. impl::mbedtls_last_error() = ret;
  19521. return false;
  19522. }
  19523. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19524. return true;
  19525. }
  19526. inline bool load_system_certs(ctx_t ctx) {
  19527. if (!ctx) { return false; }
  19528. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19529. bool loaded = false;
  19530. #ifdef _WIN32
  19531. loaded = impl::enumerate_windows_system_certs(
  19532. [&](const unsigned char *data, size_t len) {
  19533. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  19534. });
  19535. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  19536. loaded = impl::enumerate_macos_keychain_certs(
  19537. [&](const unsigned char *data, size_t len) {
  19538. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  19539. });
  19540. #else
  19541. for (auto path = impl::system_ca_paths(); *path; ++path) {
  19542. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  19543. loaded = true;
  19544. break;
  19545. }
  19546. }
  19547. if (!loaded) {
  19548. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  19549. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  19550. loaded = true;
  19551. break;
  19552. }
  19553. }
  19554. }
  19555. #endif
  19556. if (loaded) {
  19557. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19558. }
  19559. return loaded;
  19560. }
  19561. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  19562. const char *password) {
  19563. if (!ctx || !cert || !key) { return false; }
  19564. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19565. // Parse certificate
  19566. std::string cert_str(cert);
  19567. int ret = mbedtls_x509_crt_parse(
  19568. &mctx->own_cert,
  19569. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  19570. cert_str.size() + 1);
  19571. if (ret != 0) {
  19572. impl::mbedtls_last_error() = ret;
  19573. return false;
  19574. }
  19575. // Parse private key
  19576. std::string key_str(key);
  19577. const unsigned char *pwd =
  19578. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  19579. size_t pwd_len = password ? strlen(password) : 0;
  19580. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  19581. ret = mbedtls_pk_parse_key(
  19582. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  19583. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  19584. &mctx->ctr_drbg);
  19585. #else
  19586. ret = mbedtls_pk_parse_key(
  19587. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  19588. key_str.size() + 1, pwd, pwd_len);
  19589. #endif
  19590. if (ret != 0) {
  19591. impl::mbedtls_last_error() = ret;
  19592. return false;
  19593. }
  19594. // Verify that the certificate and private key match.
  19595. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  19596. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  19597. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19598. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19599. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  19600. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  19601. #else
  19602. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  19603. #endif
  19604. if (ret != 0) {
  19605. impl::mbedtls_last_error() = ret;
  19606. return false;
  19607. }
  19608. #endif
  19609. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  19610. if (ret != 0) {
  19611. impl::mbedtls_last_error() = ret;
  19612. return false;
  19613. }
  19614. return true;
  19615. }
  19616. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  19617. const char *key_path, const char *password) {
  19618. if (!ctx || !cert_path || !key_path) { return false; }
  19619. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19620. // Parse certificate file
  19621. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  19622. if (ret != 0) {
  19623. impl::mbedtls_last_error() = ret;
  19624. return false;
  19625. }
  19626. // Parse private key file
  19627. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  19628. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  19629. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  19630. #else
  19631. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  19632. #endif
  19633. if (ret != 0) {
  19634. impl::mbedtls_last_error() = ret;
  19635. return false;
  19636. }
  19637. // Verify that the certificate and private key match.
  19638. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  19639. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19640. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19641. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  19642. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  19643. #else
  19644. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  19645. #endif
  19646. if (ret != 0) {
  19647. impl::mbedtls_last_error() = ret;
  19648. return false;
  19649. }
  19650. #endif
  19651. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  19652. if (ret != 0) {
  19653. impl::mbedtls_last_error() = ret;
  19654. return false;
  19655. }
  19656. return true;
  19657. }
  19658. inline void set_verify_client(ctx_t ctx, bool require) {
  19659. if (!ctx) { return; }
  19660. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19661. mctx->verify_client = require;
  19662. impl::apply_verify_mode(*mctx);
  19663. }
  19664. inline session_t create_session(ctx_t ctx, socket_t sock) {
  19665. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  19666. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19667. auto session = new (std::nothrow) impl::MbedTlsSession();
  19668. if (!session) { return nullptr; }
  19669. session->sock = sock;
  19670. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  19671. if (ret != 0) {
  19672. impl::mbedtls_last_error() = ret;
  19673. delete session;
  19674. return nullptr;
  19675. }
  19676. // Explicitly opt out of in-handshake hostname verification by default;
  19677. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  19678. // fails outright when no hostname was set. set_sni() installs the real
  19679. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  19680. // caller verifies the certificate identity post-handshake via
  19681. // verify_hostname().
  19682. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  19683. // Set BIO callbacks
  19684. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  19685. impl::mbedtls_net_recv_cb, nullptr);
  19686. // Installed always, as it also masks the hostname mismatch that set_sni()
  19687. // may ask for. The session runs its own copy of the user's callback, which
  19688. // set_verify_callback() cannot replace under a handshake.
  19689. session->verify_callback = mctx->verify_callback;
  19690. session->is_server = mctx->is_server;
  19691. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback, session);
  19692. return static_cast<session_t>(session);
  19693. }
  19694. inline void free_session(session_t session) {
  19695. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  19696. }
  19697. inline bool set_sni(session_t session, const char *hostname,
  19698. bool verify_hostname) {
  19699. if (!session || !hostname) { return false; }
  19700. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19701. // mbedtls_ssl_set_hostname() both sends the SNI extension and binds the
  19702. // handshake-time CN/SAN check to `hostname`; the two can't be requested
  19703. // independently, so a disabled hostname check is handled below by masking
  19704. // the resulting mismatch flag instead of skipping this call.
  19705. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  19706. if (ret != 0) {
  19707. impl::mbedtls_last_error() = ret;
  19708. return false;
  19709. }
  19710. msession->hostname = hostname;
  19711. if (!verify_hostname) { msession->suppress_hostname_mismatch = true; }
  19712. return true;
  19713. }
  19714. inline TlsError connect(session_t session) {
  19715. TlsError err;
  19716. if (!session) {
  19717. err.code = ErrorCode::Fatal;
  19718. return err;
  19719. }
  19720. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19721. int ret;
  19722. do {
  19723. ret = mbedtls_ssl_handshake(&msession->ssl);
  19724. } while (impl::mbedtls_is_session_ticket(ret));
  19725. if (ret == 0) {
  19726. err.code = ErrorCode::Success;
  19727. } else {
  19728. impl::fill_mbedtls_tls_error(err, msession->ssl, ret);
  19729. impl::mbedtls_last_error() = ret;
  19730. }
  19731. return err;
  19732. }
  19733. inline TlsError accept(session_t session) {
  19734. // A failed handshake leaves its SNI behind, so start without it
  19735. impl::mbedpending_sni().clear();
  19736. // Same as connect for Mbed TLS - handshake works for both client and server
  19737. auto result = connect(session);
  19738. // After successful handshake, capture SNI from thread-local storage
  19739. if (result.code == ErrorCode::Success && session) {
  19740. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19741. msession->sni_hostname = std::move(impl::mbedpending_sni());
  19742. }
  19743. return result;
  19744. }
  19745. inline bool connect_nonblocking(session_t session, socket_t sock,
  19746. time_t timeout_sec, time_t timeout_usec,
  19747. TlsError *err,
  19748. const std::function<bool()> &interrupted) {
  19749. if (!session) {
  19750. if (err) { err->code = ErrorCode::Fatal; }
  19751. return false;
  19752. }
  19753. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19754. // Set socket to non-blocking mode
  19755. detail::set_nonblocking(sock, true);
  19756. auto cleanup =
  19757. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  19758. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  19759. int ret;
  19760. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  19761. // Non-fatal TLS 1.3 ticket; retry immediately.
  19762. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  19763. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  19764. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  19765. continue;
  19766. }
  19767. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  19768. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  19769. continue;
  19770. }
  19771. }
  19772. // TlsError or timeout
  19773. if (err) { impl::fill_mbedtls_tls_error(*err, msession->ssl, ret); }
  19774. impl::mbedtls_last_error() = ret;
  19775. return false;
  19776. }
  19777. if (err) { err->code = ErrorCode::Success; }
  19778. return true;
  19779. }
  19780. inline bool accept_nonblocking(session_t session, socket_t sock,
  19781. time_t timeout_sec, time_t timeout_usec,
  19782. TlsError *err,
  19783. const std::function<bool()> &interrupted) {
  19784. // A failed handshake leaves its SNI behind, so start without it
  19785. impl::mbedpending_sni().clear();
  19786. // Same implementation as connect for Mbed TLS
  19787. bool result = connect_nonblocking(session, sock, timeout_sec, timeout_usec,
  19788. err, interrupted);
  19789. // After successful handshake, capture SNI from thread-local storage
  19790. if (result && session) {
  19791. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19792. msession->sni_hostname = std::move(impl::mbedpending_sni());
  19793. }
  19794. return result;
  19795. }
  19796. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  19797. if (!session || !buf) {
  19798. err.code = ErrorCode::Fatal;
  19799. return -1;
  19800. }
  19801. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19802. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  19803. if (msession->has_peeked_byte) {
  19804. if (len == 0) { return 0; }
  19805. auto p = static_cast<unsigned char *>(buf);
  19806. p[0] = msession->peeked_byte;
  19807. msession->has_peeked_byte = false;
  19808. size_t n = 1;
  19809. // Top up with any already-decrypted bytes without risking a block.
  19810. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  19811. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  19812. if (extra > 0) { n += static_cast<size_t>(extra); }
  19813. }
  19814. err.code = ErrorCode::Success;
  19815. return static_cast<ssize_t>(n);
  19816. }
  19817. int ret;
  19818. do {
  19819. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  19820. len);
  19821. } while (impl::mbedtls_is_session_ticket(ret));
  19822. if (ret > 0) {
  19823. err.code = ErrorCode::Success;
  19824. return static_cast<ssize_t>(ret);
  19825. }
  19826. // 0 means EOF without close_notify, which is an error as on OpenSSL
  19827. if (ret == 0) { ret = MBEDTLS_ERR_SSL_CONN_EOF; }
  19828. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  19829. err.backend_code = static_cast<uint64_t>(-ret);
  19830. impl::mbedtls_last_error() = ret;
  19831. // mbedTLS signals a clean close_notify via a negative error code rather
  19832. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  19833. if (err.code == ErrorCode::PeerClosed) { return 0; }
  19834. return -1;
  19835. }
  19836. inline ssize_t write(session_t session, const void *buf, size_t len,
  19837. TlsError &err) {
  19838. if (!session || !buf) {
  19839. err.code = ErrorCode::Fatal;
  19840. return -1;
  19841. }
  19842. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19843. int ret;
  19844. do {
  19845. ret = mbedtls_ssl_write(&msession->ssl,
  19846. static_cast<const unsigned char *>(buf), len);
  19847. } while (impl::mbedtls_is_session_ticket(ret));
  19848. if (ret > 0) {
  19849. err.code = ErrorCode::Success;
  19850. return static_cast<ssize_t>(ret);
  19851. }
  19852. if (ret == 0) {
  19853. err.code = ErrorCode::PeerClosed;
  19854. return 0;
  19855. }
  19856. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  19857. err.backend_code = static_cast<uint64_t>(-ret);
  19858. impl::mbedtls_last_error() = ret;
  19859. return -1;
  19860. }
  19861. inline int pending(const_session_t session) {
  19862. if (!session) { return 0; }
  19863. auto msession =
  19864. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  19865. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  19866. (msession->has_peeked_byte ? 1 : 0);
  19867. }
  19868. inline void shutdown(session_t session, bool graceful) {
  19869. if (!session) { return; }
  19870. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19871. if (graceful) {
  19872. // Try to send close_notify, but don't block forever
  19873. int ret;
  19874. int attempts = 0;
  19875. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  19876. attempts < 3) {
  19877. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  19878. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  19879. break;
  19880. }
  19881. attempts++;
  19882. }
  19883. }
  19884. }
  19885. inline bool is_peer_closed(session_t session, socket_t sock) {
  19886. if (!session || sock == INVALID_SOCKET) { return true; }
  19887. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19888. // Check if there's already decrypted or pushed-back data available.
  19889. // If so, the connection is definitely alive.
  19890. if (msession->has_peeked_byte ||
  19891. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  19892. return false;
  19893. }
  19894. // Set socket to non-blocking to avoid blocking on read
  19895. detail::set_nonblocking(sock, true);
  19896. auto cleanup =
  19897. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  19898. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  19899. // on application data — e.g. a response that already arrived — push the
  19900. // byte back so the next read() delivers it instead of losing it.
  19901. unsigned char buf;
  19902. int ret;
  19903. do {
  19904. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  19905. } while (impl::mbedtls_is_session_ticket(ret));
  19906. // If we got data or WANT_READ (would block), connection is alive
  19907. if (ret > 0) {
  19908. msession->peeked_byte = buf;
  19909. msession->has_peeked_byte = true;
  19910. return false;
  19911. }
  19912. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  19913. // If we get a peer close notify or a connection reset, the peer is closed
  19914. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  19915. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  19916. }
  19917. inline cert_t get_peer_cert(const_session_t session) {
  19918. if (!session) { return nullptr; }
  19919. auto msession =
  19920. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  19921. // Mbed TLS returns a pointer to the internal peer cert chain.
  19922. // WARNING: This pointer is only valid while the session is active.
  19923. // Do not use the certificate after calling free_session().
  19924. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  19925. return const_cast<mbedtls_x509_crt *>(cert);
  19926. }
  19927. inline size_t get_peer_certs(const_session_t session,
  19928. std::vector<cert_t> &certs) {
  19929. certs.clear();
  19930. // Mbed TLS parses the whole received chain into a list headed by the peer
  19931. // certificate, owned by the session like get_peer_cert()'s result
  19932. for (auto crt = static_cast<mbedtls_x509_crt *>(get_peer_cert(session));
  19933. crt && crt->raw.len > 0; crt = crt->next) {
  19934. certs.push_back(static_cast<cert_t>(crt));
  19935. }
  19936. return certs.size();
  19937. }
  19938. inline void free_cert(cert_t cert) {
  19939. // Mbed TLS: every cert_t handed out points into a session's or a context's
  19940. // chain, so there is nothing to free. Callers still call this for the other
  19941. // backends.
  19942. (void)cert;
  19943. }
  19944. inline bool verify_hostname(cert_t cert, const char *hostname) {
  19945. if (!cert || !hostname) { return false; }
  19946. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  19947. std::string host_str(hostname);
  19948. // Check if hostname is an IP address (IPv4 or IPv6)
  19949. unsigned char ip_bytes[16];
  19950. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  19951. auto is_ip = ip_len > 0;
  19952. // Check Subject Alternative Names (SAN). Mbed TLS keeps the GeneralName type
  19953. // in buf.tag and the raw value in buf.p / buf.len.
  19954. for (auto san = &mcert->subject_alt_names; san; san = san->next) {
  19955. if (!san->buf.p || san->buf.len == 0) { continue; }
  19956. const unsigned char *p = san->buf.p;
  19957. size_t len = san->buf.len;
  19958. auto san_type = san->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK;
  19959. if (is_ip) {
  19960. // For an IP host, only a matching iPAddress SAN of the same family
  19961. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  19962. if (san_type == MBEDTLS_X509_SAN_IP_ADDRESS && len == ip_len &&
  19963. memcmp(p, ip_bytes, ip_len) == 0) {
  19964. return true;
  19965. }
  19966. } else if (san_type == MBEDTLS_X509_SAN_DNS_NAME) {
  19967. std::string san_name(reinterpret_cast<const char *>(p), len);
  19968. if (detail::match_hostname(san_name, host_str)) { return true; }
  19969. }
  19970. }
  19971. return false;
  19972. }
  19973. inline uint64_t hostname_mismatch_code() {
  19974. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  19975. }
  19976. inline long get_verify_result(const_session_t session) {
  19977. if (!session) { return -1; }
  19978. auto msession =
  19979. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  19980. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  19981. // Return 0 (X509_V_OK equivalent) if verification passed
  19982. return flags == 0 ? 0 : static_cast<long>(flags);
  19983. }
  19984. inline std::string get_cert_subject_cn(cert_t cert) {
  19985. if (!cert) return "";
  19986. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  19987. // Find the CN in the subject
  19988. const mbedtls_x509_name *name = &x509->subject;
  19989. while (name != nullptr) {
  19990. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  19991. return std::string(reinterpret_cast<const char *>(name->val.p),
  19992. name->val.len);
  19993. }
  19994. name = name->next;
  19995. }
  19996. return "";
  19997. }
  19998. inline std::string get_cert_issuer_name(cert_t cert) {
  19999. if (!cert) return "";
  20000. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  20001. // Build a human-readable issuer name string
  20002. char buf[512];
  20003. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  20004. if (ret < 0) return "";
  20005. return std::string(buf);
  20006. }
  20007. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  20008. sans.clear();
  20009. if (!cert) return false;
  20010. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  20011. // Parse the Subject Alternative Name extension
  20012. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  20013. while (cur != nullptr) {
  20014. if (cur->buf.len > 0) {
  20015. const unsigned char *p = cur->buf.p;
  20016. size_t value_len = cur->buf.len;
  20017. SanEntry entry;
  20018. switch (cur->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK) {
  20019. case MBEDTLS_X509_SAN_DNS_NAME:
  20020. entry.type = SanType::DNS;
  20021. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  20022. break;
  20023. case MBEDTLS_X509_SAN_IP_ADDRESS:
  20024. entry.type = SanType::IP;
  20025. if (value_len == 4) {
  20026. // IPv4
  20027. char buf[16];
  20028. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  20029. entry.value = buf;
  20030. } else if (value_len == 16) {
  20031. // IPv6
  20032. char buf[64];
  20033. snprintf(buf, sizeof(buf),
  20034. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  20035. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  20036. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9],
  20037. p[10], p[11], p[12], p[13], p[14], p[15]);
  20038. entry.value = buf;
  20039. }
  20040. break;
  20041. case MBEDTLS_X509_SAN_RFC822_NAME:
  20042. entry.type = SanType::EMAIL;
  20043. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  20044. break;
  20045. case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER:
  20046. entry.type = SanType::URI;
  20047. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  20048. break;
  20049. default: entry.type = SanType::OTHER; break;
  20050. }
  20051. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  20052. }
  20053. cur = cur->next;
  20054. }
  20055. return true;
  20056. }
  20057. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  20058. time_t &not_after) {
  20059. if (!cert) return false;
  20060. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  20061. // Convert mbedtls_x509_time to time_t
  20062. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  20063. struct tm tm_time = {};
  20064. tm_time.tm_year = t.year - 1900;
  20065. tm_time.tm_mon = t.mon - 1;
  20066. tm_time.tm_mday = t.day;
  20067. tm_time.tm_hour = t.hour;
  20068. tm_time.tm_min = t.min;
  20069. tm_time.tm_sec = t.sec;
  20070. #ifdef _WIN32
  20071. return _mkgmtime(&tm_time);
  20072. #else
  20073. return timegm(&tm_time);
  20074. #endif
  20075. };
  20076. not_before = to_time_t(x509->valid_from);
  20077. not_after = to_time_t(x509->valid_to);
  20078. return true;
  20079. }
  20080. inline std::string get_cert_serial(cert_t cert) {
  20081. if (!cert) return "";
  20082. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  20083. // Convert serial number to hex string
  20084. std::string result;
  20085. result.reserve(x509->serial.len * 2);
  20086. for (size_t i = 0; i < x509->serial.len; i++) {
  20087. char hex[3];
  20088. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  20089. result += hex;
  20090. }
  20091. return result;
  20092. }
  20093. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  20094. if (!cert) return false;
  20095. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  20096. if (!crt->raw.p || crt->raw.len == 0) return false;
  20097. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  20098. return true;
  20099. }
  20100. inline const char *get_sni(const_session_t session) {
  20101. if (!session) return nullptr;
  20102. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  20103. // For server: return SNI received from client during handshake
  20104. if (!msession->sni_hostname.empty()) {
  20105. return msession->sni_hostname.c_str();
  20106. }
  20107. // For client: return the hostname set via set_sni
  20108. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  20109. return nullptr;
  20110. }
  20111. inline uint64_t peek_error() {
  20112. // Mbed TLS doesn't have an error queue, return the last error
  20113. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  20114. }
  20115. inline uint64_t get_error() {
  20116. // Mbed TLS doesn't have an error queue, return and clear the last error
  20117. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  20118. impl::mbedtls_last_error() = 0;
  20119. return err;
  20120. }
  20121. inline std::string error_string(uint64_t code) {
  20122. char buf[256];
  20123. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  20124. return std::string(buf);
  20125. }
  20126. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  20127. #ifdef CPPHTTPLIB_MBEDTLS_V4
  20128. // Parsing certificates needs PSA Crypto, and no context may exist yet
  20129. if (!detail::ensure_mbedtls_psa_crypto()) { return nullptr; }
  20130. #endif
  20131. if (!pem) { return nullptr; }
  20132. // mbedtls_x509_crt_parse expects null-terminated PEM
  20133. std::string pem_str(pem, len);
  20134. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  20135. if (!ca_chain) { return nullptr; }
  20136. mbedtls_x509_crt_init(ca_chain);
  20137. auto ret = mbedtls_x509_crt_parse(
  20138. ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  20139. pem_str.size() + 1);
  20140. if (ret != 0) {
  20141. mbedtls_x509_crt_free(ca_chain);
  20142. delete ca_chain;
  20143. return nullptr;
  20144. }
  20145. return static_cast<ca_store_t>(ca_chain);
  20146. }
  20147. inline void free_ca_store(ca_store_t store) {
  20148. if (store) {
  20149. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  20150. mbedtls_x509_crt_free(ca_chain);
  20151. delete ca_chain;
  20152. }
  20153. }
  20154. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  20155. if (!ctx || !store) { return false; }
  20156. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20157. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  20158. // Free existing CA chain
  20159. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  20160. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  20161. // Copy the CA chain (deep copy)
  20162. // Parse from the raw data of the source cert
  20163. mbedtls_x509_crt *src = ca_chain;
  20164. while (src != nullptr) {
  20165. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  20166. src->raw.len);
  20167. if (ret != 0) {
  20168. free_ca_store(store);
  20169. return false;
  20170. }
  20171. src = src->next;
  20172. }
  20173. // This function takes ownership of the store; the chain was deep-copied
  20174. // above, so release the source
  20175. free_ca_store(store);
  20176. // Update the SSL config to use the new CA chain
  20177. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  20178. return true;
  20179. }
  20180. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  20181. certs.clear();
  20182. if (!ctx) { return 0; }
  20183. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20184. // Owned by the context; see free_cert()
  20185. for (auto cert = &mbed_ctx->ca_chain; cert && cert->raw.len > 0;
  20186. cert = cert->next) {
  20187. certs.push_back(static_cast<cert_t>(cert));
  20188. }
  20189. return certs.size();
  20190. }
  20191. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  20192. std::vector<std::string> names;
  20193. if (!ctx) { return names; }
  20194. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20195. // Iterate through the CA chain
  20196. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  20197. while (cert != nullptr && cert->raw.len > 0) {
  20198. char buf[512];
  20199. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  20200. if (ret > 0) { names.push_back(buf); }
  20201. cert = cert->next;
  20202. }
  20203. return names;
  20204. }
  20205. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  20206. const char *key_pem, const char *password) {
  20207. if (!ctx || !cert_pem || !key_pem) { return false; }
  20208. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20209. // Parse into new objects first, so that a bad pair leaves the old one in
  20210. // place, and swap them in after; the old ones are freed on the way out.
  20211. mbedtls_x509_crt cert;
  20212. mbedtls_pk_context key;
  20213. mbedtls_x509_crt_init(&cert);
  20214. mbedtls_pk_init(&key);
  20215. auto se = detail::scope_exit([&] {
  20216. mbedtls_x509_crt_free(&cert);
  20217. mbedtls_pk_free(&key);
  20218. });
  20219. // Parse certificate PEM
  20220. int ret = mbedtls_x509_crt_parse(
  20221. &cert, reinterpret_cast<const unsigned char *>(cert_pem),
  20222. strlen(cert_pem) + 1);
  20223. if (ret != 0) {
  20224. impl::mbedtls_last_error() = ret;
  20225. return false;
  20226. }
  20227. // Parse private key PEM
  20228. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  20229. ret = mbedtls_pk_parse_key(
  20230. &key, reinterpret_cast<const unsigned char *>(key_pem),
  20231. strlen(key_pem) + 1,
  20232. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  20233. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  20234. &mbed_ctx->ctr_drbg);
  20235. #else
  20236. ret = mbedtls_pk_parse_key(
  20237. &key, reinterpret_cast<const unsigned char *>(key_pem),
  20238. strlen(key_pem) + 1,
  20239. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  20240. password ? strlen(password) : 0);
  20241. #endif
  20242. if (ret != 0) {
  20243. impl::mbedtls_last_error() = ret;
  20244. return false;
  20245. }
  20246. std::swap(mbed_ctx->own_cert, cert);
  20247. std::swap(mbed_ctx->own_key, key);
  20248. // Configure SSL to use the new certificate and key
  20249. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  20250. &mbed_ctx->own_key);
  20251. if (ret != 0) {
  20252. impl::mbedtls_last_error() = ret;
  20253. return false;
  20254. }
  20255. return true;
  20256. }
  20257. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  20258. if (!ctx || !ca_pem) { return false; }
  20259. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20260. // Parse into a new chain first, so that a bad one leaves the old in place
  20261. mbedtls_x509_crt chain;
  20262. mbedtls_x509_crt_init(&chain);
  20263. auto se = detail::scope_exit([&] { mbedtls_x509_crt_free(&chain); });
  20264. // Parse CA PEM
  20265. int ret = mbedtls_x509_crt_parse(
  20266. &chain, reinterpret_cast<const unsigned char *>(ca_pem),
  20267. strlen(ca_pem) + 1);
  20268. if (ret != 0) {
  20269. impl::mbedtls_last_error() = ret;
  20270. return false;
  20271. }
  20272. std::swap(mbed_ctx->ca_chain, chain);
  20273. // Update SSL config to use new CA chain
  20274. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  20275. return true;
  20276. }
  20277. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  20278. if (!ctx) { return false; }
  20279. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20280. // create_session() hands each session its own copy to run.
  20281. mbed_ctx->verify_callback = std::move(callback);
  20282. impl::apply_verify_mode(*mbed_ctx);
  20283. return true;
  20284. }
  20285. inline long get_verify_error(const_session_t session) {
  20286. if (!session) { return -1; }
  20287. auto *msession =
  20288. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  20289. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  20290. }
  20291. inline std::string verify_error_string(long error_code) {
  20292. if (error_code == 0) { return ""; }
  20293. char buf[256];
  20294. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  20295. static_cast<uint32_t>(error_code));
  20296. // Remove trailing newline if present
  20297. std::string result(buf);
  20298. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  20299. result.pop_back();
  20300. }
  20301. return result;
  20302. }
  20303. } // namespace tls
  20304. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  20305. /*
  20306. * Group 10: TLS abstraction layer - wolfSSL backend
  20307. */
  20308. /*
  20309. * wolfSSL Backend Implementation
  20310. */
  20311. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  20312. namespace tls {
  20313. namespace impl {
  20314. // wolfSSL session wrapper
  20315. struct WolfSSLSession {
  20316. WOLFSSL *ssl = nullptr;
  20317. socket_t sock = INVALID_SOCKET;
  20318. std::string hostname; // For client: set via set_sni
  20319. std::string sni_hostname; // For server: received from client via SNI callback
  20320. WolfSSLSession() = default;
  20321. ~WolfSSLSession() {
  20322. if (ssl) { wolfSSL_free(ssl); }
  20323. }
  20324. WolfSSLSession(const WolfSSLSession &) = delete;
  20325. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  20326. };
  20327. // Thread-local error code accessor for wolfSSL
  20328. inline uint64_t &wolfssl_last_error() {
  20329. static thread_local uint64_t err = 0;
  20330. return err;
  20331. }
  20332. // Helper to map wolfSSL error to ErrorCode.
  20333. // ssl_error is the value from wolfSSL_get_error().
  20334. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  20335. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  20336. int &out_errno) {
  20337. switch (ssl_error) {
  20338. case SSL_ERROR_NONE: return ErrorCode::Success;
  20339. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  20340. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  20341. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  20342. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  20343. // EOF without close_notify
  20344. case SOCKET_PEER_CLOSED_E: out_errno = 0; return ErrorCode::SyscallError;
  20345. default:
  20346. if (ssl) {
  20347. // wolfSSL stores the low-level error code as a negative value.
  20348. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  20349. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  20350. if (low_err == DOMAIN_NAME_MISMATCH) {
  20351. return ErrorCode::HostnameMismatch;
  20352. }
  20353. // Check verify result to distinguish cert verification from generic SSL
  20354. // errors.
  20355. long vr = wolfSSL_get_verify_result(ssl);
  20356. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  20357. }
  20358. return ErrorCode::Fatal;
  20359. }
  20360. }
  20361. // WolfSSLContext constructor/destructor implementations
  20362. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  20363. inline WolfSSLContext::~WolfSSLContext() {
  20364. if (ctx) { wolfSSL_CTX_free(ctx); }
  20365. }
  20366. // Thread-local storage for SNI captured during handshake
  20367. inline std::string &wolfssl_pending_sni() {
  20368. static thread_local std::string sni;
  20369. return sni;
  20370. }
  20371. // SNI callback for wolfSSL server to capture client's SNI hostname
  20372. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  20373. (void)ret;
  20374. (void)exArg;
  20375. void *name_data = nullptr;
  20376. unsigned short name_len =
  20377. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  20378. if (name_data && name_len > 0) {
  20379. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  20380. name_len);
  20381. } else {
  20382. wolfssl_pending_sni().clear();
  20383. }
  20384. return 0; // Continue regardless
  20385. }
  20386. // The WOLFSSL_CTX points back to its WolfSSLContext, so a handshake only ever
  20387. // runs the verify callback of its own context.
  20388. inline int context_ex_data_index() {
  20389. static const auto index =
  20390. wolfSSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
  20391. return index;
  20392. }
  20393. // Each WOLFSSL points back to its WolfSSLSession, the session_t that every
  20394. // other tls:: function takes.
  20395. inline int session_ex_data_index() {
  20396. static const auto index =
  20397. wolfSSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
  20398. return index;
  20399. }
  20400. // A resumed session skips the client's certificate, so a server that checks
  20401. // one would let in a certificate checked against another server's CA, as
  20402. // wolfSSL shares its session cache between contexts, or against a CA since
  20403. // replaced by update_server_client_ca().
  20404. inline void disable_server_resumption(WolfSSLContext *wctx) {
  20405. if (!wctx->is_server) { return; }
  20406. wolfSSL_CTX_set_session_cache_mode(wctx->ctx, WOLFSSL_SESS_CACHE_OFF);
  20407. #ifdef HAVE_SESSION_TICKET
  20408. wolfSSL_CTX_NoTicketTLSv12(wctx->ctx);
  20409. #endif
  20410. }
  20411. // wolfSSL verify callback wrapper
  20412. inline int wolfssl_verify_callback(int preverify_ok,
  20413. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  20414. // Get the WOLFSSL object from the X509_STORE_CTX
  20415. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  20416. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  20417. if (!ssl) { return preverify_ok; }
  20418. auto wctx = static_cast<WolfSSLContext *>(wolfSSL_CTX_get_ex_data(
  20419. wolfSSL_get_SSL_CTX(ssl), context_ex_data_index()));
  20420. if (!wctx) { return preverify_ok; }
  20421. std::shared_ptr<VerifyCallback> callback;
  20422. {
  20423. std::lock_guard<std::mutex> guard(verify_callback_mutex());
  20424. callback = wctx->verify_callback;
  20425. }
  20426. if (!callback) { return preverify_ok; }
  20427. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  20428. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  20429. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  20430. VerifyContext verify_ctx;
  20431. verify_ctx.session = wolfSSL_get_ex_data(ssl, session_ex_data_index());
  20432. verify_ctx.cert = static_cast<cert_t>(cert);
  20433. verify_ctx.depth = depth;
  20434. verify_ctx.preverify_ok = (preverify_ok != 0);
  20435. verify_ctx.error_code = static_cast<long>(err);
  20436. if (err != 0) {
  20437. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  20438. } else {
  20439. verify_ctx.error_string = nullptr;
  20440. }
  20441. auto accepted = run_verify_callback(*callback, verify_ctx);
  20442. // A client verifying the server during the handshake, which is what
  20443. // set_verify_client(ctx, true) asks for there, keeps the built-in verdict
  20444. if (!wolfSSL_is_server(ssl) &&
  20445. (wolfSSL_get_verify_mode(ssl) & WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  20446. accepted = accepted && preverify_ok;
  20447. }
  20448. return accepted ? 1 : 0;
  20449. }
  20450. // Sets the verify mode from whether the peer's certificate is required and
  20451. // whether a verify callback is set.
  20452. inline void apply_verify_mode(WolfSSLContext &wctx) {
  20453. auto has_callback = static_cast<bool>(wctx.verify_callback);
  20454. if (wctx.verify_client || has_callback) { disable_server_resumption(&wctx); }
  20455. auto mode = wctx.verify_client
  20456. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  20457. : (has_callback ? SSL_VERIFY_PEER : SSL_VERIFY_NONE);
  20458. wolfSSL_CTX_set_verify(wctx.ctx, mode,
  20459. has_callback ? wolfssl_verify_callback : nullptr);
  20460. }
  20461. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  20462. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  20463. wolfSSL_CTX_set_default_passwd_cb(
  20464. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  20465. auto *pwd = static_cast<const char *>(userdata);
  20466. if (!pwd) return 0;
  20467. auto len = static_cast<int>(strlen(pwd));
  20468. if (len > size) len = size;
  20469. memcpy(buf, pwd, static_cast<size_t>(len));
  20470. return len;
  20471. });
  20472. }
  20473. } // namespace impl
  20474. inline ctx_t create_client_context() {
  20475. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  20476. if (!ctx) { return nullptr; }
  20477. ctx->is_server = false;
  20478. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  20479. if (!method) {
  20480. delete ctx;
  20481. return nullptr;
  20482. }
  20483. ctx->ctx = wolfSSL_CTX_new(method);
  20484. if (!ctx->ctx ||
  20485. wolfSSL_CTX_set_ex_data(ctx->ctx, impl::context_ex_data_index(), ctx) !=
  20486. WOLFSSL_SUCCESS) {
  20487. delete ctx;
  20488. return nullptr;
  20489. }
  20490. // Default: verify peer certificate
  20491. ctx->verify_client = true;
  20492. impl::apply_verify_mode(*ctx);
  20493. return static_cast<ctx_t>(ctx);
  20494. }
  20495. inline ctx_t create_server_context() {
  20496. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  20497. if (!ctx) { return nullptr; }
  20498. ctx->is_server = true;
  20499. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  20500. if (!method) {
  20501. delete ctx;
  20502. return nullptr;
  20503. }
  20504. ctx->ctx = wolfSSL_CTX_new(method);
  20505. if (!ctx->ctx ||
  20506. wolfSSL_CTX_set_ex_data(ctx->ctx, impl::context_ex_data_index(), ctx) !=
  20507. WOLFSSL_SUCCESS) {
  20508. delete ctx;
  20509. return nullptr;
  20510. }
  20511. // Default: don't verify client
  20512. impl::apply_verify_mode(*ctx);
  20513. // Enable SNI on server
  20514. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  20515. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  20516. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  20517. return static_cast<ctx_t>(ctx);
  20518. }
  20519. inline void free_context(ctx_t ctx) {
  20520. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  20521. }
  20522. inline bool set_min_version(ctx_t ctx, Version version) {
  20523. if (!ctx) { return false; }
  20524. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20525. int min_ver = WOLFSSL_TLSV1_2;
  20526. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  20527. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  20528. }
  20529. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  20530. if (!ctx || !pem) { return false; }
  20531. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20532. int ret = wolfSSL_CTX_load_verify_buffer(
  20533. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  20534. static_cast<long>(len), SSL_FILETYPE_PEM);
  20535. if (ret != SSL_SUCCESS) {
  20536. impl::wolfssl_last_error() =
  20537. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20538. return false;
  20539. }
  20540. wctx->ca_pem_data_.append(pem, len);
  20541. return true;
  20542. }
  20543. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  20544. if (!ctx || !file_path) { return false; }
  20545. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20546. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  20547. if (ret != SSL_SUCCESS) {
  20548. impl::wolfssl_last_error() =
  20549. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20550. return false;
  20551. }
  20552. return true;
  20553. }
  20554. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  20555. if (!ctx || !dir_path) { return false; }
  20556. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20557. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  20558. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  20559. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  20560. // immediately. Return true even on failure since the CA file may have
  20561. // already been loaded, matching OpenSSL's lenient behavior.
  20562. (void)ret;
  20563. return true;
  20564. }
  20565. inline bool load_system_certs(ctx_t ctx) {
  20566. if (!ctx) { return false; }
  20567. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20568. bool loaded = false;
  20569. #ifdef _WIN32
  20570. loaded = impl::enumerate_windows_system_certs(
  20571. [&](const unsigned char *data, size_t len) {
  20572. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  20573. static_cast<long>(len),
  20574. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  20575. });
  20576. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  20577. loaded = impl::enumerate_macos_keychain_certs(
  20578. [&](const unsigned char *data, size_t len) {
  20579. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  20580. static_cast<long>(len),
  20581. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  20582. });
  20583. #else
  20584. for (auto path = impl::system_ca_paths(); *path; ++path) {
  20585. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  20586. SSL_SUCCESS) {
  20587. loaded = true;
  20588. break;
  20589. }
  20590. }
  20591. if (!loaded) {
  20592. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  20593. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  20594. SSL_SUCCESS) {
  20595. loaded = true;
  20596. break;
  20597. }
  20598. }
  20599. }
  20600. #endif
  20601. return loaded;
  20602. }
  20603. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  20604. const char *password) {
  20605. if (!ctx || !cert || !key) { return false; }
  20606. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20607. // Load certificate
  20608. int ret = wolfSSL_CTX_use_certificate_buffer(
  20609. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  20610. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  20611. if (ret != SSL_SUCCESS) {
  20612. impl::wolfssl_last_error() =
  20613. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20614. return false;
  20615. }
  20616. // Set password callback if password is provided
  20617. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  20618. // Load private key
  20619. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  20620. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  20621. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  20622. if (ret != SSL_SUCCESS) {
  20623. impl::wolfssl_last_error() =
  20624. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20625. return false;
  20626. }
  20627. // Verify that the certificate and private key match
  20628. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  20629. }
  20630. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  20631. const char *key_path, const char *password) {
  20632. if (!ctx || !cert_path || !key_path) { return false; }
  20633. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20634. // Load certificate file
  20635. int ret =
  20636. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  20637. if (ret != SSL_SUCCESS) {
  20638. impl::wolfssl_last_error() =
  20639. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20640. return false;
  20641. }
  20642. // Set password callback if password is provided
  20643. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  20644. // Load private key file
  20645. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  20646. if (ret != SSL_SUCCESS) {
  20647. impl::wolfssl_last_error() =
  20648. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20649. return false;
  20650. }
  20651. // Verify that the certificate and private key match
  20652. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  20653. }
  20654. inline void set_verify_client(ctx_t ctx, bool require) {
  20655. if (!ctx) { return; }
  20656. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20657. wctx->verify_client = require;
  20658. impl::apply_verify_mode(*wctx);
  20659. }
  20660. inline session_t create_session(ctx_t ctx, socket_t sock) {
  20661. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  20662. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20663. auto session = new (std::nothrow) impl::WolfSSLSession();
  20664. if (!session) { return nullptr; }
  20665. session->sock = sock;
  20666. session->ssl = wolfSSL_new(wctx->ctx);
  20667. if (!session->ssl) {
  20668. impl::wolfssl_last_error() =
  20669. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20670. delete session;
  20671. return nullptr;
  20672. }
  20673. if (wolfSSL_set_ex_data(session->ssl, impl::session_ex_data_index(),
  20674. session) != WOLFSSL_SUCCESS) {
  20675. delete session;
  20676. return nullptr;
  20677. }
  20678. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  20679. return static_cast<session_t>(session);
  20680. }
  20681. inline void free_session(session_t session) {
  20682. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  20683. }
  20684. inline bool set_sni(session_t session, const char *hostname,
  20685. bool verify_hostname) {
  20686. if (!session || !hostname) { return false; }
  20687. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20688. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  20689. static_cast<word16>(strlen(hostname)));
  20690. if (ret != WOLFSSL_SUCCESS) {
  20691. impl::wolfssl_last_error() =
  20692. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20693. return false;
  20694. }
  20695. // wolfSSL_check_domain_name binds identity checking to the handshake,
  20696. // separately from the SNI extension sent above; skip it when hostname
  20697. // verification is disabled so only the chain is checked, matching OpenSSL.
  20698. if (verify_hostname) { wolfSSL_check_domain_name(wsession->ssl, hostname); }
  20699. wsession->hostname = hostname;
  20700. return true;
  20701. }
  20702. inline TlsError connect(session_t session) {
  20703. TlsError err;
  20704. if (!session) {
  20705. err.code = ErrorCode::Fatal;
  20706. return err;
  20707. }
  20708. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20709. int ret = wolfSSL_connect(wsession->ssl);
  20710. if (ret == SSL_SUCCESS) {
  20711. err.code = ErrorCode::Success;
  20712. } else {
  20713. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20714. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20715. err.backend_code = static_cast<uint64_t>(ssl_error);
  20716. impl::wolfssl_last_error() = err.backend_code;
  20717. }
  20718. return err;
  20719. }
  20720. inline TlsError accept(session_t session) {
  20721. TlsError err;
  20722. if (!session) {
  20723. err.code = ErrorCode::Fatal;
  20724. return err;
  20725. }
  20726. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20727. int ret = wolfSSL_accept(wsession->ssl);
  20728. if (ret == SSL_SUCCESS) {
  20729. err.code = ErrorCode::Success;
  20730. // Capture SNI from thread-local storage after successful handshake
  20731. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  20732. impl::wolfssl_pending_sni().clear();
  20733. } else {
  20734. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20735. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20736. err.backend_code = static_cast<uint64_t>(ssl_error);
  20737. impl::wolfssl_last_error() = err.backend_code;
  20738. }
  20739. return err;
  20740. }
  20741. inline bool connect_nonblocking(session_t session, socket_t sock,
  20742. time_t timeout_sec, time_t timeout_usec,
  20743. TlsError *err,
  20744. const std::function<bool()> &interrupted) {
  20745. if (!session) {
  20746. if (err) { err->code = ErrorCode::Fatal; }
  20747. return false;
  20748. }
  20749. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20750. // Set socket to non-blocking mode
  20751. detail::set_nonblocking(sock, true);
  20752. auto cleanup =
  20753. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  20754. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  20755. int ret;
  20756. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  20757. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20758. if (ssl_error == SSL_ERROR_WANT_READ) {
  20759. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  20760. continue;
  20761. }
  20762. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  20763. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  20764. continue;
  20765. }
  20766. }
  20767. // Error or timeout
  20768. if (err) {
  20769. err->code =
  20770. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  20771. err->backend_code = static_cast<uint64_t>(ssl_error);
  20772. }
  20773. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  20774. return false;
  20775. }
  20776. if (err) { err->code = ErrorCode::Success; }
  20777. return true;
  20778. }
  20779. inline bool accept_nonblocking(session_t session, socket_t sock,
  20780. time_t timeout_sec, time_t timeout_usec,
  20781. TlsError *err,
  20782. const std::function<bool()> &interrupted) {
  20783. if (!session) {
  20784. if (err) { err->code = ErrorCode::Fatal; }
  20785. return false;
  20786. }
  20787. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20788. // Set socket to non-blocking mode
  20789. detail::set_nonblocking(sock, true);
  20790. auto cleanup =
  20791. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  20792. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  20793. int ret;
  20794. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  20795. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20796. if (ssl_error == SSL_ERROR_WANT_READ) {
  20797. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  20798. continue;
  20799. }
  20800. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  20801. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  20802. continue;
  20803. }
  20804. }
  20805. // Error or timeout
  20806. if (err) {
  20807. err->code =
  20808. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  20809. err->backend_code = static_cast<uint64_t>(ssl_error);
  20810. }
  20811. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  20812. return false;
  20813. }
  20814. if (err) { err->code = ErrorCode::Success; }
  20815. // Capture SNI from thread-local storage after successful handshake
  20816. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  20817. impl::wolfssl_pending_sni().clear();
  20818. return true;
  20819. }
  20820. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  20821. if (!session || !buf) {
  20822. err.code = ErrorCode::Fatal;
  20823. return -1;
  20824. }
  20825. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20826. constexpr auto max_len =
  20827. static_cast<size_t>((std::numeric_limits<int>::max)());
  20828. if (len > max_len) { len = max_len; }
  20829. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  20830. if (ret > 0) {
  20831. err.code = ErrorCode::Success;
  20832. return static_cast<ssize_t>(ret);
  20833. }
  20834. // 0 is also returned for EOF without close_notify; get_error tells them apart
  20835. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20836. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20837. if (err.code == ErrorCode::PeerClosed) { return 0; }
  20838. err.backend_code = static_cast<uint64_t>(ssl_error);
  20839. impl::wolfssl_last_error() = err.backend_code;
  20840. return -1;
  20841. }
  20842. inline ssize_t write(session_t session, const void *buf, size_t len,
  20843. TlsError &err) {
  20844. if (!session || !buf) {
  20845. err.code = ErrorCode::Fatal;
  20846. return -1;
  20847. }
  20848. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20849. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  20850. if (ret > 0) {
  20851. err.code = ErrorCode::Success;
  20852. return static_cast<ssize_t>(ret);
  20853. }
  20854. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  20855. // Treat this as an error (return -1) so callers don't spin in a
  20856. // write loop adding zero to the offset.
  20857. if (ret == 0) {
  20858. err.code = ErrorCode::PeerClosed;
  20859. return -1;
  20860. }
  20861. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20862. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20863. err.backend_code = static_cast<uint64_t>(ssl_error);
  20864. impl::wolfssl_last_error() = err.backend_code;
  20865. return -1;
  20866. }
  20867. inline int pending(const_session_t session) {
  20868. if (!session) { return 0; }
  20869. auto wsession =
  20870. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20871. return wolfSSL_pending(wsession->ssl);
  20872. }
  20873. inline void shutdown(session_t session, bool graceful) {
  20874. if (!session) { return; }
  20875. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20876. if (graceful) {
  20877. int ret;
  20878. int attempts = 0;
  20879. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  20880. attempts < 3) {
  20881. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20882. if (ssl_error != SSL_ERROR_WANT_READ &&
  20883. ssl_error != SSL_ERROR_WANT_WRITE) {
  20884. break;
  20885. }
  20886. attempts++;
  20887. }
  20888. } else {
  20889. wolfSSL_shutdown(wsession->ssl);
  20890. }
  20891. }
  20892. inline bool is_peer_closed(session_t session, socket_t sock) {
  20893. if (!session || sock == INVALID_SOCKET) { return true; }
  20894. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20895. // Check if there's already decrypted data available
  20896. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  20897. // Set socket to non-blocking to avoid blocking on read
  20898. detail::set_nonblocking(sock, true);
  20899. auto cleanup =
  20900. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  20901. // Peek 1 byte to check connection status without consuming data
  20902. unsigned char buf;
  20903. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  20904. // If we got data or WANT_READ (would block), connection is alive
  20905. if (ret > 0) { return false; }
  20906. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20907. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  20908. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  20909. ret == 0;
  20910. }
  20911. inline cert_t get_peer_cert(const_session_t session) {
  20912. if (!session) { return nullptr; }
  20913. auto wsession =
  20914. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20915. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  20916. return static_cast<cert_t>(cert);
  20917. }
  20918. inline size_t get_peer_certs(const_session_t session,
  20919. std::vector<cert_t> &certs) {
  20920. certs.clear();
  20921. if (!session) { return 0; }
  20922. // wolfSSL keeps the received chain only when built with SESSION_CERTS
  20923. #ifdef SESSION_CERTS
  20924. auto wsession =
  20925. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20926. auto chain = wolfSSL_get_peer_chain(wsession->ssl);
  20927. auto count = chain ? wolfSSL_get_chain_count(chain) : 0;
  20928. for (int i = 0; i < count; i++) {
  20929. auto x509 = wolfSSL_get_chain_X509(chain, i);
  20930. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  20931. }
  20932. #endif
  20933. return certs.size();
  20934. }
  20935. inline void free_cert(cert_t cert) {
  20936. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  20937. }
  20938. inline bool verify_hostname(cert_t cert, const char *hostname) {
  20939. if (!cert || !hostname) { return false; }
  20940. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  20941. std::string host_str(hostname);
  20942. // Check if hostname is an IP address (IPv4 or IPv6)
  20943. unsigned char ip_bytes[16];
  20944. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  20945. auto is_ip = ip_len > 0;
  20946. // Check Subject Alternative Names
  20947. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  20948. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  20949. if (san_names) {
  20950. int san_count = wolfSSL_sk_num(san_names);
  20951. for (int i = 0; i < san_count; i++) {
  20952. auto *names =
  20953. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  20954. if (!names) continue;
  20955. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  20956. // DNS name
  20957. unsigned char *dns_name = nullptr;
  20958. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  20959. if (dns_name && dns_len > 0) {
  20960. std::string san_name(reinterpret_cast<char *>(dns_name),
  20961. static_cast<size_t>(dns_len));
  20962. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  20963. if (detail::match_hostname(san_name, host_str)) {
  20964. wolfSSL_sk_free(san_names);
  20965. return true;
  20966. }
  20967. }
  20968. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  20969. // IP address: only an iPAddress SAN of the same family (4 bytes for
  20970. // IPv4, 16 bytes for IPv6) may authenticate the host.
  20971. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  20972. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  20973. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  20974. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  20975. wolfSSL_sk_free(san_names);
  20976. return true;
  20977. }
  20978. }
  20979. }
  20980. wolfSSL_sk_free(san_names);
  20981. }
  20982. return false;
  20983. }
  20984. inline uint64_t hostname_mismatch_code() {
  20985. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  20986. }
  20987. inline long get_verify_result(const_session_t session) {
  20988. if (!session) { return -1; }
  20989. auto wsession =
  20990. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20991. long result = wolfSSL_get_verify_result(wsession->ssl);
  20992. return result;
  20993. }
  20994. inline std::string get_cert_subject_cn(cert_t cert) {
  20995. if (!cert) return "";
  20996. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  20997. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  20998. if (!subject) return "";
  20999. char cn[256] = {};
  21000. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  21001. sizeof(cn));
  21002. if (cn_len <= 0) return "";
  21003. return std::string(cn, static_cast<size_t>(cn_len));
  21004. }
  21005. inline std::string get_cert_issuer_name(cert_t cert) {
  21006. if (!cert) return "";
  21007. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21008. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  21009. if (!issuer) return "";
  21010. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  21011. if (!name_str) return "";
  21012. std::string result(name_str);
  21013. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  21014. return result;
  21015. }
  21016. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  21017. sans.clear();
  21018. if (!cert) return false;
  21019. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21020. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  21021. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  21022. if (!san_names) return true; // No SANs is not an error
  21023. int count = wolfSSL_sk_num(san_names);
  21024. for (int i = 0; i < count; i++) {
  21025. auto *name =
  21026. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  21027. if (!name) continue;
  21028. SanEntry entry;
  21029. switch (name->type) {
  21030. case WOLFSSL_GEN_DNS: {
  21031. entry.type = SanType::DNS;
  21032. unsigned char *dns_name = nullptr;
  21033. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  21034. if (dns_name && dns_len > 0) {
  21035. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  21036. static_cast<size_t>(dns_len));
  21037. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  21038. }
  21039. break;
  21040. }
  21041. case WOLFSSL_GEN_IPADD: {
  21042. entry.type = SanType::IP;
  21043. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  21044. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  21045. if (ip_data && ip_len == 4) {
  21046. char buf[16];
  21047. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  21048. ip_data[2], ip_data[3]);
  21049. entry.value = buf;
  21050. } else if (ip_data && ip_len == 16) {
  21051. char buf[64];
  21052. snprintf(buf, sizeof(buf),
  21053. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  21054. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  21055. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  21056. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  21057. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  21058. ip_data[14], ip_data[15]);
  21059. entry.value = buf;
  21060. }
  21061. break;
  21062. }
  21063. case WOLFSSL_GEN_EMAIL:
  21064. entry.type = SanType::EMAIL;
  21065. {
  21066. unsigned char *email = nullptr;
  21067. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  21068. if (email && email_len > 0) {
  21069. entry.value = std::string(reinterpret_cast<char *>(email),
  21070. static_cast<size_t>(email_len));
  21071. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  21072. }
  21073. }
  21074. break;
  21075. case WOLFSSL_GEN_URI:
  21076. entry.type = SanType::URI;
  21077. {
  21078. unsigned char *uri = nullptr;
  21079. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  21080. &uri, name->d.uniformResourceIdentifier);
  21081. if (uri && uri_len > 0) {
  21082. entry.value = std::string(reinterpret_cast<char *>(uri),
  21083. static_cast<size_t>(uri_len));
  21084. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  21085. }
  21086. }
  21087. break;
  21088. default: entry.type = SanType::OTHER; break;
  21089. }
  21090. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  21091. }
  21092. wolfSSL_sk_free(san_names);
  21093. return true;
  21094. }
  21095. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  21096. time_t &not_after) {
  21097. if (!cert) return false;
  21098. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21099. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  21100. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  21101. if (!nb || !na) return false;
  21102. // wolfSSL_ASN1_TIME_to_tm is available
  21103. struct tm tm_nb = {}, tm_na = {};
  21104. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  21105. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  21106. #ifdef _WIN32
  21107. not_before = _mkgmtime(&tm_nb);
  21108. not_after = _mkgmtime(&tm_na);
  21109. #else
  21110. not_before = timegm(&tm_nb);
  21111. not_after = timegm(&tm_na);
  21112. #endif
  21113. return true;
  21114. }
  21115. inline std::string get_cert_serial(cert_t cert) {
  21116. if (!cert) return "";
  21117. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21118. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  21119. if (!serial_asn1) return "";
  21120. // Get the serial number data
  21121. int len = serial_asn1->length;
  21122. unsigned char *data = serial_asn1->data;
  21123. if (!data || len <= 0) return "";
  21124. std::string result;
  21125. result.reserve(static_cast<size_t>(len) * 2);
  21126. for (int i = 0; i < len; i++) {
  21127. char hex[3];
  21128. snprintf(hex, sizeof(hex), "%02X", data[i]);
  21129. result += hex;
  21130. }
  21131. return result;
  21132. }
  21133. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  21134. if (!cert) return false;
  21135. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21136. int der_len = 0;
  21137. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  21138. if (!der_data || der_len <= 0) return false;
  21139. der.assign(der_data, der_data + der_len);
  21140. return true;
  21141. }
  21142. inline const char *get_sni(const_session_t session) {
  21143. if (!session) return nullptr;
  21144. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  21145. // For server: return SNI received from client during handshake
  21146. if (!wsession->sni_hostname.empty()) {
  21147. return wsession->sni_hostname.c_str();
  21148. }
  21149. // For client: return the hostname set via set_sni
  21150. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  21151. return nullptr;
  21152. }
  21153. inline uint64_t peek_error() {
  21154. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  21155. }
  21156. inline uint64_t get_error() {
  21157. uint64_t err = impl::wolfssl_last_error();
  21158. impl::wolfssl_last_error() = 0;
  21159. return err;
  21160. }
  21161. inline std::string error_string(uint64_t code) {
  21162. char buf[256];
  21163. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  21164. return std::string(buf);
  21165. }
  21166. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  21167. if (!pem || len == 0) { return nullptr; }
  21168. // Validate by attempting to load into a temporary ctx
  21169. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  21170. if (!tmp_ctx) { return nullptr; }
  21171. int ret = wolfSSL_CTX_load_verify_buffer(
  21172. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  21173. static_cast<long>(len), SSL_FILETYPE_PEM);
  21174. wolfSSL_CTX_free(tmp_ctx);
  21175. if (ret != SSL_SUCCESS) { return nullptr; }
  21176. return static_cast<ca_store_t>(
  21177. new impl::WolfSSLCAStore{std::string(pem, len)});
  21178. }
  21179. inline void free_ca_store(ca_store_t store) {
  21180. delete static_cast<impl::WolfSSLCAStore *>(store);
  21181. }
  21182. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  21183. if (!ctx || !store) { return false; }
  21184. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21185. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  21186. int ret = wolfSSL_CTX_load_verify_buffer(
  21187. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  21188. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  21189. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  21190. // This function takes ownership of the store; the PEM data was copied into
  21191. // the context, so release the source
  21192. free_ca_store(store);
  21193. return ret == SSL_SUCCESS;
  21194. }
  21195. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  21196. certs.clear();
  21197. if (!ctx) { return 0; }
  21198. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21199. if (wctx->ca_pem_data_.empty()) { return 0; }
  21200. const std::string &pem = wctx->ca_pem_data_;
  21201. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  21202. const std::string end_marker = "-----END CERTIFICATE-----";
  21203. size_t pos = 0;
  21204. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  21205. size_t end_pos = pem.find(end_marker, pos);
  21206. if (end_pos == std::string::npos) { break; }
  21207. end_pos += end_marker.size();
  21208. std::string cert_pem = pem.substr(pos, end_pos - pos);
  21209. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  21210. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  21211. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  21212. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  21213. pos = end_pos;
  21214. }
  21215. return certs.size();
  21216. }
  21217. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  21218. std::vector<std::string> names;
  21219. if (!ctx) { return names; }
  21220. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21221. if (wctx->ca_pem_data_.empty()) { return names; }
  21222. const std::string &pem = wctx->ca_pem_data_;
  21223. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  21224. const std::string end_marker = "-----END CERTIFICATE-----";
  21225. size_t pos = 0;
  21226. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  21227. size_t end_pos = pem.find(end_marker, pos);
  21228. if (end_pos == std::string::npos) { break; }
  21229. end_pos += end_marker.size();
  21230. std::string cert_pem = pem.substr(pos, end_pos - pos);
  21231. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  21232. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  21233. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  21234. if (x509) {
  21235. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  21236. if (subject) {
  21237. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  21238. if (name_str) {
  21239. names.push_back(name_str);
  21240. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  21241. }
  21242. }
  21243. wolfSSL_X509_free(x509);
  21244. }
  21245. pos = end_pos;
  21246. }
  21247. return names;
  21248. }
  21249. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  21250. const char *key_pem, const char *password) {
  21251. if (!ctx || !cert_pem || !key_pem) { return false; }
  21252. // Try the pair on a scratch context first, so that a bad one leaves the
  21253. // server's certificate and key as they were
  21254. auto tmp = create_server_context();
  21255. if (!tmp) { return false; }
  21256. auto se = detail::scope_exit([&] { free_context(tmp); });
  21257. if (!set_client_cert_pem(tmp, cert_pem, key_pem, password)) { return false; }
  21258. return set_client_cert_pem(ctx, cert_pem, key_pem, password);
  21259. }
  21260. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  21261. if (!ctx || !ca_pem) { return false; }
  21262. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21263. // Replace the CAs rather than add to them, as the other backends do, once
  21264. // the new ones are known to load
  21265. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  21266. if (!store) { return false; }
  21267. free_ca_store(store);
  21268. wolfSSL_CTX_UnloadCAs(wctx->ctx);
  21269. wctx->ca_pem_data_.clear();
  21270. return load_ca_pem(ctx, ca_pem, strlen(ca_pem));
  21271. }
  21272. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  21273. if (!ctx) { return false; }
  21274. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21275. auto stored = callback ? std::make_shared<VerifyCallback>(std::move(callback))
  21276. : nullptr;
  21277. {
  21278. std::lock_guard<std::mutex> guard(impl::verify_callback_mutex());
  21279. // A handshake running the previous callback keeps it until it returns.
  21280. wctx->verify_callback.swap(stored);
  21281. }
  21282. impl::apply_verify_mode(*wctx);
  21283. return true;
  21284. }
  21285. inline long get_verify_error(const_session_t session) {
  21286. if (!session) { return -1; }
  21287. auto *wsession =
  21288. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  21289. return wolfSSL_get_verify_result(wsession->ssl);
  21290. }
  21291. inline std::string verify_error_string(long error_code) {
  21292. if (error_code == 0) { return ""; }
  21293. const char *str =
  21294. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  21295. return str ? std::string(str) : std::string();
  21296. }
  21297. } // namespace tls
  21298. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  21299. // WebSocket implementation
  21300. namespace ws {
  21301. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  21302. bool fin) {
  21303. std::lock_guard<std::mutex> lock(write_mutex_);
  21304. if (closed_) { return false; }
  21305. // A failed write may have sent part of the frame, whose header announces the
  21306. // whole length, so the peer would read the next frames as the rest of it.
  21307. if (!detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_)) {
  21308. closed_ = true;
  21309. return false;
  21310. }
  21311. return true;
  21312. }
  21313. // Sends this side's one Close frame and marks the connection closed. Returns
  21314. // false when it already was.
  21315. inline bool WebSocket::send_close(const std::string &payload) {
  21316. if (closed_.exchange(true)) { return false; }
  21317. ping_cv_.notify_all();
  21318. std::lock_guard<std::mutex> lock(write_mutex_);
  21319. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  21320. payload.size(), true, !is_server_);
  21321. return true;
  21322. }
  21323. inline ReadResult WebSocket::read(std::string &msg) {
  21324. // RFC 6455 Section 7.1.7: a connection failed on the peer's error is told
  21325. // why with a Close frame, and nothing more is read from it.
  21326. auto fail_with = [&](CloseStatus status) {
  21327. send_close(impl::close_payload(status));
  21328. return Fail;
  21329. };
  21330. // Answers a control frame; any other opcode here is a protocol error.
  21331. // Returns false when the connection is done.
  21332. auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
  21333. switch (op) {
  21334. case Opcode::Ping:
  21335. return send_frame(Opcode::Pong, payload.data(), payload.size());
  21336. case Opcode::Pong: {
  21337. std::lock_guard<std::mutex> lock(ping_mutex_);
  21338. unacked_pings_ = 0;
  21339. return true;
  21340. }
  21341. case Opcode::Close:
  21342. // The reply to a close() of our own, too
  21343. set_close_status(payload);
  21344. // RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
  21345. // malformed, which is answered with a protocol error instead.
  21346. send_close(impl::is_valid_close_payload(payload)
  21347. ? payload
  21348. : impl::close_payload(CloseStatus::ProtocolError));
  21349. return false;
  21350. default: fail_with(CloseStatus::ProtocolError); return false;
  21351. }
  21352. };
  21353. std::unique_lock<std::mutex> read_lock(read_mutex_);
  21354. // A server going down closes the connection rather than wait on it: its
  21355. // listen() waits for this handler to return.
  21356. auto going_away = [&]() -> ReadResult {
  21357. read_lock.unlock();
  21358. close(CloseStatus::GoingAway, "server stopping");
  21359. return Fail;
  21360. };
  21361. // close() ends the read, even while the peer keeps sending fragments
  21362. while (!closed_) {
  21363. Opcode opcode;
  21364. std::string payload;
  21365. bool fin;
  21366. // While a message is assembled, only what is left of the limit, but room
  21367. // for a control frame, which may come between its fragments.
  21368. auto max_len =
  21369. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH == 0 || message_kind_ == Fail
  21370. ? size_t(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)
  21371. : (std::max)(size_t(125), CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH -
  21372. message_.size());
  21373. auto r = frames_.read(strm_, opcode, payload, fin, is_server_, max_len);
  21374. if (r != impl::FrameRead::Ok && server_stopping()) { return going_away(); }
  21375. // A timeout leaves what was read of the frame and of the message for the
  21376. // next read(), so the connection is still usable wherever it landed: hand
  21377. // control back without closing it. That is only useful to a caller who
  21378. // asked for the timeout; the compile-time default is a backstop against a
  21379. // peer gone quiet, and elapsing it closes the connection so a plain
  21380. // `while (ws.read(msg))` loop ends. A wait that a pong timeout cut short
  21381. // finds the connection closed.
  21382. if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
  21383. return Timeout;
  21384. }
  21385. if (r == impl::FrameRead::ProtocolError) {
  21386. return fail_with(CloseStatus::ProtocolError);
  21387. }
  21388. if (r == impl::FrameRead::TooBig) {
  21389. return fail_with(CloseStatus::MessageTooBig);
  21390. }
  21391. if (r != impl::FrameRead::Ok) {
  21392. closed_ = true;
  21393. return Fail;
  21394. }
  21395. auto continues = opcode == Opcode::Continuation;
  21396. if (opcode != Opcode::Text && opcode != Opcode::Binary && !continues) {
  21397. if (handle_control(opcode, payload)) { continue; }
  21398. return Fail;
  21399. }
  21400. // RFC 6455 5.4: a message is a Text or Binary frame and the continuation
  21401. // frames after it, with only control frames between them.
  21402. if (continues == (message_kind_ == Fail)) {
  21403. return fail_with(CloseStatus::ProtocolError);
  21404. }
  21405. if (continues) {
  21406. message_ += payload;
  21407. } else {
  21408. message_ = std::move(payload);
  21409. message_kind_ = opcode == Opcode::Text ? Text : Binary;
  21410. }
  21411. if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
  21412. message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  21413. return fail_with(CloseStatus::MessageTooBig);
  21414. }
  21415. if (!fin) { continue; }
  21416. auto result = message_kind_;
  21417. msg = std::move(message_);
  21418. message_.clear();
  21419. message_kind_ = Fail;
  21420. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  21421. if (result == Text && !impl::is_valid_utf8(msg)) {
  21422. // close() takes the read lock to wait for the peer's Close reply, so
  21423. // it must not run while this thread still holds it.
  21424. read_lock.unlock();
  21425. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  21426. return Fail;
  21427. }
  21428. return result;
  21429. }
  21430. return Fail;
  21431. }
  21432. inline bool WebSocket::send(const std::string &data) {
  21433. return send_frame(Opcode::Text, data.data(), data.size());
  21434. }
  21435. inline bool WebSocket::send(const char *data, size_t len) {
  21436. return send_frame(Opcode::Binary, data, len);
  21437. }
  21438. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  21439. if (!send_close(impl::close_payload(status, reason))) { return; }
  21440. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  21441. // Close response before closing the TCP connection.
  21442. //
  21443. // Wait only when no other thread is parsing frames. When one is, it is the
  21444. // thread positioned to see the peer's reply, and reading here would take
  21445. // bytes out of the message it is assembling. Bailing out also leaves the
  21446. // stream, including its read timeout, entirely to that thread.
  21447. std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
  21448. if (!read_lock.owns_lock()) { return; }
  21449. // A max timeout turns a negative (unbounded) read timeout into 0
  21450. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  21451. strm_.set_max_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND * 1000);
  21452. // The max timeout cuts a trickled frame short, the deadline a frame flood
  21453. auto deadline =
  21454. detail::deadline_after(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  21455. // From where the last read() left the stream, inside a frame as it may be
  21456. Opcode op;
  21457. std::string resp;
  21458. bool fin;
  21459. while (std::chrono::steady_clock::now() < deadline &&
  21460. frames_.read(strm_, op, resp, fin, is_server_, 125) ==
  21461. impl::FrameRead::Ok) {
  21462. if (op == Opcode::Close) {
  21463. set_close_status(resp);
  21464. break;
  21465. }
  21466. }
  21467. }
  21468. inline WebSocket::~WebSocket() {
  21469. {
  21470. std::lock_guard<std::mutex> lock(ping_mutex_);
  21471. closed_ = true;
  21472. }
  21473. ping_cv_.notify_all();
  21474. if (ping_thread_.joinable()) { ping_thread_.join(); }
  21475. // A server's stream outlives this object
  21476. strm_.set_read_interrupt(nullptr);
  21477. }
  21478. // A pong timeout ends a read() blocked on the silent peer, and so does the
  21479. // server stopping: its listen() waits for every handler to return.
  21480. inline void WebSocket::interrupt_reads() {
  21481. auto watches_pongs = ping_interval_sec_ > 0 && max_missed_pongs_ > 0;
  21482. if (!watches_pongs && !server_stopping_) { return; }
  21483. strm_.set_read_interrupt(
  21484. [this] { return pong_timed_out_.load() || server_stopping(); });
  21485. }
  21486. inline void WebSocket::start_heartbeat() {
  21487. if (ping_interval_sec_ <= 0) { return; }
  21488. ping_thread_ = std::thread([this]() {
  21489. std::unique_lock<std::mutex> lock(ping_mutex_);
  21490. // The predicate keeps a spurious wakeup from sending a ping early
  21491. while (!ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_),
  21492. [this]() { return closed_.load(); })) {
  21493. // If the peer has failed to respond to the previous pings, give up.
  21494. // RFC 6455 does not define a pong-timeout mechanism; this is an
  21495. // opt-in liveness check controlled by max_missed_pongs_.
  21496. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  21497. lock.unlock();
  21498. close(CloseStatus::GoingAway, "pong timeout");
  21499. pong_timed_out_ = true;
  21500. return;
  21501. }
  21502. lock.unlock();
  21503. if (!send_frame(Opcode::Ping, nullptr, 0)) { return; }
  21504. lock.lock();
  21505. unacked_pings_++;
  21506. }
  21507. });
  21508. }
  21509. inline const Request &WebSocket::request() const { return req_; }
  21510. inline bool WebSocket::is_open() const { return !closed_; }
  21511. inline CloseStatus WebSocket::close_status() const { return close_status_; }
  21512. inline std::string WebSocket::close_reason() const {
  21513. return close_status_ == CloseStatus::Abnormal ? std::string() : close_reason_;
  21514. }
  21515. // Called with read_mutex_ held. Only the first Close counts.
  21516. inline void WebSocket::set_close_status(const std::string &payload) {
  21517. if (close_status_ != CloseStatus::Abnormal) { return; }
  21518. if (payload.empty()) {
  21519. close_status_ = CloseStatus::NoStatus;
  21520. } else if (impl::is_valid_close_payload(payload)) {
  21521. close_reason_ = payload.substr(2);
  21522. close_status_ = static_cast<CloseStatus>(impl::close_code(payload));
  21523. } else {
  21524. close_status_ = CloseStatus::ProtocolError;
  21525. }
  21526. }
  21527. inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
  21528. // 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
  21529. // poll(), where 0 would instead mean "return immediately", so hand it the
  21530. // negative poll uses for an unbounded wait.
  21531. if (sec == 0 && usec == 0) { sec = -1; }
  21532. strm_.set_read_timeout(sec, usec);
  21533. read_timeout_set_ = true;
  21534. }
  21535. // WebSocketClient implementation
  21536. inline WebSocketClient::WebSocketClient(
  21537. const std::string &scheme_host_port_path, const Headers &headers)
  21538. : headers_(headers) {
  21539. detail::UrlComponents uc;
  21540. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  21541. !uc.host.empty() && !uc.path.empty()) {
  21542. auto &scheme = uc.scheme;
  21543. #ifdef CPPHTTPLIB_SSL_ENABLED
  21544. if (scheme != "ws" && scheme != "wss") {
  21545. #else
  21546. if (scheme != "ws") {
  21547. #endif
  21548. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  21549. std::string msg = "'" + scheme + "' scheme is not supported.";
  21550. throw std::invalid_argument(msg);
  21551. #endif
  21552. return;
  21553. }
  21554. auto is_ssl = scheme == "wss";
  21555. host_ = std::move(uc.host);
  21556. port_ = is_ssl ? 443 : 80;
  21557. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  21558. path_ = std::move(uc.path);
  21559. if (!uc.query.empty()) { path_ += uc.query; }
  21560. #ifdef CPPHTTPLIB_SSL_ENABLED
  21561. is_ssl_ = is_ssl;
  21562. if (is_ssl_) {
  21563. // The context lives as long as the client so that CA configuration
  21564. // survives reconnects; sessions are created per connection.
  21565. tls_ctx_ = tls::create_client_context();
  21566. if (!tls_ctx_) { return; }
  21567. }
  21568. #else
  21569. if (is_ssl) { return; }
  21570. #endif
  21571. is_valid_ = true;
  21572. }
  21573. }
  21574. #ifdef CPPHTTPLIB_SSL_ENABLED
  21575. inline WebSocketClient::WebSocketClient(
  21576. const std::string &scheme_host_port_path, const PemMemory &pem,
  21577. const Headers &headers)
  21578. : WebSocketClient(scheme_host_port_path, headers) {
  21579. // For ws:// URLs the client certificate is silently ignored, consistent
  21580. // with the TLS-only setters such as set_ca_cert_path().
  21581. if (is_valid_ && is_ssl_ && pem.cert_pem && pem.key_pem) {
  21582. std::string cert_buf, key_buf;
  21583. if (!tls::set_client_cert_pem(
  21584. tls_ctx_,
  21585. detail::pem_c_str(pem.cert_pem, pem.cert_pem_len, cert_buf),
  21586. detail::pem_c_str(pem.key_pem, pem.key_pem_len, key_buf),
  21587. pem.private_key_password)) {
  21588. tls::free_context(tls_ctx_);
  21589. tls_ctx_ = nullptr;
  21590. is_valid_ = false;
  21591. }
  21592. }
  21593. }
  21594. #endif
  21595. inline WebSocketClient::~WebSocketClient() {
  21596. shutdown_and_close();
  21597. #ifdef CPPHTTPLIB_SSL_ENABLED
  21598. if (tls_ctx_) {
  21599. tls::free_context(tls_ctx_);
  21600. tls_ctx_ = nullptr;
  21601. }
  21602. #endif
  21603. }
  21604. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  21605. inline void WebSocketClient::shutdown_and_close() {
  21606. // Send the close frame while the TLS session is still alive: ws_ holds an
  21607. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  21608. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  21609. if (ws_ && ws_->is_open()) { ws_->close(); }
  21610. ws_.reset();
  21611. #ifdef CPPHTTPLIB_SSL_ENABLED
  21612. if (is_ssl_) {
  21613. if (tls_session_) {
  21614. tls::shutdown(tls_session_, true);
  21615. tls::free_session(tls_session_);
  21616. tls_session_ = nullptr;
  21617. }
  21618. }
  21619. #endif
  21620. if (sock_ != INVALID_SOCKET) {
  21621. detail::shutdown_socket(sock_);
  21622. detail::close_socket(sock_);
  21623. sock_ = INVALID_SOCKET;
  21624. }
  21625. }
  21626. // The handshakes belong to establishing the connection, so an unset read
  21627. // timeout leaves them bounded by the connection timeout instead of forever.
  21628. inline std::pair<time_t, time_t> WebSocketClient::handshake_timeout() const {
  21629. if (read_timeout_sec_ == 0 && read_timeout_usec_ == 0) {
  21630. return {connection_timeout_sec_, connection_timeout_usec_};
  21631. }
  21632. return {read_timeout_sec_, read_timeout_usec_};
  21633. }
  21634. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
  21635. Error &error, int &ssl_error,
  21636. uint64_t &ssl_backend_error) {
  21637. // A read timeout of 0 means "wait forever", the way SO_RCVTIMEO reads it.
  21638. // The streams wait with poll(), where 0 instead means "return immediately",
  21639. // so they are given the negative poll uses for an unbounded wait.
  21640. auto unbounded = read_timeout_sec_ == 0 && read_timeout_usec_ == 0;
  21641. time_t strm_read_sec = unbounded ? -1 : read_timeout_sec_;
  21642. time_t strm_read_usec = unbounded ? 0 : read_timeout_usec_;
  21643. #ifdef CPPHTTPLIB_SSL_ENABLED
  21644. if (is_ssl_) {
  21645. // A plain flag rather than SSLClient::load_certs()'s call_once: connect()
  21646. // is not safe to call concurrently on one client to begin with, since
  21647. // nothing else here is guarded either.
  21648. if (server_certificate_verification_ && !certs_loaded_) {
  21649. uint64_t backend_error = 0;
  21650. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_,
  21651. ca_cert_dir_path_, custom_ca_loaded_,
  21652. system_ca_mode_, backend_error);
  21653. certs_loaded_ = true;
  21654. }
  21655. detail::ClientTlsSessionOptions options;
  21656. options.server_hostname_verification = server_hostname_verification_;
  21657. options.session_verifier = session_verifier_;
  21658. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  21659. options.windows_cert_verification = detail::use_windows_cert_verification(
  21660. enable_windows_cert_verification_, ca_cert_file_path_,
  21661. ca_cert_dir_path_, custom_ca_loaded_, system_ca_mode_);
  21662. options.server_certificate_verifier_set = server_certificate_verifier_set_;
  21663. #endif
  21664. auto timeout = handshake_timeout();
  21665. detail::ClientTlsSessionError tls_error;
  21666. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  21667. server_certificate_verification_,
  21668. timeout.first, timeout.second,
  21669. &tls_error, options)) {
  21670. error = tls_error.error;
  21671. ssl_error = tls_error.ssl_error;
  21672. ssl_backend_error = tls_error.backend_error;
  21673. return false;
  21674. }
  21675. strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  21676. sock_, tls_session_, strm_read_sec, strm_read_usec, write_timeout_sec_,
  21677. write_timeout_usec_));
  21678. return true;
  21679. }
  21680. #else
  21681. (void)error;
  21682. (void)ssl_error;
  21683. (void)ssl_backend_error;
  21684. #endif
  21685. strm = std::unique_ptr<Stream>(
  21686. new detail::SocketStream(sock_, strm_read_sec, strm_read_usec,
  21687. write_timeout_sec_, write_timeout_usec_));
  21688. return true;
  21689. }
  21690. inline void WebSocketClient::prepare_default_headers(Request &req) {
  21691. #ifdef CPPHTTPLIB_SSL_ENABLED
  21692. auto is_ssl = is_ssl_;
  21693. #else
  21694. auto is_ssl = false;
  21695. #endif
  21696. if (!req.has_header("Host")) {
  21697. req.headers.emplace("Host", detail::make_default_host_header_value(
  21698. host_, port_, is_ssl, address_family_));
  21699. }
  21700. detail::add_default_user_agent_header(req);
  21701. detail::add_authorization_header(req, basic_auth_username_,
  21702. basic_auth_password_,
  21703. bearer_token_auth_token_, false);
  21704. }
  21705. inline Result WebSocketClient::connect() {
  21706. if (!is_valid_) { return Result{Error::Connection, -1, Headers{}}; }
  21707. shutdown_and_close();
  21708. auto error = Error::Success;
  21709. if (!create_and_connect_socket(error)) {
  21710. return Result{error, -1, Headers{}};
  21711. }
  21712. if (is_proxy_enabled()) {
  21713. Response proxy_res;
  21714. if (!connect_with_proxy(proxy_res, error)) {
  21715. shutdown_and_close();
  21716. return Result{error, proxy_res.status, std::move(proxy_res.headers)};
  21717. }
  21718. }
  21719. std::unique_ptr<Stream> strm;
  21720. auto stream_error = Error::SSLConnection;
  21721. int ssl_error = 0;
  21722. uint64_t ssl_backend_error = 0;
  21723. if (!create_stream(strm, stream_error, ssl_error, ssl_backend_error)) {
  21724. shutdown_and_close();
  21725. #ifdef CPPHTTPLIB_SSL_ENABLED
  21726. return Result{stream_error, -1, Headers{}, ssl_error, ssl_backend_error};
  21727. #else
  21728. return Result{stream_error, -1, Headers{}};
  21729. #endif
  21730. }
  21731. Request req;
  21732. req.method = "GET";
  21733. req.path = path_;
  21734. req.headers = headers_;
  21735. prepare_default_headers(req);
  21736. detail::WebSocketUpgradeResponse upgrade;
  21737. if (!detail::perform_websocket_handshake(*strm, req, upgrade)) {
  21738. shutdown_and_close();
  21739. return Result{upgrade.error, upgrade.status, std::move(upgrade.headers)};
  21740. }
  21741. subprotocol_ = std::move(upgrade.selected_subprotocol);
  21742. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  21743. websocket_ping_interval_sec_,
  21744. websocket_max_missed_pongs_));
  21745. // The stream was created with the timeout already; tell the WebSocket
  21746. // whether it came from the caller, so read() knows to report it as Timeout.
  21747. ws_->read_timeout_set_ = read_timeout_set_;
  21748. return Result{Error::Success, upgrade.status, std::move(upgrade.headers)};
  21749. }
  21750. inline ReadResult WebSocketClient::read(std::string &msg) {
  21751. if (!ws_) { return Fail; }
  21752. return ws_->read(msg);
  21753. }
  21754. inline bool WebSocketClient::send(const std::string &data) {
  21755. if (!ws_) { return false; }
  21756. return ws_->send(data);
  21757. }
  21758. inline bool WebSocketClient::send(const char *data, size_t len) {
  21759. if (!ws_) { return false; }
  21760. return ws_->send(data, len);
  21761. }
  21762. inline void WebSocketClient::close(CloseStatus status,
  21763. const std::string &reason) {
  21764. if (ws_) { ws_->close(status, reason); }
  21765. }
  21766. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  21767. inline CloseStatus WebSocketClient::close_status() const {
  21768. return ws_ ? ws_->close_status() : CloseStatus::Abnormal;
  21769. }
  21770. inline std::string WebSocketClient::close_reason() const {
  21771. return ws_ ? ws_->close_reason() : std::string();
  21772. }
  21773. inline const std::string &WebSocketClient::subprotocol() const {
  21774. return subprotocol_;
  21775. }
  21776. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  21777. read_timeout_sec_ = sec;
  21778. read_timeout_usec_ = usec;
  21779. read_timeout_set_ = true;
  21780. // The members above only seed the next connect(); read() consults the
  21781. // stream, so an already-open connection has to be told directly.
  21782. if (ws_) { ws_->set_read_timeout(sec, usec); }
  21783. }
  21784. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  21785. write_timeout_sec_ = sec;
  21786. write_timeout_usec_ = usec;
  21787. }
  21788. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  21789. websocket_ping_interval_sec_ = sec;
  21790. }
  21791. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  21792. websocket_max_missed_pongs_ = count;
  21793. }
  21794. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  21795. inline void WebSocketClient::set_address_family(int family) {
  21796. address_family_ = family;
  21797. }
  21798. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  21799. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  21800. socket_options_ = std::move(socket_options);
  21801. }
  21802. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  21803. connection_timeout_sec_ = sec;
  21804. connection_timeout_usec_ = usec;
  21805. }
  21806. inline void WebSocketClient::set_interface(const std::string &intf) {
  21807. interface_ = intf;
  21808. }
  21809. inline void WebSocketClient::set_hostname_addr_map(
  21810. std::map<std::string, std::string> addr_map) {
  21811. set_direct_hostname_addr_map(std::move(addr_map));
  21812. }
  21813. inline void WebSocketClient::set_direct_hostname_addr_map(
  21814. std::map<std::string, std::string> addr_map) {
  21815. addr_map_ = std::move(addr_map);
  21816. }
  21817. inline void WebSocketClient::set_tunnel_hostname_addr_map(
  21818. std::map<std::string, std::string> addr_map) {
  21819. tunnel_addr_map_ = std::move(addr_map);
  21820. }
  21821. inline bool WebSocketClient::is_proxy_enabled() const {
  21822. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  21823. if (no_proxy_entries_.empty()) { return true; }
  21824. return !detail::host_matches_no_proxy(detail::normalize_target(host_),
  21825. no_proxy_entries_);
  21826. }
  21827. inline bool WebSocketClient::create_and_connect_socket(Error &error) {
  21828. std::string connect_host;
  21829. std::string ip;
  21830. auto port = port_;
  21831. if (is_proxy_enabled()) {
  21832. connect_host = proxy_host_;
  21833. port = proxy_port_;
  21834. } else {
  21835. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  21836. }
  21837. sock_ = detail::create_client_socket(
  21838. connect_host, ip, port, address_family_, tcp_nodelay_, ipv6_v6only_,
  21839. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  21840. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  21841. write_timeout_usec_, interface_, error);
  21842. if (sock_ != INVALID_SOCKET) { return true; }
  21843. if (error == Error::Success) { error = Error::Connection; }
  21844. return false;
  21845. }
  21846. inline bool WebSocketClient::send_proxy_connect(Request &req,
  21847. Response &proxy_res,
  21848. Error &error) {
  21849. auto timeout = handshake_timeout();
  21850. detail::SocketStream strm(sock_, timeout.first, timeout.second,
  21851. write_timeout_sec_, write_timeout_usec_);
  21852. if (!detail::write_request_head(strm, req, error)) { return false; }
  21853. if (!detail::read_response_head(strm, proxy_res.status, proxy_res.headers)) {
  21854. error = Error::Read;
  21855. return false;
  21856. }
  21857. return true;
  21858. }
  21859. // RFC 6455 4.1: ws:// is tunnelled with CONNECT as well, since a proxy need not
  21860. // forward an Upgrade request.
  21861. inline bool WebSocketClient::connect_with_proxy(Response &proxy_res,
  21862. Error &error) {
  21863. Request req;
  21864. req.method = "CONNECT";
  21865. req.path =
  21866. detail::make_connect_request_target(tunnel_addr_map_, host_, port_);
  21867. req.headers.emplace("Host", req.path);
  21868. detail::add_default_user_agent_header(req);
  21869. detail::add_authorization_header(req, proxy_basic_auth_username_,
  21870. proxy_basic_auth_password_,
  21871. proxy_bearer_token_auth_token_, true);
  21872. if (!send_proxy_connect(req, proxy_res, error)) { return false; }
  21873. #ifdef CPPHTTPLIB_SSL_ENABLED
  21874. // A Digest challenge gets one retry on a fresh connection, like SSLClient.
  21875. std::map<std::string, std::string> auth;
  21876. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407 &&
  21877. !proxy_digest_auth_username_.empty() &&
  21878. !proxy_digest_auth_password_.empty() &&
  21879. detail::parse_www_authenticate(proxy_res, auth, true)) {
  21880. proxy_res = Response();
  21881. shutdown_and_close();
  21882. if (!create_and_connect_socket(error)) { return false; }
  21883. req.headers.erase("Proxy-Authorization");
  21884. req.headers.insert(detail::make_digest_authentication_header(
  21885. req, req.path, auth, 1, detail::random_string(10),
  21886. proxy_digest_auth_username_, proxy_digest_auth_password_, true));
  21887. if (!send_proxy_connect(req, proxy_res, error)) { return false; }
  21888. }
  21889. #endif
  21890. if (proxy_res.status != StatusCode::OK_200) {
  21891. error = Error::ProxyConnection;
  21892. return false;
  21893. }
  21894. return true;
  21895. }
  21896. inline void WebSocketClient::set_basic_auth(const std::string &username,
  21897. const std::string &password) {
  21898. basic_auth_username_ = username;
  21899. basic_auth_password_ = password;
  21900. }
  21901. inline void WebSocketClient::set_bearer_token_auth(const std::string &token) {
  21902. bearer_token_auth_token_ = token;
  21903. }
  21904. inline void WebSocketClient::set_proxy(const std::string &host, int port) {
  21905. proxy_host_ = host;
  21906. proxy_port_ = port;
  21907. }
  21908. inline void WebSocketClient::set_proxy_basic_auth(const std::string &username,
  21909. const std::string &password) {
  21910. proxy_basic_auth_username_ = username;
  21911. proxy_basic_auth_password_ = password;
  21912. }
  21913. inline void
  21914. WebSocketClient::set_proxy_bearer_token_auth(const std::string &token) {
  21915. proxy_bearer_token_auth_token_ = token;
  21916. }
  21917. inline void
  21918. WebSocketClient::set_no_proxy(const std::vector<std::string> &patterns) {
  21919. no_proxy_entries_ = detail::parse_no_proxy_entries(patterns);
  21920. }
  21921. #ifdef CPPHTTPLIB_SSL_ENABLED
  21922. inline void
  21923. WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,
  21924. const std::string &ca_cert_dir_path) {
  21925. ca_cert_file_path_ = ca_cert_file_path;
  21926. ca_cert_dir_path_ = ca_cert_dir_path;
  21927. }
  21928. inline void
  21929. WebSocketClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  21930. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  21931. server_certificate_verifier_set_ = static_cast<bool>(verifier);
  21932. #endif
  21933. if (tls_ctx_) { tls::set_verify_callback(tls_ctx_, std::move(verifier)); }
  21934. }
  21935. inline void WebSocketClient::set_session_verifier(
  21936. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  21937. session_verifier_ = std::move(verifier);
  21938. }
  21939. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  21940. if (store && tls_ctx_) {
  21941. // set_ca_store takes ownership of store
  21942. tls::set_ca_store(tls_ctx_, store);
  21943. } else if (store) {
  21944. tls::free_ca_store(store);
  21945. }
  21946. custom_ca_loaded_ = true;
  21947. }
  21948. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  21949. std::size_t size) {
  21950. if (tls_ctx_ && ca_cert && size > 0) {
  21951. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  21952. }
  21953. custom_ca_loaded_ = true;
  21954. }
  21955. inline void
  21956. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  21957. server_certificate_verification_ = enabled;
  21958. }
  21959. inline void WebSocketClient::enable_server_hostname_verification(bool enabled) {
  21960. server_hostname_verification_ = enabled;
  21961. }
  21962. inline void WebSocketClient::enable_system_ca(bool enabled) {
  21963. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  21964. }
  21965. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  21966. inline void
  21967. WebSocketClient::enable_windows_certificate_verification(bool enabled) {
  21968. enable_windows_cert_verification_ = enabled;
  21969. }
  21970. #endif
  21971. inline void
  21972. WebSocketClient::set_proxy_digest_auth(const std::string &username,
  21973. const std::string &password) {
  21974. proxy_digest_auth_username_ = username;
  21975. proxy_digest_auth_password_ = password;
  21976. }
  21977. #endif // CPPHTTPLIB_SSL_ENABLED
  21978. } // namespace ws
  21979. // ----------------------------------------------------------------------------
  21980. } // namespace httplib
  21981. #endif // CPPHTTPLIB_HTTPLIB_H