httplib.h 668 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320
  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.39.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x002700"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. /*
  160. * Headers
  161. */
  162. #ifdef _WIN32
  163. #ifndef _CRT_SECURE_NO_WARNINGS
  164. #define _CRT_SECURE_NO_WARNINGS
  165. #endif //_CRT_SECURE_NO_WARNINGS
  166. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  167. #define _CRT_NONSTDC_NO_DEPRECATE
  168. #endif //_CRT_NONSTDC_NO_DEPRECATE
  169. #if defined(_MSC_VER)
  170. #if _MSC_VER < 1900
  171. #error Sorry, Visual Studio versions prior to 2015 are not supported
  172. #endif
  173. #pragma comment(lib, "ws2_32.lib")
  174. #ifndef _SSIZE_T_DEFINED
  175. using ssize_t = __int64;
  176. #define _SSIZE_T_DEFINED
  177. #endif
  178. #endif // _MSC_VER
  179. #ifndef S_ISREG
  180. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  181. #endif // S_ISREG
  182. #ifndef S_ISDIR
  183. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  184. #endif // S_ISDIR
  185. #ifndef NOMINMAX
  186. #define NOMINMAX
  187. #endif // NOMINMAX
  188. #include <io.h>
  189. #include <winsock2.h>
  190. #include <ws2tcpip.h>
  191. #if defined(__has_include)
  192. #if __has_include(<afunix.h>)
  193. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  194. #include <afunix.h>
  195. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  196. #endif
  197. #endif
  198. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  199. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  200. #endif
  201. using nfds_t = unsigned long;
  202. using socket_t = SOCKET;
  203. using socklen_t = int;
  204. #else // not _WIN32
  205. #include <arpa/inet.h>
  206. #if !defined(_AIX) && !defined(__MVS__)
  207. #include <ifaddrs.h>
  208. #endif
  209. #ifdef __MVS__
  210. #include <strings.h>
  211. #ifndef NI_MAXHOST
  212. #define NI_MAXHOST 1025
  213. #endif
  214. #endif
  215. #include <net/if.h>
  216. #include <netdb.h>
  217. #include <netinet/in.h>
  218. #ifdef __linux__
  219. #include <resolv.h>
  220. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  221. #endif
  222. #include <csignal>
  223. #include <netinet/tcp.h>
  224. #include <poll.h>
  225. #include <pthread.h>
  226. #include <sys/mman.h>
  227. #include <sys/socket.h>
  228. #include <sys/un.h>
  229. #include <unistd.h>
  230. using socket_t = int;
  231. #ifndef INVALID_SOCKET
  232. #define INVALID_SOCKET (-1)
  233. #endif
  234. #endif //_WIN32
  235. #if defined(__APPLE__)
  236. #include <TargetConditionals.h>
  237. #endif
  238. #include <algorithm>
  239. #include <array>
  240. #include <atomic>
  241. #include <cassert>
  242. #include <cctype>
  243. #include <chrono>
  244. #include <climits>
  245. #include <condition_variable>
  246. #include <cstdlib>
  247. #include <cstring>
  248. #include <errno.h>
  249. #include <exception>
  250. #include <fcntl.h>
  251. #include <fstream>
  252. #include <functional>
  253. #include <iomanip>
  254. #include <iostream>
  255. #include <list>
  256. #include <map>
  257. #include <memory>
  258. #include <mutex>
  259. #include <random>
  260. #include <regex>
  261. #include <set>
  262. #include <sstream>
  263. #include <string>
  264. #include <sys/stat.h>
  265. #include <system_error>
  266. #include <thread>
  267. #include <unordered_map>
  268. #include <unordered_set>
  269. #include <utility>
  270. #if __cplusplus >= 201703L
  271. #include <any>
  272. #endif
  273. // On macOS with a TLS backend, enable Keychain root certificates by default
  274. // unless the user explicitly opts out.
  275. #if defined(__APPLE__) && \
  276. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  277. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  278. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  279. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  280. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  281. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  282. #endif
  283. #endif
  284. // On Windows, enable Schannel certificate verification by default
  285. // unless the user explicitly opts out.
  286. #if defined(_WIN32) && \
  287. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  288. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  289. #endif
  290. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  291. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  292. #if TARGET_OS_MAC
  293. #include <CFNetwork/CFHost.h>
  294. #include <CoreFoundation/CoreFoundation.h>
  295. #endif
  296. #endif
  297. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  298. #ifdef _WIN32
  299. #include <wincrypt.h>
  300. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  301. // used
  302. #undef X509_NAME
  303. #undef X509_CERT_PAIR
  304. #undef X509_EXTENSIONS
  305. #undef PKCS7_SIGNER_INFO
  306. #ifdef _MSC_VER
  307. #pragma comment(lib, "crypt32.lib")
  308. #endif
  309. #endif // _WIN32
  310. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  311. #if TARGET_OS_MAC
  312. #include <Security/Security.h>
  313. #endif
  314. #endif
  315. #include <openssl/err.h>
  316. #include <openssl/evp.h>
  317. #include <openssl/ssl.h>
  318. #include <openssl/x509v3.h>
  319. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  320. #include <openssl/applink.c>
  321. #endif
  322. #include <iostream>
  323. #include <sstream>
  324. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  325. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  326. #error Please use OpenSSL or a current version of BoringSSL
  327. #endif
  328. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  329. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  330. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  331. #endif
  332. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  333. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  334. #include <mbedtls/ctr_drbg.h>
  335. #include <mbedtls/entropy.h>
  336. #include <mbedtls/error.h>
  337. #include <mbedtls/md5.h>
  338. #include <mbedtls/net_sockets.h>
  339. #include <mbedtls/oid.h>
  340. #include <mbedtls/pk.h>
  341. #include <mbedtls/sha1.h>
  342. #include <mbedtls/sha256.h>
  343. #include <mbedtls/sha512.h>
  344. #include <mbedtls/ssl.h>
  345. #include <mbedtls/x509_crt.h>
  346. #ifdef _WIN32
  347. #include <wincrypt.h>
  348. #ifdef _MSC_VER
  349. #pragma comment(lib, "crypt32.lib")
  350. #endif
  351. #endif // _WIN32
  352. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  353. #if TARGET_OS_MAC
  354. #include <Security/Security.h>
  355. #endif
  356. #endif
  357. // Mbed TLS 3.x API compatibility
  358. #if MBEDTLS_VERSION_MAJOR >= 3
  359. #define CPPHTTPLIB_MBEDTLS_V3
  360. #endif
  361. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  362. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  363. #include <wolfssl/options.h>
  364. #include <wolfssl/openssl/x509v3.h>
  365. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  366. #ifndef WOLFSSL_GEN_EMAIL
  367. #define WOLFSSL_GEN_EMAIL 1
  368. #endif
  369. #ifndef WOLFSSL_GEN_DNS
  370. #define WOLFSSL_GEN_DNS 2
  371. #endif
  372. #ifndef WOLFSSL_GEN_URI
  373. #define WOLFSSL_GEN_URI 6
  374. #endif
  375. #ifndef WOLFSSL_GEN_IPADD
  376. #define WOLFSSL_GEN_IPADD 7
  377. #endif
  378. #include <wolfssl/ssl.h>
  379. #include <wolfssl/wolfcrypt/hash.h>
  380. #include <wolfssl/wolfcrypt/md5.h>
  381. #include <wolfssl/wolfcrypt/sha256.h>
  382. #include <wolfssl/wolfcrypt/sha512.h>
  383. #ifdef _WIN32
  384. #include <wincrypt.h>
  385. #ifdef _MSC_VER
  386. #pragma comment(lib, "crypt32.lib")
  387. #endif
  388. #endif // _WIN32
  389. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  390. #if TARGET_OS_MAC
  391. #include <Security/Security.h>
  392. #endif
  393. #endif
  394. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  395. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  396. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  397. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  398. #define CPPHTTPLIB_SSL_ENABLED
  399. #endif
  400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  401. #include <zlib.h>
  402. #endif
  403. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  404. #include <brotli/decode.h>
  405. #include <brotli/encode.h>
  406. #endif
  407. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  408. #include <zstd.h>
  409. #endif
  410. /*
  411. * Declaration
  412. */
  413. namespace httplib {
  414. namespace ws {
  415. class WebSocket;
  416. } // namespace ws
  417. namespace detail {
  418. /*
  419. * Backport std::make_unique from C++14.
  420. *
  421. * NOTE: This code came up with the following stackoverflow post:
  422. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  423. *
  424. */
  425. template <class T, class... Args>
  426. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  427. make_unique(Args &&...args) {
  428. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  429. }
  430. template <class T>
  431. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  432. make_unique(std::size_t n) {
  433. typedef typename std::remove_extent<T>::type RT;
  434. return std::unique_ptr<T>(new RT[n]);
  435. }
  436. namespace case_ignore {
  437. inline unsigned char to_lower(int c) {
  438. const static unsigned char table[256] = {
  439. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  440. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  441. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  442. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  443. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  444. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  445. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  446. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  447. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  448. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  449. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  450. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  451. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  452. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  453. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  454. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  455. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  456. 255,
  457. };
  458. return table[(unsigned char)(char)c];
  459. }
  460. inline std::string to_lower(const std::string &s) {
  461. std::string result = s;
  462. std::transform(
  463. result.begin(), result.end(), result.begin(),
  464. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  465. return result;
  466. }
  467. inline bool equal(const std::string &a, const std::string &b) {
  468. return a.size() == b.size() &&
  469. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  470. return to_lower(ca) == to_lower(cb);
  471. });
  472. }
  473. struct equal_to {
  474. bool operator()(const std::string &a, const std::string &b) const {
  475. return equal(a, b);
  476. }
  477. };
  478. struct hash {
  479. size_t operator()(const std::string &key) const {
  480. return hash_core(key.data(), key.size(), 0);
  481. }
  482. size_t hash_core(const char *s, size_t l, size_t h) const {
  483. return (l == 0) ? h
  484. : hash_core(s + 1, l - 1,
  485. // Unsets the 6 high bits of h, therefore no
  486. // overflow happens
  487. (((std::numeric_limits<size_t>::max)() >> 6) &
  488. h * 33) ^
  489. static_cast<unsigned char>(to_lower(*s)));
  490. }
  491. };
  492. template <typename T>
  493. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  494. detail::case_ignore::equal_to>;
  495. } // namespace case_ignore
  496. // This is based on
  497. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  498. struct scope_exit {
  499. explicit scope_exit(std::function<void(void)> &&f)
  500. : exit_function(std::move(f)), execute_on_destruction{true} {}
  501. scope_exit(scope_exit &&rhs) noexcept
  502. : exit_function(std::move(rhs.exit_function)),
  503. execute_on_destruction{rhs.execute_on_destruction} {
  504. rhs.release();
  505. }
  506. ~scope_exit() {
  507. if (execute_on_destruction) { this->exit_function(); }
  508. }
  509. void release() { this->execute_on_destruction = false; }
  510. private:
  511. scope_exit(const scope_exit &) = delete;
  512. void operator=(const scope_exit &) = delete;
  513. scope_exit &operator=(scope_exit &&) = delete;
  514. std::function<void(void)> exit_function;
  515. bool execute_on_destruction;
  516. };
  517. // Simple from_chars implementation for integer and double types (C++17
  518. // substitute)
  519. template <typename T> struct from_chars_result {
  520. const char *ptr;
  521. std::errc ec;
  522. };
  523. template <typename T>
  524. inline from_chars_result<T> from_chars(const char *first, const char *last,
  525. T &value, int base = 10) {
  526. value = 0;
  527. const char *p = first;
  528. bool negative = false;
  529. if (p != last && *p == '-') {
  530. negative = true;
  531. ++p;
  532. }
  533. if (p == last) { return {first, std::errc::invalid_argument}; }
  534. T result = 0;
  535. for (; p != last; ++p) {
  536. char c = *p;
  537. int digit = -1;
  538. if ('0' <= c && c <= '9') {
  539. digit = c - '0';
  540. } else if ('a' <= c && c <= 'z') {
  541. digit = c - 'a' + 10;
  542. } else if ('A' <= c && c <= 'Z') {
  543. digit = c - 'A' + 10;
  544. } else {
  545. break;
  546. }
  547. if (digit < 0 || digit >= base) { break; }
  548. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  549. return {p, std::errc::result_out_of_range};
  550. }
  551. result = result * base + digit;
  552. }
  553. if (p == first || (negative && p == first + 1)) {
  554. return {first, std::errc::invalid_argument};
  555. }
  556. value = negative ? -result : result;
  557. return {p, std::errc{}};
  558. }
  559. // from_chars for double (simple wrapper for strtod)
  560. inline from_chars_result<double> from_chars(const char *first, const char *last,
  561. double &value) {
  562. std::string s(first, last);
  563. char *endptr = nullptr;
  564. errno = 0;
  565. value = std::strtod(s.c_str(), &endptr);
  566. if (endptr == s.c_str()) { return {first, std::errc::invalid_argument}; }
  567. if (errno == ERANGE) {
  568. return {first + (endptr - s.c_str()), std::errc::result_out_of_range};
  569. }
  570. return {first + (endptr - s.c_str()), std::errc{}};
  571. }
  572. inline bool parse_port(const char *s, size_t len, int &port) {
  573. int val = 0;
  574. auto r = from_chars(s, s + len, val);
  575. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  576. port = val;
  577. return true;
  578. }
  579. inline bool parse_port(const std::string &s, int &port) {
  580. return parse_port(s.data(), s.size(), port);
  581. }
  582. } // namespace detail
  583. enum SSLVerifierResponse {
  584. // no decision has been made, use the built-in certificate verifier
  585. NoDecisionMade,
  586. // connection certificate is verified and accepted
  587. CertificateAccepted,
  588. // connection certificate was processed but is rejected
  589. CertificateRejected
  590. };
  591. enum StatusCode {
  592. // Information responses
  593. Continue_100 = 100,
  594. SwitchingProtocol_101 = 101,
  595. Processing_102 = 102,
  596. EarlyHints_103 = 103,
  597. // Successful responses
  598. OK_200 = 200,
  599. Created_201 = 201,
  600. Accepted_202 = 202,
  601. NonAuthoritativeInformation_203 = 203,
  602. NoContent_204 = 204,
  603. ResetContent_205 = 205,
  604. PartialContent_206 = 206,
  605. MultiStatus_207 = 207,
  606. AlreadyReported_208 = 208,
  607. IMUsed_226 = 226,
  608. // Redirection messages
  609. MultipleChoices_300 = 300,
  610. MovedPermanently_301 = 301,
  611. Found_302 = 302,
  612. SeeOther_303 = 303,
  613. NotModified_304 = 304,
  614. UseProxy_305 = 305,
  615. unused_306 = 306,
  616. TemporaryRedirect_307 = 307,
  617. PermanentRedirect_308 = 308,
  618. // Client error responses
  619. BadRequest_400 = 400,
  620. Unauthorized_401 = 401,
  621. PaymentRequired_402 = 402,
  622. Forbidden_403 = 403,
  623. NotFound_404 = 404,
  624. MethodNotAllowed_405 = 405,
  625. NotAcceptable_406 = 406,
  626. ProxyAuthenticationRequired_407 = 407,
  627. RequestTimeout_408 = 408,
  628. Conflict_409 = 409,
  629. Gone_410 = 410,
  630. LengthRequired_411 = 411,
  631. PreconditionFailed_412 = 412,
  632. PayloadTooLarge_413 = 413,
  633. UriTooLong_414 = 414,
  634. UnsupportedMediaType_415 = 415,
  635. RangeNotSatisfiable_416 = 416,
  636. ExpectationFailed_417 = 417,
  637. ImATeapot_418 = 418,
  638. MisdirectedRequest_421 = 421,
  639. UnprocessableContent_422 = 422,
  640. Locked_423 = 423,
  641. FailedDependency_424 = 424,
  642. TooEarly_425 = 425,
  643. UpgradeRequired_426 = 426,
  644. PreconditionRequired_428 = 428,
  645. TooManyRequests_429 = 429,
  646. RequestHeaderFieldsTooLarge_431 = 431,
  647. UnavailableForLegalReasons_451 = 451,
  648. // Server error responses
  649. InternalServerError_500 = 500,
  650. NotImplemented_501 = 501,
  651. BadGateway_502 = 502,
  652. ServiceUnavailable_503 = 503,
  653. GatewayTimeout_504 = 504,
  654. HttpVersionNotSupported_505 = 505,
  655. VariantAlsoNegotiates_506 = 506,
  656. InsufficientStorage_507 = 507,
  657. LoopDetected_508 = 508,
  658. NotExtended_510 = 510,
  659. NetworkAuthenticationRequired_511 = 511,
  660. };
  661. using Headers =
  662. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  663. detail::case_ignore::equal_to>;
  664. using Params = std::multimap<std::string, std::string>;
  665. using Match = std::smatch;
  666. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  667. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  668. // ----------------------------------------------------------------------------
  669. // httplib::any — type-erased value container (C++11 compatible)
  670. // On C++17+ builds, thin wrappers around std::any are provided.
  671. // ----------------------------------------------------------------------------
  672. #if __cplusplus >= 201703L
  673. using any = std::any;
  674. using bad_any_cast = std::bad_any_cast;
  675. template <typename T> T any_cast(const any &a) { return std::any_cast<T>(a); }
  676. template <typename T> T any_cast(any &a) { return std::any_cast<T>(a); }
  677. template <typename T> T any_cast(any &&a) {
  678. return std::any_cast<T>(std::move(a));
  679. }
  680. template <typename T> const T *any_cast(const any *a) noexcept {
  681. return std::any_cast<T>(a);
  682. }
  683. template <typename T> T *any_cast(any *a) noexcept {
  684. return std::any_cast<T>(a);
  685. }
  686. #else // C++11/14 implementation
  687. class bad_any_cast : public std::bad_cast {
  688. public:
  689. const char *what() const noexcept override { return "bad any_cast"; }
  690. };
  691. namespace detail {
  692. using any_type_id = const void *;
  693. // Returns a unique per-type ID without RTTI.
  694. // The static address is stable across TUs because function templates are
  695. // implicitly inline and the ODR merges their statics into one.
  696. template <typename T> any_type_id any_typeid() noexcept {
  697. static const char id = 0;
  698. return &id;
  699. }
  700. struct any_storage {
  701. virtual ~any_storage() = default;
  702. virtual std::unique_ptr<any_storage> clone() const = 0;
  703. virtual any_type_id type_id() const noexcept = 0;
  704. };
  705. template <typename T> struct any_value final : any_storage {
  706. T value;
  707. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  708. std::unique_ptr<any_storage> clone() const override {
  709. return std::unique_ptr<any_storage>(new any_value<T>(value));
  710. }
  711. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  712. };
  713. } // namespace detail
  714. class any {
  715. std::unique_ptr<detail::any_storage> storage_;
  716. public:
  717. any() noexcept = default;
  718. any(const any &o) : storage_(o.storage_ ? o.storage_->clone() : nullptr) {}
  719. any(any &&) noexcept = default;
  720. any &operator=(const any &o) {
  721. storage_ = o.storage_ ? o.storage_->clone() : nullptr;
  722. return *this;
  723. }
  724. any &operator=(any &&) noexcept = default;
  725. template <
  726. typename T, typename D = typename std::decay<T>::type,
  727. typename std::enable_if<!std::is_same<D, any>::value, int>::type = 0>
  728. any(T &&v) : storage_(new detail::any_value<D>(std::forward<T>(v))) {}
  729. template <
  730. typename T, typename D = typename std::decay<T>::type,
  731. typename std::enable_if<!std::is_same<D, any>::value, int>::type = 0>
  732. any &operator=(T &&v) {
  733. storage_.reset(new detail::any_value<D>(std::forward<T>(v)));
  734. return *this;
  735. }
  736. bool has_value() const noexcept { return storage_ != nullptr; }
  737. void reset() noexcept { storage_.reset(); }
  738. template <typename T> friend T *any_cast(any *a) noexcept;
  739. template <typename T> friend const T *any_cast(const any *a) noexcept;
  740. };
  741. template <typename T> T *any_cast(any *a) noexcept {
  742. if (!a || !a->storage_) { return nullptr; }
  743. if (a->storage_->type_id() != detail::any_typeid<T>()) { return nullptr; }
  744. return &static_cast<detail::any_value<T> *>(a->storage_.get())->value;
  745. }
  746. template <typename T> const T *any_cast(const any *a) noexcept {
  747. if (!a || !a->storage_) { return nullptr; }
  748. if (a->storage_->type_id() != detail::any_typeid<T>()) { return nullptr; }
  749. return &static_cast<const detail::any_value<T> *>(a->storage_.get())->value;
  750. }
  751. template <typename T> T any_cast(const any &a) {
  752. using U =
  753. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  754. const U *p = any_cast<U>(&a);
  755. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  756. if (!p) { throw bad_any_cast{}; }
  757. #else
  758. if (!p) { std::abort(); }
  759. #endif
  760. return static_cast<T>(*p);
  761. }
  762. template <typename T> T any_cast(any &a) {
  763. using U =
  764. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  765. U *p = any_cast<U>(&a);
  766. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  767. if (!p) { throw bad_any_cast{}; }
  768. #else
  769. if (!p) { std::abort(); }
  770. #endif
  771. return static_cast<T>(*p);
  772. }
  773. template <typename T> T any_cast(any &&a) {
  774. using U =
  775. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  776. U *p = any_cast<U>(&a);
  777. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  778. if (!p) { throw bad_any_cast{}; }
  779. #else
  780. if (!p) { std::abort(); }
  781. #endif
  782. return static_cast<T>(std::move(*p));
  783. }
  784. #endif // __cplusplus >= 201703L
  785. struct Response;
  786. using ResponseHandler = std::function<bool(const Response &response)>;
  787. struct FormData {
  788. std::string name;
  789. std::string content;
  790. std::string filename;
  791. std::string content_type;
  792. Headers headers;
  793. };
  794. struct FormField {
  795. std::string name;
  796. std::string content;
  797. Headers headers;
  798. };
  799. using FormFields = std::multimap<std::string, FormField>;
  800. using FormFiles = std::multimap<std::string, FormData>;
  801. struct MultipartFormData {
  802. FormFields fields; // Text fields from multipart
  803. FormFiles files; // Files from multipart
  804. // Text field access
  805. std::string get_field(const std::string &key, size_t id = 0) const;
  806. std::vector<std::string> get_fields(const std::string &key) const;
  807. bool has_field(const std::string &key) const;
  808. size_t get_field_count(const std::string &key) const;
  809. // File access
  810. FormData get_file(const std::string &key, size_t id = 0) const;
  811. std::vector<FormData> get_files(const std::string &key) const;
  812. bool has_file(const std::string &key) const;
  813. size_t get_file_count(const std::string &key) const;
  814. };
  815. struct UploadFormData {
  816. std::string name;
  817. std::string content;
  818. std::string filename;
  819. std::string content_type;
  820. };
  821. using UploadFormDataItems = std::vector<UploadFormData>;
  822. class DataSink {
  823. public:
  824. DataSink() : os(&sb_), sb_(*this) {}
  825. DataSink(const DataSink &) = delete;
  826. DataSink &operator=(const DataSink &) = delete;
  827. DataSink(DataSink &&) = delete;
  828. DataSink &operator=(DataSink &&) = delete;
  829. std::function<bool(const char *data, size_t data_len)> write;
  830. std::function<bool()> is_writable;
  831. std::function<void()> done;
  832. std::function<void(const Headers &trailer)> done_with_trailer;
  833. std::ostream os;
  834. private:
  835. class data_sink_streambuf final : public std::streambuf {
  836. public:
  837. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  838. protected:
  839. std::streamsize xsputn(const char *s, std::streamsize n) override {
  840. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  841. return 0;
  842. }
  843. private:
  844. DataSink &sink_;
  845. };
  846. data_sink_streambuf sb_;
  847. };
  848. using ContentProvider =
  849. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  850. using ContentProviderWithoutLength =
  851. std::function<bool(size_t offset, DataSink &sink)>;
  852. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  853. struct FormDataProvider {
  854. std::string name;
  855. ContentProviderWithoutLength provider;
  856. std::string filename;
  857. std::string content_type;
  858. };
  859. using FormDataProviderItems = std::vector<FormDataProvider>;
  860. inline FormDataProvider
  861. make_file_provider(const std::string &name, const std::string &filepath,
  862. const std::string &filename = std::string(),
  863. const std::string &content_type = std::string()) {
  864. FormDataProvider fdp;
  865. fdp.name = name;
  866. fdp.filename = filename.empty() ? filepath : filename;
  867. fdp.content_type = content_type;
  868. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  869. std::ifstream f(filepath, std::ios::binary);
  870. if (!f) { return false; }
  871. if (offset > 0) {
  872. f.seekg(static_cast<std::streamoff>(offset));
  873. if (!f.good()) {
  874. sink.done();
  875. return true;
  876. }
  877. }
  878. char buf[8192];
  879. f.read(buf, sizeof(buf));
  880. auto n = static_cast<size_t>(f.gcount());
  881. if (n > 0) { return sink.write(buf, n); }
  882. sink.done(); // EOF
  883. return true;
  884. };
  885. return fdp;
  886. }
  887. inline std::pair<size_t, ContentProvider>
  888. make_file_body(const std::string &filepath) {
  889. size_t size = 0;
  890. {
  891. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  892. if (!f) { return {0, ContentProvider{}}; }
  893. size = static_cast<size_t>(f.tellg());
  894. }
  895. ContentProvider provider = [filepath](size_t offset, size_t length,
  896. DataSink &sink) -> bool {
  897. std::ifstream f(filepath, std::ios::binary);
  898. if (!f) { return false; }
  899. f.seekg(static_cast<std::streamoff>(offset));
  900. if (!f.good()) { return false; }
  901. char buf[8192];
  902. while (length > 0) {
  903. auto to_read = (std::min)(sizeof(buf), length);
  904. f.read(buf, static_cast<std::streamsize>(to_read));
  905. auto n = static_cast<size_t>(f.gcount());
  906. if (n == 0) { break; }
  907. if (!sink.write(buf, n)) { return false; }
  908. length -= n;
  909. }
  910. return true;
  911. };
  912. return {size, std::move(provider)};
  913. }
  914. using ContentReceiverWithProgress = std::function<bool(
  915. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  916. using ContentReceiver =
  917. std::function<bool(const char *data, size_t data_length)>;
  918. using FormDataHeader = std::function<bool(const FormData &file)>;
  919. class ContentReader {
  920. public:
  921. using Reader = std::function<bool(ContentReceiver receiver)>;
  922. using FormDataReader =
  923. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  924. ContentReader(Reader reader, FormDataReader multipart_reader)
  925. : reader_(std::move(reader)),
  926. formdata_reader_(std::move(multipart_reader)) {}
  927. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  928. return formdata_reader_(std::move(header), std::move(receiver));
  929. }
  930. bool operator()(ContentReceiver receiver) const {
  931. return reader_(std::move(receiver));
  932. }
  933. Reader reader_;
  934. FormDataReader formdata_reader_;
  935. };
  936. using Range = std::pair<ssize_t, ssize_t>;
  937. using Ranges = std::vector<Range>;
  938. #ifdef CPPHTTPLIB_SSL_ENABLED
  939. // TLS abstraction layer - public type definitions and API
  940. namespace tls {
  941. // Opaque handles (defined as void* for abstraction)
  942. using ctx_t = void *;
  943. using session_t = void *;
  944. using const_session_t = const void *; // For read-only session access
  945. using cert_t = void *;
  946. using ca_store_t = void *;
  947. // TLS versions
  948. enum class Version {
  949. TLS1_2 = 0x0303,
  950. TLS1_3 = 0x0304,
  951. };
  952. // Subject Alternative Names (SAN) entry types
  953. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  954. // SAN entry structure
  955. struct SanEntry {
  956. SanType type;
  957. std::string value;
  958. };
  959. // Verification context for certificate verification callback
  960. struct VerifyContext {
  961. session_t session; // TLS session handle
  962. cert_t cert; // Current certificate being verified
  963. int depth; // Certificate chain depth (0 = leaf)
  964. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  965. long error_code; // Backend-specific error code (0 = no error)
  966. const char *error_string; // Human-readable error description
  967. // Certificate introspection methods
  968. std::string subject_cn() const;
  969. std::string issuer_name() const;
  970. bool check_hostname(const char *hostname) const;
  971. std::vector<SanEntry> sans() const;
  972. bool validity(time_t &not_before, time_t &not_after) const;
  973. std::string serial() const;
  974. };
  975. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  976. // TlsError codes for TLS operations (backend-independent)
  977. enum class ErrorCode : int {
  978. Success = 0,
  979. WantRead, // Non-blocking: need to wait for read
  980. WantWrite, // Non-blocking: need to wait for write
  981. PeerClosed, // Peer closed the connection
  982. Fatal, // Unrecoverable error
  983. SyscallError, // System call error (check sys_errno)
  984. CertVerifyFailed, // Certificate verification failed
  985. HostnameMismatch, // Hostname verification failed
  986. };
  987. // TLS error information
  988. struct TlsError {
  989. ErrorCode code = ErrorCode::Fatal;
  990. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  991. int sys_errno = 0; // errno when SyscallError
  992. // Convert verification error code to human-readable string
  993. static std::string verify_error_to_string(long error_code);
  994. };
  995. // RAII wrapper for peer certificate
  996. class PeerCert {
  997. public:
  998. PeerCert();
  999. PeerCert(PeerCert &&other) noexcept;
  1000. PeerCert &operator=(PeerCert &&other) noexcept;
  1001. ~PeerCert();
  1002. PeerCert(const PeerCert &) = delete;
  1003. PeerCert &operator=(const PeerCert &) = delete;
  1004. explicit operator bool() const;
  1005. std::string subject_cn() const;
  1006. std::string issuer_name() const;
  1007. bool check_hostname(const char *hostname) const;
  1008. std::vector<SanEntry> sans() const;
  1009. bool validity(time_t &not_before, time_t &not_after) const;
  1010. std::string serial() const;
  1011. private:
  1012. explicit PeerCert(cert_t cert);
  1013. cert_t cert_ = nullptr;
  1014. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1015. };
  1016. // Callback for TLS context setup (used by SSLServer constructor)
  1017. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1018. } // namespace tls
  1019. #endif
  1020. struct Request {
  1021. std::string method;
  1022. std::string path;
  1023. std::string matched_route;
  1024. Params params;
  1025. Headers headers;
  1026. Headers trailers;
  1027. std::string body;
  1028. std::string remote_addr;
  1029. int remote_port = -1;
  1030. std::string local_addr;
  1031. int local_port = -1;
  1032. // for server
  1033. std::string version;
  1034. std::string target;
  1035. MultipartFormData form;
  1036. Ranges ranges;
  1037. Match matches;
  1038. std::unordered_map<std::string, std::string> path_params;
  1039. std::function<bool()> is_connection_closed = []() { return true; };
  1040. // for client
  1041. std::vector<std::string> accept_content_types;
  1042. ResponseHandler response_handler;
  1043. ContentReceiverWithProgress content_receiver;
  1044. DownloadProgress download_progress;
  1045. UploadProgress upload_progress;
  1046. bool has_header(const std::string &key) const;
  1047. std::string get_header_value(const std::string &key, const char *def = "",
  1048. size_t id = 0) const;
  1049. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1050. size_t id = 0) const;
  1051. size_t get_header_value_count(const std::string &key) const;
  1052. void set_header(const std::string &key, const std::string &val);
  1053. bool has_trailer(const std::string &key) const;
  1054. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1055. size_t get_trailer_value_count(const std::string &key) const;
  1056. bool has_param(const std::string &key) const;
  1057. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1058. size_t get_param_value_count(const std::string &key) const;
  1059. bool is_multipart_form_data() const;
  1060. // private members...
  1061. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1062. size_t content_length_ = 0;
  1063. ContentProvider content_provider_;
  1064. bool is_chunked_content_provider_ = false;
  1065. size_t authorization_count_ = 0;
  1066. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1067. (std::chrono::steady_clock::time_point::min)();
  1068. #ifdef CPPHTTPLIB_SSL_ENABLED
  1069. tls::const_session_t ssl = nullptr;
  1070. tls::PeerCert peer_cert() const;
  1071. std::string sni() const;
  1072. #endif
  1073. };
  1074. struct Response {
  1075. std::string version;
  1076. int status = -1;
  1077. std::string reason;
  1078. Headers headers;
  1079. Headers trailers;
  1080. std::string body;
  1081. std::string location; // Redirect location
  1082. // User-defined context — set by pre-routing/pre-request handlers and read
  1083. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1084. std::map<std::string, any> user_data;
  1085. bool has_header(const std::string &key) const;
  1086. std::string get_header_value(const std::string &key, const char *def = "",
  1087. size_t id = 0) const;
  1088. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1089. size_t id = 0) const;
  1090. size_t get_header_value_count(const std::string &key) const;
  1091. void set_header(const std::string &key, const std::string &val);
  1092. bool has_trailer(const std::string &key) const;
  1093. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1094. size_t get_trailer_value_count(const std::string &key) const;
  1095. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1096. void set_content(const char *s, size_t n, const std::string &content_type);
  1097. void set_content(const std::string &s, const std::string &content_type);
  1098. void set_content(std::string &&s, const std::string &content_type);
  1099. void set_content_provider(
  1100. size_t length, const std::string &content_type, ContentProvider provider,
  1101. ContentProviderResourceReleaser resource_releaser = nullptr);
  1102. void set_content_provider(
  1103. const std::string &content_type, ContentProviderWithoutLength provider,
  1104. ContentProviderResourceReleaser resource_releaser = nullptr);
  1105. void set_chunked_content_provider(
  1106. const std::string &content_type, ContentProviderWithoutLength provider,
  1107. ContentProviderResourceReleaser resource_releaser = nullptr);
  1108. void set_file_content(const std::string &path,
  1109. const std::string &content_type);
  1110. void set_file_content(const std::string &path);
  1111. Response() = default;
  1112. Response(const Response &) = default;
  1113. Response &operator=(const Response &) = default;
  1114. Response(Response &&) = default;
  1115. Response &operator=(Response &&) = default;
  1116. ~Response() {
  1117. if (content_provider_resource_releaser_) {
  1118. content_provider_resource_releaser_(content_provider_success_);
  1119. }
  1120. }
  1121. // private members...
  1122. size_t content_length_ = 0;
  1123. ContentProvider content_provider_;
  1124. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1125. bool is_chunked_content_provider_ = false;
  1126. bool content_provider_success_ = false;
  1127. std::string file_content_path_;
  1128. std::string file_content_content_type_;
  1129. };
  1130. enum class Error {
  1131. Success = 0,
  1132. Unknown,
  1133. Connection,
  1134. BindIPAddress,
  1135. Read,
  1136. Write,
  1137. ExceedRedirectCount,
  1138. Canceled,
  1139. SSLConnection,
  1140. SSLLoadingCerts,
  1141. SSLServerVerification,
  1142. SSLServerHostnameVerification,
  1143. UnsupportedMultipartBoundaryChars,
  1144. Compression,
  1145. ConnectionTimeout,
  1146. ProxyConnection,
  1147. ConnectionClosed,
  1148. Timeout,
  1149. ResourceExhaustion,
  1150. TooManyFormDataFiles,
  1151. ExceedMaxPayloadSize,
  1152. ExceedUriMaxLength,
  1153. ExceedMaxSocketDescriptorCount,
  1154. InvalidRequestLine,
  1155. InvalidHTTPMethod,
  1156. InvalidHTTPVersion,
  1157. InvalidHeaders,
  1158. MultipartParsing,
  1159. OpenFile,
  1160. Listen,
  1161. GetSockName,
  1162. UnsupportedAddressFamily,
  1163. HTTPParsing,
  1164. InvalidRangeHeader,
  1165. // For internal use only
  1166. SSLPeerCouldBeClosed_,
  1167. };
  1168. std::string to_string(Error error);
  1169. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1170. class Stream {
  1171. public:
  1172. virtual ~Stream() = default;
  1173. virtual bool is_readable() const = 0;
  1174. virtual bool wait_readable() const = 0;
  1175. virtual bool wait_writable() const = 0;
  1176. virtual bool is_peer_alive() const { return wait_writable(); }
  1177. virtual ssize_t read(char *ptr, size_t size) = 0;
  1178. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1179. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1180. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1181. virtual socket_t socket() const = 0;
  1182. virtual time_t duration() const = 0;
  1183. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1184. (void)sec;
  1185. (void)usec;
  1186. }
  1187. ssize_t write(const char *ptr);
  1188. ssize_t write(const std::string &s);
  1189. Error get_error() const { return error_; }
  1190. protected:
  1191. Error error_ = Error::Success;
  1192. };
  1193. class TaskQueue {
  1194. public:
  1195. TaskQueue() = default;
  1196. virtual ~TaskQueue() = default;
  1197. virtual bool enqueue(std::function<void()> fn) = 0;
  1198. virtual void shutdown() = 0;
  1199. virtual void on_idle() {}
  1200. };
  1201. class ThreadPool final : public TaskQueue {
  1202. public:
  1203. explicit ThreadPool(size_t n, size_t max_n = 0, size_t mqr = 0);
  1204. ThreadPool(const ThreadPool &) = delete;
  1205. ~ThreadPool() override = default;
  1206. bool enqueue(std::function<void()> fn) override;
  1207. void shutdown() override;
  1208. private:
  1209. void worker(bool is_dynamic);
  1210. void move_to_finished(std::thread::id id);
  1211. void cleanup_finished_threads();
  1212. size_t base_thread_count_;
  1213. size_t max_thread_count_;
  1214. size_t max_queued_requests_;
  1215. size_t idle_thread_count_;
  1216. bool shutdown_;
  1217. std::list<std::function<void()>> jobs_;
  1218. std::vector<std::thread> threads_; // base threads
  1219. std::list<std::thread> dynamic_threads_; // dynamic threads
  1220. std::vector<std::thread>
  1221. finished_threads_; // exited dynamic threads awaiting join
  1222. std::condition_variable cond_;
  1223. std::mutex mutex_;
  1224. };
  1225. using Logger = std::function<void(const Request &, const Response &)>;
  1226. // Forward declaration for Error type
  1227. enum class Error;
  1228. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1229. using SocketOptions = std::function<void(socket_t sock)>;
  1230. void default_socket_options(socket_t sock);
  1231. const char *status_message(int status);
  1232. std::string to_string(Error error);
  1233. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1234. std::string get_bearer_token_auth(const Request &req);
  1235. namespace detail {
  1236. class MatcherBase {
  1237. public:
  1238. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1239. virtual ~MatcherBase() = default;
  1240. const std::string &pattern() const { return pattern_; }
  1241. // Match request path and populate its matches and
  1242. virtual bool match(Request &request) const = 0;
  1243. private:
  1244. std::string pattern_;
  1245. };
  1246. /**
  1247. * Captures parameters in request path and stores them in Request::path_params
  1248. *
  1249. * Capture name is a substring of a pattern from : to /.
  1250. * The rest of the pattern is matched against the request path directly
  1251. * Parameters are captured starting from the next character after
  1252. * the end of the last matched static pattern fragment until the next /.
  1253. *
  1254. * Example pattern:
  1255. * "/path/fragments/:capture/more/fragments/:second_capture"
  1256. * Static fragments:
  1257. * "/path/fragments/", "more/fragments/"
  1258. *
  1259. * Given the following request path:
  1260. * "/path/fragments/:1/more/fragments/:2"
  1261. * the resulting capture will be
  1262. * {{"capture", "1"}, {"second_capture", "2"}}
  1263. */
  1264. class PathParamsMatcher final : public MatcherBase {
  1265. public:
  1266. PathParamsMatcher(const std::string &pattern);
  1267. bool match(Request &request) const override;
  1268. private:
  1269. // Treat segment separators as the end of path parameter capture
  1270. // Does not need to handle query parameters as they are parsed before path
  1271. // matching
  1272. static constexpr char separator = '/';
  1273. // Contains static path fragments to match against, excluding the '/' after
  1274. // path params
  1275. // Fragments are separated by path params
  1276. std::vector<std::string> static_fragments_;
  1277. // Stores the names of the path parameters to be used as keys in the
  1278. // Request::path_params map
  1279. std::vector<std::string> param_names_;
  1280. };
  1281. /**
  1282. * Performs std::regex_match on request path
  1283. * and stores the result in Request::matches
  1284. *
  1285. * Note that regex match is performed directly on the whole request.
  1286. * This means that wildcard patterns may match multiple path segments with /:
  1287. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1288. */
  1289. class RegexMatcher final : public MatcherBase {
  1290. public:
  1291. RegexMatcher(const std::string &pattern)
  1292. : MatcherBase(pattern), regex_(pattern) {}
  1293. bool match(Request &request) const override;
  1294. private:
  1295. std::regex regex_;
  1296. };
  1297. int close_socket(socket_t sock);
  1298. ssize_t write_headers(Stream &strm, const Headers &headers);
  1299. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1300. time_t usec);
  1301. } // namespace detail
  1302. class Server {
  1303. public:
  1304. using Handler = std::function<void(const Request &, Response &)>;
  1305. using ExceptionHandler =
  1306. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1307. enum class HandlerResponse {
  1308. Handled,
  1309. Unhandled,
  1310. };
  1311. using HandlerWithResponse =
  1312. std::function<HandlerResponse(const Request &, Response &)>;
  1313. using HandlerWithContentReader = std::function<void(
  1314. const Request &, Response &, const ContentReader &content_reader)>;
  1315. using Expect100ContinueHandler =
  1316. std::function<int(const Request &, Response &)>;
  1317. using WebSocketHandler =
  1318. std::function<void(const Request &, ws::WebSocket &)>;
  1319. using SubProtocolSelector =
  1320. std::function<std::string(const std::vector<std::string> &protocols)>;
  1321. Server();
  1322. virtual ~Server();
  1323. virtual bool is_valid() const;
  1324. Server &Get(const std::string &pattern, Handler handler);
  1325. Server &Post(const std::string &pattern, Handler handler);
  1326. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1327. Server &Put(const std::string &pattern, Handler handler);
  1328. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1329. Server &Patch(const std::string &pattern, Handler handler);
  1330. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1331. Server &Delete(const std::string &pattern, Handler handler);
  1332. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1333. Server &Options(const std::string &pattern, Handler handler);
  1334. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1335. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1336. SubProtocolSelector sub_protocol_selector);
  1337. bool set_base_dir(const std::string &dir,
  1338. const std::string &mount_point = std::string());
  1339. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1340. Headers headers = Headers());
  1341. bool remove_mount_point(const std::string &mount_point);
  1342. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1343. const std::string &mime);
  1344. Server &set_default_file_mimetype(const std::string &mime);
  1345. Server &set_file_request_handler(Handler handler);
  1346. template <class ErrorHandlerFunc>
  1347. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1348. return set_error_handler_core(
  1349. std::forward<ErrorHandlerFunc>(handler),
  1350. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1351. }
  1352. Server &set_exception_handler(ExceptionHandler handler);
  1353. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1354. Server &set_post_routing_handler(Handler handler);
  1355. Server &set_pre_request_handler(HandlerWithResponse handler);
  1356. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1357. Server &set_logger(Logger logger);
  1358. Server &set_pre_compression_logger(Logger logger);
  1359. Server &set_error_logger(ErrorLogger error_logger);
  1360. Server &set_address_family(int family);
  1361. Server &set_tcp_nodelay(bool on);
  1362. Server &set_ipv6_v6only(bool on);
  1363. Server &set_socket_options(SocketOptions socket_options);
  1364. Server &set_default_headers(Headers headers);
  1365. Server &
  1366. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1367. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1368. Server &set_keep_alive_max_count(size_t count);
  1369. Server &set_keep_alive_timeout(time_t sec);
  1370. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1371. template <class Rep, class Period>
  1372. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1373. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1374. template <class Rep, class Period>
  1375. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1376. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1377. template <class Rep, class Period>
  1378. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1379. Server &set_payload_max_length(size_t length);
  1380. Server &set_websocket_ping_interval(time_t sec);
  1381. template <class Rep, class Period>
  1382. Server &set_websocket_ping_interval(
  1383. const std::chrono::duration<Rep, Period> &duration);
  1384. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1385. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1386. bool listen_after_bind();
  1387. bool listen(const std::string &host, int port, int socket_flags = 0);
  1388. bool is_running() const;
  1389. void wait_until_ready() const;
  1390. void stop();
  1391. void decommission();
  1392. std::function<TaskQueue *(void)> new_task_queue;
  1393. protected:
  1394. bool process_request(Stream &strm, const std::string &remote_addr,
  1395. int remote_port, const std::string &local_addr,
  1396. int local_port, bool close_connection,
  1397. bool &connection_closed,
  1398. const std::function<void(Request &)> &setup_request,
  1399. bool *websocket_upgraded = nullptr);
  1400. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1401. std::vector<std::string> trusted_proxies_;
  1402. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1403. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1404. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1405. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1406. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1407. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1408. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1409. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1410. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1411. time_t websocket_ping_interval_sec_ =
  1412. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1413. private:
  1414. using Handlers =
  1415. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1416. using HandlersForContentReader =
  1417. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1418. HandlerWithContentReader>>;
  1419. static std::unique_ptr<detail::MatcherBase>
  1420. make_matcher(const std::string &pattern);
  1421. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1422. Server &set_error_handler_core(Handler handler, std::false_type);
  1423. socket_t create_server_socket(const std::string &host, int port,
  1424. int socket_flags,
  1425. SocketOptions socket_options) const;
  1426. int bind_internal(const std::string &host, int port, int socket_flags);
  1427. bool listen_internal();
  1428. bool routing(Request &req, Response &res, Stream &strm);
  1429. bool handle_file_request(Request &req, Response &res);
  1430. bool check_if_not_modified(const Request &req, Response &res,
  1431. const std::string &etag, time_t mtime) const;
  1432. bool check_if_range(Request &req, const std::string &etag,
  1433. time_t mtime) const;
  1434. bool dispatch_request(Request &req, Response &res,
  1435. const Handlers &handlers) const;
  1436. bool dispatch_request_for_content_reader(
  1437. Request &req, Response &res, ContentReader content_reader,
  1438. const HandlersForContentReader &handlers) const;
  1439. bool parse_request_line(const char *s, Request &req) const;
  1440. void apply_ranges(const Request &req, Response &res,
  1441. std::string &content_type, std::string &boundary) const;
  1442. bool write_response(Stream &strm, bool close_connection, Request &req,
  1443. Response &res);
  1444. bool write_response_with_content(Stream &strm, bool close_connection,
  1445. const Request &req, Response &res);
  1446. bool write_response_core(Stream &strm, bool close_connection,
  1447. const Request &req, Response &res,
  1448. bool need_apply_ranges);
  1449. bool write_content_with_provider(Stream &strm, const Request &req,
  1450. Response &res, const std::string &boundary,
  1451. const std::string &content_type);
  1452. bool read_content(Stream &strm, Request &req, Response &res);
  1453. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1454. Response &res,
  1455. ContentReceiver receiver,
  1456. FormDataHeader multipart_header,
  1457. ContentReceiver multipart_receiver);
  1458. bool read_content_core(Stream &strm, Request &req, Response &res,
  1459. ContentReceiver receiver,
  1460. FormDataHeader multipart_header,
  1461. ContentReceiver multipart_receiver) const;
  1462. virtual bool process_and_close_socket(socket_t sock);
  1463. void output_log(const Request &req, const Response &res) const;
  1464. void output_pre_compression_log(const Request &req,
  1465. const Response &res) const;
  1466. void output_error_log(const Error &err, const Request *req) const;
  1467. std::atomic<bool> is_running_{false};
  1468. std::atomic<bool> is_decommissioned{false};
  1469. struct MountPointEntry {
  1470. std::string mount_point;
  1471. std::string base_dir;
  1472. std::string resolved_base_dir;
  1473. Headers headers;
  1474. };
  1475. std::vector<MountPointEntry> base_dirs_;
  1476. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1477. std::string default_file_mimetype_ = "application/octet-stream";
  1478. Handler file_request_handler_;
  1479. Handlers get_handlers_;
  1480. Handlers post_handlers_;
  1481. HandlersForContentReader post_handlers_for_content_reader_;
  1482. Handlers put_handlers_;
  1483. HandlersForContentReader put_handlers_for_content_reader_;
  1484. Handlers patch_handlers_;
  1485. HandlersForContentReader patch_handlers_for_content_reader_;
  1486. Handlers delete_handlers_;
  1487. HandlersForContentReader delete_handlers_for_content_reader_;
  1488. Handlers options_handlers_;
  1489. struct WebSocketHandlerEntry {
  1490. std::unique_ptr<detail::MatcherBase> matcher;
  1491. WebSocketHandler handler;
  1492. SubProtocolSelector sub_protocol_selector;
  1493. };
  1494. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1495. WebSocketHandlers websocket_handlers_;
  1496. HandlerWithResponse error_handler_;
  1497. ExceptionHandler exception_handler_;
  1498. HandlerWithResponse pre_routing_handler_;
  1499. Handler post_routing_handler_;
  1500. HandlerWithResponse pre_request_handler_;
  1501. Expect100ContinueHandler expect_100_continue_handler_;
  1502. mutable std::mutex logger_mutex_;
  1503. Logger logger_;
  1504. Logger pre_compression_logger_;
  1505. ErrorLogger error_logger_;
  1506. int address_family_ = AF_UNSPEC;
  1507. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1508. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1509. SocketOptions socket_options_ = default_socket_options;
  1510. Headers default_headers_;
  1511. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1512. detail::write_headers;
  1513. };
  1514. class Result {
  1515. public:
  1516. Result() = default;
  1517. Result(std::unique_ptr<Response> &&res, Error err,
  1518. Headers &&request_headers = Headers{})
  1519. : res_(std::move(res)), err_(err),
  1520. request_headers_(std::move(request_headers)) {}
  1521. // Response
  1522. operator bool() const { return res_ != nullptr; }
  1523. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1524. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1525. const Response &value() const { return *res_; }
  1526. Response &value() { return *res_; }
  1527. const Response &operator*() const { return *res_; }
  1528. Response &operator*() { return *res_; }
  1529. const Response *operator->() const { return res_.get(); }
  1530. Response *operator->() { return res_.get(); }
  1531. // Error
  1532. Error error() const { return err_; }
  1533. // Request Headers
  1534. bool has_request_header(const std::string &key) const;
  1535. std::string get_request_header_value(const std::string &key,
  1536. const char *def = "",
  1537. size_t id = 0) const;
  1538. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1539. size_t id = 0) const;
  1540. size_t get_request_header_value_count(const std::string &key) const;
  1541. private:
  1542. std::unique_ptr<Response> res_;
  1543. Error err_ = Error::Unknown;
  1544. Headers request_headers_;
  1545. #ifdef CPPHTTPLIB_SSL_ENABLED
  1546. public:
  1547. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1548. int ssl_error)
  1549. : res_(std::move(res)), err_(err),
  1550. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1551. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1552. int ssl_error, uint64_t ssl_backend_error)
  1553. : res_(std::move(res)), err_(err),
  1554. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1555. ssl_backend_error_(ssl_backend_error) {}
  1556. int ssl_error() const { return ssl_error_; }
  1557. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1558. private:
  1559. int ssl_error_ = 0;
  1560. uint64_t ssl_backend_error_ = 0;
  1561. #endif
  1562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1563. public:
  1564. [[deprecated("Use ssl_backend_error() instead. "
  1565. "This function will be removed by v1.0.0.")]]
  1566. uint64_t ssl_openssl_error() const {
  1567. return ssl_backend_error_;
  1568. }
  1569. #endif
  1570. };
  1571. struct ClientConnection {
  1572. socket_t sock = INVALID_SOCKET;
  1573. bool is_open() const { return sock != INVALID_SOCKET; }
  1574. ClientConnection() = default;
  1575. ~ClientConnection();
  1576. ClientConnection(const ClientConnection &) = delete;
  1577. ClientConnection &operator=(const ClientConnection &) = delete;
  1578. ClientConnection(ClientConnection &&other) noexcept
  1579. : sock(other.sock)
  1580. #ifdef CPPHTTPLIB_SSL_ENABLED
  1581. ,
  1582. session(other.session)
  1583. #endif
  1584. {
  1585. other.sock = INVALID_SOCKET;
  1586. #ifdef CPPHTTPLIB_SSL_ENABLED
  1587. other.session = nullptr;
  1588. #endif
  1589. }
  1590. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1591. if (this != &other) {
  1592. sock = other.sock;
  1593. other.sock = INVALID_SOCKET;
  1594. #ifdef CPPHTTPLIB_SSL_ENABLED
  1595. session = other.session;
  1596. other.session = nullptr;
  1597. #endif
  1598. }
  1599. return *this;
  1600. }
  1601. #ifdef CPPHTTPLIB_SSL_ENABLED
  1602. tls::session_t session = nullptr;
  1603. #endif
  1604. };
  1605. namespace detail {
  1606. struct ChunkedDecoder;
  1607. struct BodyReader {
  1608. Stream *stream = nullptr;
  1609. bool has_content_length = false;
  1610. size_t content_length = 0;
  1611. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1612. size_t bytes_read = 0;
  1613. bool chunked = false;
  1614. bool eof = false;
  1615. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1616. Error last_error = Error::Success;
  1617. ssize_t read(char *buf, size_t len);
  1618. bool has_error() const { return last_error != Error::Success; }
  1619. };
  1620. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1621. size_t len) {
  1622. (void)stream;
  1623. return br.read(buf, len);
  1624. }
  1625. class decompressor;
  1626. } // namespace detail
  1627. class ClientImpl {
  1628. public:
  1629. explicit ClientImpl(const std::string &host);
  1630. explicit ClientImpl(const std::string &host, int port);
  1631. explicit ClientImpl(const std::string &host, int port,
  1632. const std::string &client_cert_path,
  1633. const std::string &client_key_path);
  1634. virtual ~ClientImpl();
  1635. virtual bool is_valid() const;
  1636. struct StreamHandle {
  1637. std::unique_ptr<Response> response;
  1638. Error error = Error::Success;
  1639. StreamHandle() = default;
  1640. StreamHandle(const StreamHandle &) = delete;
  1641. StreamHandle &operator=(const StreamHandle &) = delete;
  1642. StreamHandle(StreamHandle &&) = default;
  1643. StreamHandle &operator=(StreamHandle &&) = default;
  1644. ~StreamHandle() = default;
  1645. bool is_valid() const {
  1646. return response != nullptr && error == Error::Success;
  1647. }
  1648. ssize_t read(char *buf, size_t len);
  1649. void parse_trailers_if_needed();
  1650. Error get_read_error() const { return body_reader_.last_error; }
  1651. bool has_read_error() const { return body_reader_.has_error(); }
  1652. bool trailers_parsed_ = false;
  1653. private:
  1654. friend class ClientImpl;
  1655. ssize_t read_with_decompression(char *buf, size_t len);
  1656. std::unique_ptr<ClientConnection> connection_;
  1657. std::unique_ptr<Stream> socket_stream_;
  1658. Stream *stream_ = nullptr;
  1659. detail::BodyReader body_reader_;
  1660. std::unique_ptr<detail::decompressor> decompressor_;
  1661. std::string decompress_buffer_;
  1662. size_t decompress_offset_ = 0;
  1663. size_t decompressed_bytes_read_ = 0;
  1664. };
  1665. // clang-format off
  1666. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1667. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1668. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1669. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1670. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1671. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1672. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1673. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1674. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1675. Result Head(const std::string &path);
  1676. Result Head(const std::string &path, const Headers &headers);
  1677. Result Post(const std::string &path);
  1678. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1679. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1680. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1681. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1682. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1683. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1684. Result Post(const std::string &path, const Params &params);
  1685. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1686. Result Post(const std::string &path, const Headers &headers);
  1687. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1688. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1689. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1690. 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);
  1691. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1692. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1693. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1694. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1695. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1696. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1697. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1698. Result Put(const std::string &path);
  1699. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1700. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1701. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1702. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1703. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1704. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1705. Result Put(const std::string &path, const Params &params);
  1706. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1707. Result Put(const std::string &path, const Headers &headers);
  1708. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1709. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1710. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1711. 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);
  1712. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1713. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1714. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1715. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1716. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1717. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1718. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1719. Result Patch(const std::string &path);
  1720. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1721. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1722. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1723. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1724. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1725. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1726. Result Patch(const std::string &path, const Params &params);
  1727. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1728. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1729. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1730. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1731. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1732. 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);
  1733. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1734. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1735. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1736. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1737. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1738. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1739. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1740. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1741. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1742. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1743. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1744. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1745. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1746. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1747. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1748. Result Options(const std::string &path);
  1749. Result Options(const std::string &path, const Headers &headers);
  1750. // clang-format on
  1751. // Streaming API: Open a stream for reading response body incrementally
  1752. // Socket ownership is transferred to StreamHandle for true streaming
  1753. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1754. StreamHandle open_stream(const std::string &method, const std::string &path,
  1755. const Params &params = {},
  1756. const Headers &headers = {},
  1757. const std::string &body = {},
  1758. const std::string &content_type = {});
  1759. bool send(Request &req, Response &res, Error &error);
  1760. Result send(const Request &req);
  1761. void stop();
  1762. std::string host() const;
  1763. int port() const;
  1764. size_t is_socket_open() const;
  1765. socket_t socket() const;
  1766. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1767. void set_default_headers(Headers headers);
  1768. void
  1769. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1770. void set_address_family(int family);
  1771. void set_tcp_nodelay(bool on);
  1772. void set_ipv6_v6only(bool on);
  1773. void set_socket_options(SocketOptions socket_options);
  1774. void set_connection_timeout(time_t sec, time_t usec = 0);
  1775. template <class Rep, class Period>
  1776. void
  1777. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1778. void set_read_timeout(time_t sec, time_t usec = 0);
  1779. template <class Rep, class Period>
  1780. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1781. void set_write_timeout(time_t sec, time_t usec = 0);
  1782. template <class Rep, class Period>
  1783. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1784. void set_max_timeout(time_t msec);
  1785. template <class Rep, class Period>
  1786. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1787. void set_basic_auth(const std::string &username, const std::string &password);
  1788. void set_bearer_token_auth(const std::string &token);
  1789. void set_keep_alive(bool on);
  1790. void set_follow_location(bool on);
  1791. void set_path_encode(bool on);
  1792. void set_compress(bool on);
  1793. void set_decompress(bool on);
  1794. void set_payload_max_length(size_t length);
  1795. void set_interface(const std::string &intf);
  1796. void set_proxy(const std::string &host, int port);
  1797. void set_proxy_basic_auth(const std::string &username,
  1798. const std::string &password);
  1799. void set_proxy_bearer_token_auth(const std::string &token);
  1800. void set_logger(Logger logger);
  1801. void set_error_logger(ErrorLogger error_logger);
  1802. protected:
  1803. struct Socket {
  1804. socket_t sock = INVALID_SOCKET;
  1805. // For Mbed TLS compatibility: start_time for request timeout tracking
  1806. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1807. bool is_open() const { return sock != INVALID_SOCKET; }
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. tls::session_t ssl = nullptr;
  1810. #endif
  1811. };
  1812. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1813. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1814. virtual bool setup_proxy_connection(
  1815. Socket &socket,
  1816. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1817. Response &res, bool &success, Error &error);
  1818. // All of:
  1819. // shutdown_ssl
  1820. // shutdown_socket
  1821. // close_socket
  1822. // should ONLY be called when socket_mutex_ is locked.
  1823. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1824. // with a DIFFERENT thread sending requests using that socket.
  1825. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1826. void shutdown_socket(Socket &socket) const;
  1827. void close_socket(Socket &socket);
  1828. bool process_request(Stream &strm, Request &req, Response &res,
  1829. bool close_connection, Error &error);
  1830. bool write_content_with_provider(Stream &strm, const Request &req,
  1831. Error &error) const;
  1832. void copy_settings(const ClientImpl &rhs);
  1833. void output_log(const Request &req, const Response &res) const;
  1834. void output_error_log(const Error &err, const Request *req) const;
  1835. // Socket endpoint information
  1836. const std::string host_;
  1837. const int port_;
  1838. // Current open socket
  1839. Socket socket_;
  1840. mutable std::mutex socket_mutex_;
  1841. std::recursive_mutex request_mutex_;
  1842. // These are all protected under socket_mutex
  1843. size_t socket_requests_in_flight_ = 0;
  1844. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1845. bool socket_should_be_closed_when_request_is_done_ = false;
  1846. // Hostname-IP map
  1847. std::map<std::string, std::string> addr_map_;
  1848. // Default headers
  1849. Headers default_headers_;
  1850. // Header writer
  1851. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1852. detail::write_headers;
  1853. // Settings
  1854. std::string client_cert_path_;
  1855. std::string client_key_path_;
  1856. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1857. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1858. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1859. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1860. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1861. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1862. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1863. std::string basic_auth_username_;
  1864. std::string basic_auth_password_;
  1865. std::string bearer_token_auth_token_;
  1866. bool keep_alive_ = false;
  1867. bool follow_location_ = false;
  1868. bool path_encode_ = true;
  1869. int address_family_ = AF_UNSPEC;
  1870. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1871. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1872. SocketOptions socket_options_ = nullptr;
  1873. bool compress_ = false;
  1874. bool decompress_ = true;
  1875. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1876. bool has_payload_max_length_ = false;
  1877. std::string interface_;
  1878. std::string proxy_host_;
  1879. int proxy_port_ = -1;
  1880. std::string proxy_basic_auth_username_;
  1881. std::string proxy_basic_auth_password_;
  1882. std::string proxy_bearer_token_auth_token_;
  1883. mutable std::mutex logger_mutex_;
  1884. Logger logger_;
  1885. ErrorLogger error_logger_;
  1886. private:
  1887. bool send_(Request &req, Response &res, Error &error);
  1888. Result send_(Request &&req);
  1889. socket_t create_client_socket(Error &error) const;
  1890. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1891. bool skip_100_continue = true) const;
  1892. bool write_request(Stream &strm, Request &req, bool close_connection,
  1893. Error &error, bool skip_body = false);
  1894. bool write_request_body(Stream &strm, Request &req, Error &error);
  1895. void prepare_default_headers(Request &r, bool for_stream,
  1896. const std::string &ct);
  1897. bool redirect(Request &req, Response &res, Error &error);
  1898. bool create_redirect_client(const std::string &scheme,
  1899. const std::string &host, int port, Request &req,
  1900. Response &res, const std::string &path,
  1901. const std::string &location, Error &error);
  1902. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1903. bool handle_request(Stream &strm, Request &req, Response &res,
  1904. bool close_connection, Error &error);
  1905. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1906. Request &req, const char *body, size_t content_length,
  1907. ContentProvider content_provider,
  1908. ContentProviderWithoutLength content_provider_without_length,
  1909. const std::string &content_type, ContentReceiver content_receiver,
  1910. Error &error);
  1911. Result send_with_content_provider_and_receiver(
  1912. const std::string &method, const std::string &path,
  1913. const Headers &headers, const char *body, size_t content_length,
  1914. ContentProvider content_provider,
  1915. ContentProviderWithoutLength content_provider_without_length,
  1916. const std::string &content_type, ContentReceiver content_receiver,
  1917. UploadProgress progress);
  1918. ContentProviderWithoutLength get_multipart_content_provider(
  1919. const std::string &boundary, const UploadFormDataItems &items,
  1920. const FormDataProviderItems &provider_items) const;
  1921. virtual bool
  1922. process_socket(const Socket &socket,
  1923. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1924. std::function<bool(Stream &strm)> callback);
  1925. virtual bool is_ssl() const;
  1926. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1927. #ifdef CPPHTTPLIB_SSL_ENABLED
  1928. public:
  1929. void set_digest_auth(const std::string &username,
  1930. const std::string &password);
  1931. void set_proxy_digest_auth(const std::string &username,
  1932. const std::string &password);
  1933. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1934. const std::string &ca_cert_dir_path = std::string());
  1935. void enable_server_certificate_verification(bool enabled);
  1936. void enable_server_hostname_verification(bool enabled);
  1937. protected:
  1938. std::string digest_auth_username_;
  1939. std::string digest_auth_password_;
  1940. std::string proxy_digest_auth_username_;
  1941. std::string proxy_digest_auth_password_;
  1942. std::string ca_cert_file_path_;
  1943. std::string ca_cert_dir_path_;
  1944. bool server_certificate_verification_ = true;
  1945. bool server_hostname_verification_ = true;
  1946. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1947. int last_ssl_error_ = 0;
  1948. uint64_t last_backend_error_ = 0;
  1949. #endif
  1950. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1951. public:
  1952. [[deprecated("Use load_ca_cert_store() instead. "
  1953. "This function will be removed by v1.0.0.")]]
  1954. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1955. [[deprecated("Use tls::create_ca_store() instead. "
  1956. "This function will be removed by v1.0.0.")]]
  1957. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1958. [[deprecated("Use set_server_certificate_verifier(VerifyCallback) instead. "
  1959. "This function will be removed by v1.0.0.")]]
  1960. virtual void set_server_certificate_verifier(
  1961. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1962. #endif
  1963. };
  1964. class Client {
  1965. public:
  1966. // Universal interface
  1967. explicit Client(const std::string &scheme_host_port);
  1968. explicit Client(const std::string &scheme_host_port,
  1969. const std::string &client_cert_path,
  1970. const std::string &client_key_path);
  1971. // HTTP only interface
  1972. explicit Client(const std::string &host, int port);
  1973. explicit Client(const std::string &host, int port,
  1974. const std::string &client_cert_path,
  1975. const std::string &client_key_path);
  1976. Client(Client &&) = default;
  1977. Client &operator=(Client &&) = default;
  1978. ~Client();
  1979. bool is_valid() const;
  1980. // clang-format off
  1981. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1982. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1983. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1984. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1985. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1986. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1987. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1988. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1989. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1990. Result Head(const std::string &path);
  1991. Result Head(const std::string &path, const Headers &headers);
  1992. Result Post(const std::string &path);
  1993. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1994. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1995. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1996. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1997. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1998. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1999. Result Post(const std::string &path, const Params &params);
  2000. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2001. Result Post(const std::string &path, const Headers &headers);
  2002. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2003. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2004. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2005. 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);
  2006. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2007. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2008. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2009. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2010. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2011. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2012. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2013. Result Put(const std::string &path);
  2014. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2015. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2016. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2017. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2018. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2019. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2020. Result Put(const std::string &path, const Params &params);
  2021. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2022. Result Put(const std::string &path, const Headers &headers);
  2023. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2024. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2025. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2026. 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);
  2027. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2028. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2029. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2030. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2031. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2032. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2033. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2034. Result Patch(const std::string &path);
  2035. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2036. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2037. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2038. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2039. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2040. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2041. Result Patch(const std::string &path, const Params &params);
  2042. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2043. Result Patch(const std::string &path, const Headers &headers);
  2044. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2045. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2046. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2047. 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);
  2048. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2049. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2050. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2051. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2052. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2053. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2054. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2055. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2056. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2057. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2058. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2059. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2060. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2061. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2062. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2063. Result Options(const std::string &path);
  2064. Result Options(const std::string &path, const Headers &headers);
  2065. // clang-format on
  2066. // Streaming API: Open a stream for reading response body incrementally
  2067. // Socket ownership is transferred to StreamHandle for true streaming
  2068. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2069. ClientImpl::StreamHandle open_stream(const std::string &method,
  2070. const std::string &path,
  2071. const Params &params = {},
  2072. const Headers &headers = {},
  2073. const std::string &body = {},
  2074. const std::string &content_type = {});
  2075. bool send(Request &req, Response &res, Error &error);
  2076. Result send(const Request &req);
  2077. void stop();
  2078. std::string host() const;
  2079. int port() const;
  2080. size_t is_socket_open() const;
  2081. socket_t socket() const;
  2082. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2083. void set_default_headers(Headers headers);
  2084. void
  2085. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2086. void set_address_family(int family);
  2087. void set_tcp_nodelay(bool on);
  2088. void set_socket_options(SocketOptions socket_options);
  2089. void set_connection_timeout(time_t sec, time_t usec = 0);
  2090. template <class Rep, class Period>
  2091. void
  2092. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2093. void set_read_timeout(time_t sec, time_t usec = 0);
  2094. template <class Rep, class Period>
  2095. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2096. void set_write_timeout(time_t sec, time_t usec = 0);
  2097. template <class Rep, class Period>
  2098. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2099. void set_max_timeout(time_t msec);
  2100. template <class Rep, class Period>
  2101. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2102. void set_basic_auth(const std::string &username, const std::string &password);
  2103. void set_bearer_token_auth(const std::string &token);
  2104. void set_keep_alive(bool on);
  2105. void set_follow_location(bool on);
  2106. void set_path_encode(bool on);
  2107. void set_url_encode(bool on);
  2108. void set_compress(bool on);
  2109. void set_decompress(bool on);
  2110. void set_payload_max_length(size_t length);
  2111. void set_interface(const std::string &intf);
  2112. void set_proxy(const std::string &host, int port);
  2113. void set_proxy_basic_auth(const std::string &username,
  2114. const std::string &password);
  2115. void set_proxy_bearer_token_auth(const std::string &token);
  2116. void set_logger(Logger logger);
  2117. void set_error_logger(ErrorLogger error_logger);
  2118. private:
  2119. std::unique_ptr<ClientImpl> cli_;
  2120. #ifdef CPPHTTPLIB_SSL_ENABLED
  2121. public:
  2122. void set_digest_auth(const std::string &username,
  2123. const std::string &password);
  2124. void set_proxy_digest_auth(const std::string &username,
  2125. const std::string &password);
  2126. void enable_server_certificate_verification(bool enabled);
  2127. void enable_server_hostname_verification(bool enabled);
  2128. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2129. const std::string &ca_cert_dir_path = std::string());
  2130. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2131. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2132. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2133. void set_session_verifier(
  2134. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2135. tls::ctx_t tls_context() const;
  2136. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2137. void enable_windows_certificate_verification(bool enabled);
  2138. #endif
  2139. private:
  2140. bool is_ssl_ = false;
  2141. #endif
  2142. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2143. public:
  2144. [[deprecated("Use tls_context() instead. "
  2145. "This function will be removed by v1.0.0.")]]
  2146. SSL_CTX *ssl_context() const;
  2147. [[deprecated("Use set_session_verifier(session_t) instead. "
  2148. "This function will be removed by v1.0.0.")]]
  2149. void set_server_certificate_verifier(
  2150. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  2151. [[deprecated("Use Result::ssl_backend_error() instead. "
  2152. "This function will be removed by v1.0.0.")]]
  2153. long get_verify_result() const;
  2154. #endif
  2155. };
  2156. #ifdef CPPHTTPLIB_SSL_ENABLED
  2157. class SSLServer : public Server {
  2158. public:
  2159. SSLServer(const char *cert_path, const char *private_key_path,
  2160. const char *client_ca_cert_file_path = nullptr,
  2161. const char *client_ca_cert_dir_path = nullptr,
  2162. const char *private_key_password = nullptr);
  2163. struct PemMemory {
  2164. const char *cert_pem;
  2165. size_t cert_pem_len;
  2166. const char *key_pem;
  2167. size_t key_pem_len;
  2168. const char *client_ca_pem;
  2169. size_t client_ca_pem_len;
  2170. const char *private_key_password;
  2171. };
  2172. explicit SSLServer(const PemMemory &pem);
  2173. // The callback receives the ctx_t handle which can be cast to the
  2174. // appropriate backend type (SSL_CTX* for OpenSSL,
  2175. // tls::impl::MbedTlsContext* for Mbed TLS)
  2176. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2177. ~SSLServer() override;
  2178. bool is_valid() const override;
  2179. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2180. const char *client_ca_pem = nullptr,
  2181. const char *password = nullptr);
  2182. tls::ctx_t tls_context() const { return ctx_; }
  2183. int ssl_last_error() const { return last_ssl_error_; }
  2184. private:
  2185. bool process_and_close_socket(socket_t sock) override;
  2186. tls::ctx_t ctx_ = nullptr;
  2187. std::mutex ctx_mutex_;
  2188. int last_ssl_error_ = 0;
  2189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2190. public:
  2191. [[deprecated("Use SSLServer(PemMemory) or "
  2192. "SSLServer(ContextSetupCallback) instead. "
  2193. "This constructor will be removed by v1.0.0.")]]
  2194. SSLServer(X509 *cert, EVP_PKEY *private_key,
  2195. X509_STORE *client_ca_cert_store = nullptr);
  2196. [[deprecated("Use SSLServer(ContextSetupCallback) instead. "
  2197. "This constructor will be removed by v1.0.0.")]]
  2198. SSLServer(
  2199. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  2200. [[deprecated("Use tls_context() instead. "
  2201. "This function will be removed by v1.0.0.")]]
  2202. SSL_CTX *ssl_context() const;
  2203. [[deprecated("Use update_certs_pem() instead. "
  2204. "This function will be removed by v1.0.0.")]]
  2205. void update_certs(X509 *cert, EVP_PKEY *private_key,
  2206. X509_STORE *client_ca_cert_store = nullptr);
  2207. #endif
  2208. };
  2209. class SSLClient final : public ClientImpl {
  2210. public:
  2211. explicit SSLClient(const std::string &host);
  2212. explicit SSLClient(const std::string &host, int port);
  2213. explicit SSLClient(const std::string &host, int port,
  2214. const std::string &client_cert_path,
  2215. const std::string &client_key_path,
  2216. const std::string &private_key_password = std::string());
  2217. struct PemMemory {
  2218. const char *cert_pem;
  2219. size_t cert_pem_len;
  2220. const char *key_pem;
  2221. size_t key_pem_len;
  2222. const char *private_key_password;
  2223. };
  2224. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2225. ~SSLClient() override;
  2226. bool is_valid() const override;
  2227. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2228. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2229. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2230. // Post-handshake session verifier (backend-independent)
  2231. void set_session_verifier(
  2232. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2233. tls::ctx_t tls_context() const { return ctx_; }
  2234. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2235. void enable_windows_certificate_verification(bool enabled);
  2236. #endif
  2237. private:
  2238. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2239. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2240. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2241. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2242. bool
  2243. process_socket(const Socket &socket,
  2244. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2245. std::function<bool(Stream &strm)> callback) override;
  2246. bool is_ssl() const override;
  2247. bool setup_proxy_connection(
  2248. Socket &socket,
  2249. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2250. Response &res, bool &success, Error &error) override;
  2251. bool connect_with_proxy(
  2252. Socket &sock,
  2253. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2254. Response &res, bool &success, Error &error);
  2255. bool initialize_ssl(Socket &socket, Error &error);
  2256. bool load_certs();
  2257. tls::ctx_t ctx_ = nullptr;
  2258. std::mutex ctx_mutex_;
  2259. std::once_flag initialize_cert_;
  2260. long verify_result_ = 0;
  2261. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2262. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2263. bool enable_windows_cert_verification_ = true;
  2264. #endif
  2265. friend class ClientImpl;
  2266. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2267. public:
  2268. [[deprecated("Use SSLClient(host, port, PemMemory) instead. "
  2269. "This constructor will be removed by v1.0.0.")]]
  2270. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  2271. EVP_PKEY *client_key,
  2272. const std::string &private_key_password = std::string());
  2273. [[deprecated("Use Result::ssl_backend_error() instead. "
  2274. "This function will be removed by v1.0.0.")]]
  2275. long get_verify_result() const;
  2276. [[deprecated("Use tls_context() instead. "
  2277. "This function will be removed by v1.0.0.")]]
  2278. SSL_CTX *ssl_context() const;
  2279. [[deprecated("Use set_session_verifier(session_t) instead. "
  2280. "This function will be removed by v1.0.0.")]]
  2281. void set_server_certificate_verifier(
  2282. std::function<SSLVerifierResponse(SSL *ssl)> verifier) override;
  2283. private:
  2284. bool verify_host(X509 *server_cert) const;
  2285. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  2286. bool verify_host_with_common_name(X509 *server_cert) const;
  2287. #endif
  2288. };
  2289. #endif // CPPHTTPLIB_SSL_ENABLED
  2290. namespace detail {
  2291. template <typename T, typename U>
  2292. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2293. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2294. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2295. duration - std::chrono::seconds(sec))
  2296. .count();
  2297. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2298. }
  2299. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2300. return N - 1;
  2301. }
  2302. inline bool is_numeric(const std::string &str) {
  2303. return !str.empty() &&
  2304. std::all_of(str.cbegin(), str.cend(),
  2305. [](unsigned char c) { return std::isdigit(c); });
  2306. }
  2307. inline size_t get_header_value_u64(const Headers &headers,
  2308. const std::string &key, size_t def,
  2309. size_t id, bool &is_invalid_value) {
  2310. is_invalid_value = false;
  2311. auto rng = headers.equal_range(key);
  2312. auto it = rng.first;
  2313. std::advance(it, static_cast<ssize_t>(id));
  2314. if (it != rng.second) {
  2315. if (is_numeric(it->second)) {
  2316. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2317. } else {
  2318. is_invalid_value = true;
  2319. }
  2320. }
  2321. return def;
  2322. }
  2323. inline size_t get_header_value_u64(const Headers &headers,
  2324. const std::string &key, size_t def,
  2325. size_t id) {
  2326. auto dummy = false;
  2327. return get_header_value_u64(headers, key, def, id, dummy);
  2328. }
  2329. } // namespace detail
  2330. template <class Rep, class Period>
  2331. inline Server &
  2332. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2333. detail::duration_to_sec_and_usec(
  2334. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2335. return *this;
  2336. }
  2337. template <class Rep, class Period>
  2338. inline Server &
  2339. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2340. detail::duration_to_sec_and_usec(
  2341. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2342. return *this;
  2343. }
  2344. template <class Rep, class Period>
  2345. inline Server &
  2346. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2347. detail::duration_to_sec_and_usec(
  2348. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2349. return *this;
  2350. }
  2351. template <class Rep, class Period>
  2352. inline void ClientImpl::set_connection_timeout(
  2353. const std::chrono::duration<Rep, Period> &duration) {
  2354. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2355. set_connection_timeout(sec, usec);
  2356. });
  2357. }
  2358. template <class Rep, class Period>
  2359. inline void ClientImpl::set_read_timeout(
  2360. const std::chrono::duration<Rep, Period> &duration) {
  2361. detail::duration_to_sec_and_usec(
  2362. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2363. }
  2364. template <class Rep, class Period>
  2365. inline void ClientImpl::set_write_timeout(
  2366. const std::chrono::duration<Rep, Period> &duration) {
  2367. detail::duration_to_sec_and_usec(
  2368. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2369. }
  2370. template <class Rep, class Period>
  2371. inline void ClientImpl::set_max_timeout(
  2372. const std::chrono::duration<Rep, Period> &duration) {
  2373. auto msec =
  2374. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2375. set_max_timeout(msec);
  2376. }
  2377. template <class Rep, class Period>
  2378. inline void Client::set_connection_timeout(
  2379. const std::chrono::duration<Rep, Period> &duration) {
  2380. cli_->set_connection_timeout(duration);
  2381. }
  2382. template <class Rep, class Period>
  2383. inline void
  2384. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2385. cli_->set_read_timeout(duration);
  2386. }
  2387. template <class Rep, class Period>
  2388. inline void
  2389. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2390. cli_->set_write_timeout(duration);
  2391. }
  2392. inline void Client::set_max_timeout(time_t msec) {
  2393. cli_->set_max_timeout(msec);
  2394. }
  2395. template <class Rep, class Period>
  2396. inline void
  2397. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2398. cli_->set_max_timeout(duration);
  2399. }
  2400. /*
  2401. * Forward declarations and types that will be part of the .h file if split into
  2402. * .h + .cc.
  2403. */
  2404. std::string hosted_at(const std::string &hostname);
  2405. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2406. // JavaScript-style URL encoding/decoding functions
  2407. std::string encode_uri_component(const std::string &value);
  2408. std::string encode_uri(const std::string &value);
  2409. std::string decode_uri_component(const std::string &value);
  2410. std::string decode_uri(const std::string &value);
  2411. // RFC 3986 compliant URL component encoding/decoding functions
  2412. std::string encode_path_component(const std::string &component);
  2413. std::string decode_path_component(const std::string &component);
  2414. std::string encode_query_component(const std::string &component,
  2415. bool space_as_plus = true);
  2416. std::string decode_query_component(const std::string &component,
  2417. bool plus_as_space = true);
  2418. std::string sanitize_filename(const std::string &filename);
  2419. std::string append_query_params(const std::string &path, const Params &params);
  2420. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2421. std::pair<std::string, std::string>
  2422. make_basic_authentication_header(const std::string &username,
  2423. const std::string &password,
  2424. bool is_proxy = false);
  2425. namespace detail {
  2426. #if defined(_WIN32)
  2427. inline std::wstring u8string_to_wstring(const char *s) {
  2428. if (!s) { return std::wstring(); }
  2429. auto len = static_cast<int>(strlen(s));
  2430. if (!len) { return std::wstring(); }
  2431. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2432. if (!wlen) { return std::wstring(); }
  2433. std::wstring ws;
  2434. ws.resize(wlen);
  2435. wlen = ::MultiByteToWideChar(
  2436. CP_UTF8, 0, s, len,
  2437. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2438. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2439. return ws;
  2440. }
  2441. #endif
  2442. struct FileStat {
  2443. FileStat(const std::string &path);
  2444. bool is_file() const;
  2445. bool is_dir() const;
  2446. time_t mtime() const;
  2447. size_t size() const;
  2448. private:
  2449. #if defined(_WIN32)
  2450. struct _stat st_;
  2451. #else
  2452. struct stat st_;
  2453. #endif
  2454. int ret_ = -1;
  2455. };
  2456. std::string make_host_and_port_string(const std::string &host, int port,
  2457. bool is_ssl);
  2458. std::string trim_copy(const std::string &s);
  2459. void divide(
  2460. const char *data, std::size_t size, char d,
  2461. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2462. fn);
  2463. void divide(
  2464. const std::string &str, char d,
  2465. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2466. fn);
  2467. void split(const char *b, const char *e, char d,
  2468. std::function<void(const char *, const char *)> fn);
  2469. void split(const char *b, const char *e, char d, size_t m,
  2470. std::function<void(const char *, const char *)> fn);
  2471. bool process_client_socket(
  2472. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2473. time_t write_timeout_sec, time_t write_timeout_usec,
  2474. time_t max_timeout_msec,
  2475. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2476. std::function<bool(Stream &)> callback);
  2477. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2478. int port, int address_family, bool tcp_nodelay,
  2479. bool ipv6_v6only, SocketOptions socket_options,
  2480. time_t connection_timeout_sec,
  2481. time_t connection_timeout_usec,
  2482. time_t read_timeout_sec, time_t read_timeout_usec,
  2483. time_t write_timeout_sec,
  2484. time_t write_timeout_usec,
  2485. const std::string &intf, Error &error);
  2486. const char *get_header_value(const Headers &headers, const std::string &key,
  2487. const char *def, size_t id);
  2488. std::string params_to_query_str(const Params &params);
  2489. void parse_query_text(const char *data, std::size_t size, Params &params);
  2490. void parse_query_text(const std::string &s, Params &params);
  2491. bool parse_multipart_boundary(const std::string &content_type,
  2492. std::string &boundary);
  2493. bool parse_range_header(const std::string &s, Ranges &ranges);
  2494. bool parse_accept_header(const std::string &s,
  2495. std::vector<std::string> &content_types);
  2496. int close_socket(socket_t sock);
  2497. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2498. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2499. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2500. EncodingType encoding_type(const Request &req, const Response &res);
  2501. class BufferStream final : public Stream {
  2502. public:
  2503. BufferStream() = default;
  2504. ~BufferStream() override = default;
  2505. bool is_readable() const override;
  2506. bool wait_readable() const override;
  2507. bool wait_writable() const override;
  2508. ssize_t read(char *ptr, size_t size) override;
  2509. ssize_t write(const char *ptr, size_t size) override;
  2510. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2511. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2512. socket_t socket() const override;
  2513. time_t duration() const override;
  2514. const std::string &get_buffer() const;
  2515. private:
  2516. std::string buffer;
  2517. size_t position = 0;
  2518. };
  2519. class compressor {
  2520. public:
  2521. virtual ~compressor() = default;
  2522. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2523. virtual bool compress(const char *data, size_t data_length, bool last,
  2524. Callback callback) = 0;
  2525. };
  2526. class decompressor {
  2527. public:
  2528. virtual ~decompressor() = default;
  2529. virtual bool is_valid() const = 0;
  2530. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2531. virtual bool decompress(const char *data, size_t data_length,
  2532. Callback callback) = 0;
  2533. };
  2534. class nocompressor final : public compressor {
  2535. public:
  2536. ~nocompressor() override = default;
  2537. bool compress(const char *data, size_t data_length, bool /*last*/,
  2538. Callback callback) override;
  2539. };
  2540. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2541. class gzip_compressor final : public compressor {
  2542. public:
  2543. gzip_compressor();
  2544. ~gzip_compressor() override;
  2545. bool compress(const char *data, size_t data_length, bool last,
  2546. Callback callback) override;
  2547. private:
  2548. bool is_valid_ = false;
  2549. z_stream strm_;
  2550. };
  2551. class gzip_decompressor final : public decompressor {
  2552. public:
  2553. gzip_decompressor();
  2554. ~gzip_decompressor() override;
  2555. bool is_valid() const override;
  2556. bool decompress(const char *data, size_t data_length,
  2557. Callback callback) override;
  2558. private:
  2559. bool is_valid_ = false;
  2560. z_stream strm_;
  2561. };
  2562. #endif
  2563. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2564. class brotli_compressor final : public compressor {
  2565. public:
  2566. brotli_compressor();
  2567. ~brotli_compressor();
  2568. bool compress(const char *data, size_t data_length, bool last,
  2569. Callback callback) override;
  2570. private:
  2571. BrotliEncoderState *state_ = nullptr;
  2572. };
  2573. class brotli_decompressor final : public decompressor {
  2574. public:
  2575. brotli_decompressor();
  2576. ~brotli_decompressor();
  2577. bool is_valid() const override;
  2578. bool decompress(const char *data, size_t data_length,
  2579. Callback callback) override;
  2580. private:
  2581. BrotliDecoderResult decoder_r;
  2582. BrotliDecoderState *decoder_s = nullptr;
  2583. };
  2584. #endif
  2585. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2586. class zstd_compressor : public compressor {
  2587. public:
  2588. zstd_compressor();
  2589. ~zstd_compressor();
  2590. bool compress(const char *data, size_t data_length, bool last,
  2591. Callback callback) override;
  2592. private:
  2593. ZSTD_CCtx *ctx_ = nullptr;
  2594. };
  2595. class zstd_decompressor : public decompressor {
  2596. public:
  2597. zstd_decompressor();
  2598. ~zstd_decompressor();
  2599. bool is_valid() const override;
  2600. bool decompress(const char *data, size_t data_length,
  2601. Callback callback) override;
  2602. private:
  2603. ZSTD_DCtx *ctx_ = nullptr;
  2604. };
  2605. #endif
  2606. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2607. // to store data. The call can set memory on stack for performance.
  2608. class stream_line_reader {
  2609. public:
  2610. stream_line_reader(Stream &strm, char *fixed_buffer,
  2611. size_t fixed_buffer_size);
  2612. const char *ptr() const;
  2613. size_t size() const;
  2614. bool end_with_crlf() const;
  2615. bool getline();
  2616. private:
  2617. void append(char c);
  2618. Stream &strm_;
  2619. char *fixed_buffer_;
  2620. const size_t fixed_buffer_size_;
  2621. size_t fixed_buffer_used_size_ = 0;
  2622. std::string growable_buffer_;
  2623. };
  2624. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2625. const Headers &src_headers);
  2626. struct ChunkedDecoder {
  2627. Stream &strm;
  2628. size_t chunk_remaining = 0;
  2629. bool finished = false;
  2630. char line_buf[64];
  2631. size_t last_chunk_total = 0;
  2632. size_t last_chunk_offset = 0;
  2633. explicit ChunkedDecoder(Stream &s);
  2634. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2635. size_t &out_chunk_total);
  2636. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2637. };
  2638. class mmap {
  2639. public:
  2640. mmap(const char *path);
  2641. ~mmap();
  2642. bool open(const char *path);
  2643. void close();
  2644. bool is_open() const;
  2645. size_t size() const;
  2646. const char *data() const;
  2647. private:
  2648. #if defined(_WIN32)
  2649. HANDLE hFile_ = NULL;
  2650. HANDLE hMapping_ = NULL;
  2651. #else
  2652. int fd_ = -1;
  2653. #endif
  2654. size_t size_ = 0;
  2655. void *addr_ = nullptr;
  2656. bool is_open_empty_file = false;
  2657. };
  2658. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2659. namespace fields {
  2660. bool is_token_char(char c);
  2661. bool is_token(const std::string &s);
  2662. bool is_field_name(const std::string &s);
  2663. bool is_vchar(char c);
  2664. bool is_obs_text(char c);
  2665. bool is_field_vchar(char c);
  2666. bool is_field_content(const std::string &s);
  2667. bool is_field_value(const std::string &s);
  2668. } // namespace fields
  2669. } // namespace detail
  2670. /*
  2671. * TLS Abstraction Layer Declarations
  2672. */
  2673. #ifdef CPPHTTPLIB_SSL_ENABLED
  2674. // TLS abstraction layer - backend-specific type declarations
  2675. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2676. namespace tls {
  2677. namespace impl {
  2678. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2679. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2680. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2681. struct MbedTlsContext {
  2682. mbedtls_ssl_config conf;
  2683. mbedtls_entropy_context entropy;
  2684. mbedtls_ctr_drbg_context ctr_drbg;
  2685. mbedtls_x509_crt ca_chain;
  2686. mbedtls_x509_crt own_cert;
  2687. mbedtls_pk_context own_key;
  2688. bool is_server = false;
  2689. bool verify_client = false;
  2690. bool has_verify_callback = false;
  2691. MbedTlsContext();
  2692. ~MbedTlsContext();
  2693. MbedTlsContext(const MbedTlsContext &) = delete;
  2694. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2695. };
  2696. } // namespace impl
  2697. } // namespace tls
  2698. #endif
  2699. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2700. namespace tls {
  2701. namespace impl {
  2702. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2703. // This struct is accessible via tls::impl for use in SSL context
  2704. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2705. struct WolfSSLContext {
  2706. WOLFSSL_CTX *ctx = nullptr;
  2707. bool is_server = false;
  2708. bool verify_client = false;
  2709. bool has_verify_callback = false;
  2710. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2711. WolfSSLContext();
  2712. ~WolfSSLContext();
  2713. WolfSSLContext(const WolfSSLContext &) = delete;
  2714. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2715. };
  2716. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2717. struct WolfSSLCAStore {
  2718. std::string pem_data;
  2719. };
  2720. } // namespace impl
  2721. } // namespace tls
  2722. #endif
  2723. #endif // CPPHTTPLIB_SSL_ENABLED
  2724. namespace stream {
  2725. class Result {
  2726. public:
  2727. Result();
  2728. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2729. Result(Result &&other) noexcept;
  2730. Result &operator=(Result &&other) noexcept;
  2731. Result(const Result &) = delete;
  2732. Result &operator=(const Result &) = delete;
  2733. // Response info
  2734. bool is_valid() const;
  2735. explicit operator bool() const;
  2736. int status() const;
  2737. const Headers &headers() const;
  2738. std::string get_header_value(const std::string &key,
  2739. const char *def = "") const;
  2740. bool has_header(const std::string &key) const;
  2741. Error error() const;
  2742. Error read_error() const;
  2743. bool has_read_error() const;
  2744. // Stream reading
  2745. bool next();
  2746. const char *data() const;
  2747. size_t size() const;
  2748. std::string read_all();
  2749. private:
  2750. ClientImpl::StreamHandle handle_;
  2751. std::string buffer_;
  2752. size_t current_size_ = 0;
  2753. size_t chunk_size_;
  2754. bool finished_ = false;
  2755. };
  2756. // GET
  2757. template <typename ClientType>
  2758. inline Result Get(ClientType &cli, const std::string &path,
  2759. size_t chunk_size = 8192) {
  2760. return Result{cli.open_stream("GET", path), chunk_size};
  2761. }
  2762. template <typename ClientType>
  2763. inline Result Get(ClientType &cli, const std::string &path,
  2764. const Headers &headers, size_t chunk_size = 8192) {
  2765. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2766. }
  2767. template <typename ClientType>
  2768. inline Result Get(ClientType &cli, const std::string &path,
  2769. const Params &params, size_t chunk_size = 8192) {
  2770. return Result{cli.open_stream("GET", path, params), chunk_size};
  2771. }
  2772. template <typename ClientType>
  2773. inline Result Get(ClientType &cli, const std::string &path,
  2774. const Params &params, const Headers &headers,
  2775. size_t chunk_size = 8192) {
  2776. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2777. }
  2778. // POST
  2779. template <typename ClientType>
  2780. inline Result Post(ClientType &cli, const std::string &path,
  2781. const std::string &body, const std::string &content_type,
  2782. size_t chunk_size = 8192) {
  2783. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2784. chunk_size};
  2785. }
  2786. template <typename ClientType>
  2787. inline Result Post(ClientType &cli, const std::string &path,
  2788. const Headers &headers, const std::string &body,
  2789. const std::string &content_type, size_t chunk_size = 8192) {
  2790. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2791. chunk_size};
  2792. }
  2793. template <typename ClientType>
  2794. inline Result Post(ClientType &cli, const std::string &path,
  2795. const Params &params, const std::string &body,
  2796. const std::string &content_type, size_t chunk_size = 8192) {
  2797. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2798. chunk_size};
  2799. }
  2800. template <typename ClientType>
  2801. inline Result Post(ClientType &cli, const std::string &path,
  2802. const Params &params, const Headers &headers,
  2803. const std::string &body, const std::string &content_type,
  2804. size_t chunk_size = 8192) {
  2805. return Result{
  2806. cli.open_stream("POST", path, params, headers, body, content_type),
  2807. chunk_size};
  2808. }
  2809. // PUT
  2810. template <typename ClientType>
  2811. inline Result Put(ClientType &cli, const std::string &path,
  2812. const std::string &body, const std::string &content_type,
  2813. size_t chunk_size = 8192) {
  2814. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2815. chunk_size};
  2816. }
  2817. template <typename ClientType>
  2818. inline Result Put(ClientType &cli, const std::string &path,
  2819. const Headers &headers, const std::string &body,
  2820. const std::string &content_type, size_t chunk_size = 8192) {
  2821. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2822. chunk_size};
  2823. }
  2824. template <typename ClientType>
  2825. inline Result Put(ClientType &cli, const std::string &path,
  2826. const Params &params, const std::string &body,
  2827. const std::string &content_type, size_t chunk_size = 8192) {
  2828. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2829. chunk_size};
  2830. }
  2831. template <typename ClientType>
  2832. inline Result Put(ClientType &cli, const std::string &path,
  2833. const Params &params, const Headers &headers,
  2834. const std::string &body, const std::string &content_type,
  2835. size_t chunk_size = 8192) {
  2836. return Result{
  2837. cli.open_stream("PUT", path, params, headers, body, content_type),
  2838. chunk_size};
  2839. }
  2840. // PATCH
  2841. template <typename ClientType>
  2842. inline Result Patch(ClientType &cli, const std::string &path,
  2843. const std::string &body, const std::string &content_type,
  2844. size_t chunk_size = 8192) {
  2845. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2846. chunk_size};
  2847. }
  2848. template <typename ClientType>
  2849. inline Result Patch(ClientType &cli, const std::string &path,
  2850. const Headers &headers, const std::string &body,
  2851. const std::string &content_type, size_t chunk_size = 8192) {
  2852. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2853. chunk_size};
  2854. }
  2855. template <typename ClientType>
  2856. inline Result Patch(ClientType &cli, const std::string &path,
  2857. const Params &params, const std::string &body,
  2858. const std::string &content_type, size_t chunk_size = 8192) {
  2859. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2860. chunk_size};
  2861. }
  2862. template <typename ClientType>
  2863. inline Result Patch(ClientType &cli, const std::string &path,
  2864. const Params &params, const Headers &headers,
  2865. const std::string &body, const std::string &content_type,
  2866. size_t chunk_size = 8192) {
  2867. return Result{
  2868. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2869. chunk_size};
  2870. }
  2871. // DELETE
  2872. template <typename ClientType>
  2873. inline Result Delete(ClientType &cli, const std::string &path,
  2874. size_t chunk_size = 8192) {
  2875. return Result{cli.open_stream("DELETE", path), chunk_size};
  2876. }
  2877. template <typename ClientType>
  2878. inline Result Delete(ClientType &cli, const std::string &path,
  2879. const Headers &headers, size_t chunk_size = 8192) {
  2880. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2881. }
  2882. template <typename ClientType>
  2883. inline Result Delete(ClientType &cli, const std::string &path,
  2884. const std::string &body, const std::string &content_type,
  2885. size_t chunk_size = 8192) {
  2886. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2887. chunk_size};
  2888. }
  2889. template <typename ClientType>
  2890. inline Result Delete(ClientType &cli, const std::string &path,
  2891. const Headers &headers, const std::string &body,
  2892. const std::string &content_type,
  2893. size_t chunk_size = 8192) {
  2894. return Result{
  2895. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2896. chunk_size};
  2897. }
  2898. template <typename ClientType>
  2899. inline Result Delete(ClientType &cli, const std::string &path,
  2900. const Params &params, size_t chunk_size = 8192) {
  2901. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2902. }
  2903. template <typename ClientType>
  2904. inline Result Delete(ClientType &cli, const std::string &path,
  2905. const Params &params, const Headers &headers,
  2906. size_t chunk_size = 8192) {
  2907. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2908. }
  2909. template <typename ClientType>
  2910. inline Result Delete(ClientType &cli, const std::string &path,
  2911. const Params &params, const std::string &body,
  2912. const std::string &content_type,
  2913. size_t chunk_size = 8192) {
  2914. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2915. chunk_size};
  2916. }
  2917. template <typename ClientType>
  2918. inline Result Delete(ClientType &cli, const std::string &path,
  2919. const Params &params, const Headers &headers,
  2920. const std::string &body, const std::string &content_type,
  2921. size_t chunk_size = 8192) {
  2922. return Result{
  2923. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2924. chunk_size};
  2925. }
  2926. // HEAD
  2927. template <typename ClientType>
  2928. inline Result Head(ClientType &cli, const std::string &path,
  2929. size_t chunk_size = 8192) {
  2930. return Result{cli.open_stream("HEAD", path), chunk_size};
  2931. }
  2932. template <typename ClientType>
  2933. inline Result Head(ClientType &cli, const std::string &path,
  2934. const Headers &headers, size_t chunk_size = 8192) {
  2935. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2936. }
  2937. template <typename ClientType>
  2938. inline Result Head(ClientType &cli, const std::string &path,
  2939. const Params &params, size_t chunk_size = 8192) {
  2940. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2941. }
  2942. template <typename ClientType>
  2943. inline Result Head(ClientType &cli, const std::string &path,
  2944. const Params &params, const Headers &headers,
  2945. size_t chunk_size = 8192) {
  2946. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2947. }
  2948. // OPTIONS
  2949. template <typename ClientType>
  2950. inline Result Options(ClientType &cli, const std::string &path,
  2951. size_t chunk_size = 8192) {
  2952. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2953. }
  2954. template <typename ClientType>
  2955. inline Result Options(ClientType &cli, const std::string &path,
  2956. const Headers &headers, size_t chunk_size = 8192) {
  2957. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2958. }
  2959. template <typename ClientType>
  2960. inline Result Options(ClientType &cli, const std::string &path,
  2961. const Params &params, size_t chunk_size = 8192) {
  2962. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2963. }
  2964. template <typename ClientType>
  2965. inline Result Options(ClientType &cli, const std::string &path,
  2966. const Params &params, const Headers &headers,
  2967. size_t chunk_size = 8192) {
  2968. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2969. }
  2970. } // namespace stream
  2971. namespace sse {
  2972. struct SSEMessage {
  2973. std::string event; // Event type (default: "message")
  2974. std::string data; // Event payload
  2975. std::string id; // Event ID for Last-Event-ID header
  2976. SSEMessage();
  2977. void clear();
  2978. };
  2979. class SSEClient {
  2980. public:
  2981. using MessageHandler = std::function<void(const SSEMessage &)>;
  2982. using ErrorHandler = std::function<void(Error)>;
  2983. using OpenHandler = std::function<void()>;
  2984. SSEClient(Client &client, const std::string &path);
  2985. SSEClient(Client &client, const std::string &path, const Headers &headers);
  2986. ~SSEClient();
  2987. SSEClient(const SSEClient &) = delete;
  2988. SSEClient &operator=(const SSEClient &) = delete;
  2989. // Event handlers
  2990. SSEClient &on_message(MessageHandler handler);
  2991. SSEClient &on_event(const std::string &type, MessageHandler handler);
  2992. SSEClient &on_open(OpenHandler handler);
  2993. SSEClient &on_error(ErrorHandler handler);
  2994. SSEClient &set_reconnect_interval(int ms);
  2995. SSEClient &set_max_reconnect_attempts(int n);
  2996. // Update headers (thread-safe)
  2997. SSEClient &set_headers(const Headers &headers);
  2998. // State accessors
  2999. bool is_connected() const;
  3000. const std::string &last_event_id() const;
  3001. // Blocking start - runs event loop with auto-reconnect
  3002. void start();
  3003. // Non-blocking start - runs in background thread
  3004. void start_async();
  3005. // Stop the client (thread-safe)
  3006. void stop();
  3007. private:
  3008. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3009. void run_event_loop();
  3010. void dispatch_event(const SSEMessage &msg);
  3011. bool should_reconnect(int count) const;
  3012. void wait_for_reconnect();
  3013. // Client and path
  3014. Client &client_;
  3015. std::string path_;
  3016. Headers headers_;
  3017. mutable std::mutex headers_mutex_;
  3018. // Callbacks
  3019. MessageHandler on_message_;
  3020. std::map<std::string, MessageHandler> event_handlers_;
  3021. OpenHandler on_open_;
  3022. ErrorHandler on_error_;
  3023. // Configuration
  3024. int reconnect_interval_ms_ = 3000;
  3025. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3026. // State
  3027. std::atomic<bool> running_{false};
  3028. std::atomic<bool> connected_{false};
  3029. std::string last_event_id_;
  3030. // Async support
  3031. std::thread async_thread_;
  3032. };
  3033. } // namespace sse
  3034. namespace ws {
  3035. enum class Opcode : uint8_t {
  3036. Continuation = 0x0,
  3037. Text = 0x1,
  3038. Binary = 0x2,
  3039. Close = 0x8,
  3040. Ping = 0x9,
  3041. Pong = 0xA,
  3042. };
  3043. enum class CloseStatus : uint16_t {
  3044. Normal = 1000,
  3045. GoingAway = 1001,
  3046. ProtocolError = 1002,
  3047. UnsupportedData = 1003,
  3048. NoStatus = 1005,
  3049. Abnormal = 1006,
  3050. InvalidPayload = 1007,
  3051. PolicyViolation = 1008,
  3052. MessageTooBig = 1009,
  3053. MandatoryExtension = 1010,
  3054. InternalError = 1011,
  3055. };
  3056. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3057. class WebSocket {
  3058. public:
  3059. WebSocket(const WebSocket &) = delete;
  3060. WebSocket &operator=(const WebSocket &) = delete;
  3061. ~WebSocket();
  3062. ReadResult read(std::string &msg);
  3063. bool send(const std::string &data);
  3064. bool send(const char *data, size_t len);
  3065. void close(CloseStatus status = CloseStatus::Normal,
  3066. const std::string &reason = "");
  3067. const Request &request() const;
  3068. bool is_open() const;
  3069. private:
  3070. friend class httplib::Server;
  3071. friend class WebSocketClient;
  3072. WebSocket(
  3073. Stream &strm, const Request &req, bool is_server,
  3074. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND)
  3075. : strm_(strm), req_(req), is_server_(is_server),
  3076. ping_interval_sec_(ping_interval_sec) {
  3077. start_heartbeat();
  3078. }
  3079. WebSocket(
  3080. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3081. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND)
  3082. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3083. is_server_(is_server), ping_interval_sec_(ping_interval_sec) {
  3084. start_heartbeat();
  3085. }
  3086. void start_heartbeat();
  3087. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3088. Stream &strm_;
  3089. std::unique_ptr<Stream> owned_strm_;
  3090. Request req_;
  3091. bool is_server_;
  3092. time_t ping_interval_sec_;
  3093. std::atomic<bool> closed_{false};
  3094. std::mutex write_mutex_;
  3095. std::thread ping_thread_;
  3096. std::mutex ping_mutex_;
  3097. std::condition_variable ping_cv_;
  3098. };
  3099. class WebSocketClient {
  3100. public:
  3101. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3102. const Headers &headers = {});
  3103. ~WebSocketClient();
  3104. WebSocketClient(const WebSocketClient &) = delete;
  3105. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3106. bool is_valid() const;
  3107. bool connect();
  3108. ReadResult read(std::string &msg);
  3109. bool send(const std::string &data);
  3110. bool send(const char *data, size_t len);
  3111. void close(CloseStatus status = CloseStatus::Normal,
  3112. const std::string &reason = "");
  3113. bool is_open() const;
  3114. const std::string &subprotocol() const;
  3115. void set_read_timeout(time_t sec, time_t usec = 0);
  3116. void set_write_timeout(time_t sec, time_t usec = 0);
  3117. void set_websocket_ping_interval(time_t sec);
  3118. void set_tcp_nodelay(bool on);
  3119. void set_address_family(int family);
  3120. void set_ipv6_v6only(bool on);
  3121. void set_socket_options(SocketOptions socket_options);
  3122. void set_connection_timeout(time_t sec, time_t usec = 0);
  3123. void set_interface(const std::string &intf);
  3124. #ifdef CPPHTTPLIB_SSL_ENABLED
  3125. void set_ca_cert_path(const std::string &path);
  3126. void set_ca_cert_store(tls::ca_store_t store);
  3127. void enable_server_certificate_verification(bool enabled);
  3128. #endif
  3129. private:
  3130. void shutdown_and_close();
  3131. bool create_stream(std::unique_ptr<Stream> &strm);
  3132. std::string host_;
  3133. int port_;
  3134. std::string path_;
  3135. Headers headers_;
  3136. std::string subprotocol_;
  3137. bool is_valid_ = false;
  3138. socket_t sock_ = INVALID_SOCKET;
  3139. std::unique_ptr<WebSocket> ws_;
  3140. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3141. time_t read_timeout_usec_ = 0;
  3142. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3143. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3144. time_t websocket_ping_interval_sec_ =
  3145. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3146. int address_family_ = AF_UNSPEC;
  3147. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3148. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3149. SocketOptions socket_options_ = nullptr;
  3150. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3151. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3152. std::string interface_;
  3153. #ifdef CPPHTTPLIB_SSL_ENABLED
  3154. bool is_ssl_ = false;
  3155. tls::ctx_t tls_ctx_ = nullptr;
  3156. tls::session_t tls_session_ = nullptr;
  3157. std::string ca_cert_file_path_;
  3158. tls::ca_store_t ca_cert_store_ = nullptr;
  3159. bool server_certificate_verification_ = true;
  3160. #endif
  3161. };
  3162. namespace impl {
  3163. bool is_valid_utf8(const std::string &s);
  3164. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3165. bool &fin, bool expect_masked, size_t max_len);
  3166. } // namespace impl
  3167. } // namespace ws
  3168. // ----------------------------------------------------------------------------
  3169. /*
  3170. * Implementation that will be part of the .cc file if split into .h + .cc.
  3171. */
  3172. namespace stream {
  3173. // stream::Result implementations
  3174. inline Result::Result() : chunk_size_(8192) {}
  3175. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3176. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3177. inline Result::Result(Result &&other) noexcept
  3178. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3179. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3180. finished_(other.finished_) {
  3181. other.current_size_ = 0;
  3182. other.finished_ = true;
  3183. }
  3184. inline Result &Result::operator=(Result &&other) noexcept {
  3185. if (this != &other) {
  3186. handle_ = std::move(other.handle_);
  3187. buffer_ = std::move(other.buffer_);
  3188. current_size_ = other.current_size_;
  3189. chunk_size_ = other.chunk_size_;
  3190. finished_ = other.finished_;
  3191. other.current_size_ = 0;
  3192. other.finished_ = true;
  3193. }
  3194. return *this;
  3195. }
  3196. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3197. inline Result::operator bool() const { return is_valid(); }
  3198. inline int Result::status() const {
  3199. return handle_.response ? handle_.response->status : -1;
  3200. }
  3201. inline const Headers &Result::headers() const {
  3202. static const Headers empty_headers;
  3203. return handle_.response ? handle_.response->headers : empty_headers;
  3204. }
  3205. inline std::string Result::get_header_value(const std::string &key,
  3206. const char *def) const {
  3207. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3208. }
  3209. inline bool Result::has_header(const std::string &key) const {
  3210. return handle_.response ? handle_.response->has_header(key) : false;
  3211. }
  3212. inline Error Result::error() const { return handle_.error; }
  3213. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3214. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3215. inline bool Result::next() {
  3216. if (!handle_.is_valid() || finished_) { return false; }
  3217. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3218. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3219. if (n > 0) {
  3220. current_size_ = static_cast<size_t>(n);
  3221. return true;
  3222. }
  3223. current_size_ = 0;
  3224. finished_ = true;
  3225. return false;
  3226. }
  3227. inline const char *Result::data() const { return buffer_.data(); }
  3228. inline size_t Result::size() const { return current_size_; }
  3229. inline std::string Result::read_all() {
  3230. std::string result;
  3231. while (next()) {
  3232. result.append(data(), size());
  3233. }
  3234. return result;
  3235. }
  3236. } // namespace stream
  3237. namespace sse {
  3238. // SSEMessage implementations
  3239. inline SSEMessage::SSEMessage() : event("message") {}
  3240. inline void SSEMessage::clear() {
  3241. event = "message";
  3242. data.clear();
  3243. id.clear();
  3244. }
  3245. // SSEClient implementations
  3246. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3247. : client_(client), path_(path) {}
  3248. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3249. const Headers &headers)
  3250. : client_(client), path_(path), headers_(headers) {}
  3251. inline SSEClient::~SSEClient() { stop(); }
  3252. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3253. on_message_ = std::move(handler);
  3254. return *this;
  3255. }
  3256. inline SSEClient &SSEClient::on_event(const std::string &type,
  3257. MessageHandler handler) {
  3258. event_handlers_[type] = std::move(handler);
  3259. return *this;
  3260. }
  3261. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3262. on_open_ = std::move(handler);
  3263. return *this;
  3264. }
  3265. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3266. on_error_ = std::move(handler);
  3267. return *this;
  3268. }
  3269. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3270. reconnect_interval_ms_ = ms;
  3271. return *this;
  3272. }
  3273. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3274. max_reconnect_attempts_ = n;
  3275. return *this;
  3276. }
  3277. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3278. std::lock_guard<std::mutex> lock(headers_mutex_);
  3279. headers_ = headers;
  3280. return *this;
  3281. }
  3282. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3283. inline const std::string &SSEClient::last_event_id() const {
  3284. return last_event_id_;
  3285. }
  3286. inline void SSEClient::start() {
  3287. running_.store(true);
  3288. run_event_loop();
  3289. }
  3290. inline void SSEClient::start_async() {
  3291. running_.store(true);
  3292. async_thread_ = std::thread([this]() { run_event_loop(); });
  3293. }
  3294. inline void SSEClient::stop() {
  3295. running_.store(false);
  3296. client_.stop(); // Cancel any pending operations
  3297. if (async_thread_.joinable()) { async_thread_.join(); }
  3298. }
  3299. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3300. int &retry_ms) {
  3301. // Blank line signals end of event
  3302. if (line.empty() || line == "\r") { return true; }
  3303. // Lines starting with ':' are comments (ignored)
  3304. if (!line.empty() && line[0] == ':') { return false; }
  3305. // Find the colon separator
  3306. auto colon_pos = line.find(':');
  3307. if (colon_pos == std::string::npos) {
  3308. // Line with no colon is treated as field name with empty value
  3309. return false;
  3310. }
  3311. auto field = line.substr(0, colon_pos);
  3312. std::string value;
  3313. // Value starts after colon, skip optional single space
  3314. if (colon_pos + 1 < line.size()) {
  3315. auto value_start = colon_pos + 1;
  3316. if (line[value_start] == ' ') { value_start++; }
  3317. value = line.substr(value_start);
  3318. // Remove trailing \r if present
  3319. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3320. }
  3321. // Handle known fields
  3322. if (field == "event") {
  3323. msg.event = value;
  3324. } else if (field == "data") {
  3325. // Multiple data lines are concatenated with newlines
  3326. if (!msg.data.empty()) { msg.data += "\n"; }
  3327. msg.data += value;
  3328. } else if (field == "id") {
  3329. // Empty id is valid (clears the last event ID)
  3330. msg.id = value;
  3331. } else if (field == "retry") {
  3332. // Parse retry interval in milliseconds
  3333. {
  3334. int v = 0;
  3335. auto res =
  3336. detail::from_chars(value.data(), value.data() + value.size(), v);
  3337. if (res.ec == std::errc{}) { retry_ms = v; }
  3338. }
  3339. }
  3340. // Unknown fields are ignored per SSE spec
  3341. return false;
  3342. }
  3343. inline void SSEClient::run_event_loop() {
  3344. auto reconnect_count = 0;
  3345. while (running_.load()) {
  3346. // Build headers, including Last-Event-ID if we have one
  3347. Headers request_headers;
  3348. {
  3349. std::lock_guard<std::mutex> lock(headers_mutex_);
  3350. request_headers = headers_;
  3351. }
  3352. if (!last_event_id_.empty()) {
  3353. request_headers.emplace("Last-Event-ID", last_event_id_);
  3354. }
  3355. // Open streaming connection
  3356. auto result = stream::Get(client_, path_, request_headers);
  3357. // Connection error handling
  3358. if (!result) {
  3359. connected_.store(false);
  3360. if (on_error_) { on_error_(result.error()); }
  3361. if (!should_reconnect(reconnect_count)) { break; }
  3362. wait_for_reconnect();
  3363. reconnect_count++;
  3364. continue;
  3365. }
  3366. if (result.status() != StatusCode::OK_200) {
  3367. connected_.store(false);
  3368. if (on_error_) { on_error_(Error::Connection); }
  3369. // For certain errors, don't reconnect.
  3370. // Note: 401 is intentionally absent so that handlers can refresh
  3371. // credentials via set_headers() and let the client reconnect.
  3372. if (result.status() == StatusCode::NoContent_204 ||
  3373. result.status() == StatusCode::NotFound_404 ||
  3374. result.status() == StatusCode::Forbidden_403) {
  3375. break;
  3376. }
  3377. if (!should_reconnect(reconnect_count)) { break; }
  3378. wait_for_reconnect();
  3379. reconnect_count++;
  3380. continue;
  3381. }
  3382. // Connection successful
  3383. connected_.store(true);
  3384. reconnect_count = 0;
  3385. if (on_open_) { on_open_(); }
  3386. // Event receiving loop
  3387. std::string buffer;
  3388. SSEMessage current_msg;
  3389. while (running_.load() && result.next()) {
  3390. buffer.append(result.data(), result.size());
  3391. // Process complete lines in the buffer
  3392. size_t line_start = 0;
  3393. size_t newline_pos;
  3394. while ((newline_pos = buffer.find('\n', line_start)) !=
  3395. std::string::npos) {
  3396. auto line = buffer.substr(line_start, newline_pos - line_start);
  3397. line_start = newline_pos + 1;
  3398. // Parse the line and check if event is complete
  3399. auto event_complete =
  3400. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3401. if (event_complete && !current_msg.data.empty()) {
  3402. // Update last_event_id for reconnection
  3403. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3404. // Dispatch event to appropriate handler
  3405. dispatch_event(current_msg);
  3406. current_msg.clear();
  3407. }
  3408. }
  3409. // Keep unprocessed data in buffer
  3410. buffer.erase(0, line_start);
  3411. }
  3412. // Connection ended
  3413. connected_.store(false);
  3414. if (!running_.load()) { break; }
  3415. // Check for read errors
  3416. if (result.has_read_error()) {
  3417. if (on_error_) { on_error_(result.read_error()); }
  3418. }
  3419. if (!should_reconnect(reconnect_count)) { break; }
  3420. wait_for_reconnect();
  3421. reconnect_count++;
  3422. }
  3423. connected_.store(false);
  3424. }
  3425. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3426. // Check for specific event type handler first
  3427. auto it = event_handlers_.find(msg.event);
  3428. if (it != event_handlers_.end()) {
  3429. it->second(msg);
  3430. return;
  3431. }
  3432. // Fall back to generic message handler
  3433. if (on_message_) { on_message_(msg); }
  3434. }
  3435. inline bool SSEClient::should_reconnect(int count) const {
  3436. if (!running_.load()) { return false; }
  3437. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3438. return count < max_reconnect_attempts_;
  3439. }
  3440. inline void SSEClient::wait_for_reconnect() {
  3441. // Use small increments to check running_ flag frequently
  3442. auto waited = 0;
  3443. while (running_.load() && waited < reconnect_interval_ms_) {
  3444. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3445. waited += 100;
  3446. }
  3447. }
  3448. } // namespace sse
  3449. #ifdef CPPHTTPLIB_SSL_ENABLED
  3450. /*
  3451. * TLS abstraction layer - internal function declarations
  3452. * These are implementation details and not part of the public API.
  3453. */
  3454. namespace tls {
  3455. // Client context
  3456. ctx_t create_client_context();
  3457. void free_context(ctx_t ctx);
  3458. bool set_min_version(ctx_t ctx, Version version);
  3459. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3460. bool load_ca_file(ctx_t ctx, const char *file_path);
  3461. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3462. bool load_system_certs(ctx_t ctx);
  3463. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3464. const char *password);
  3465. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3466. const char *key_path, const char *password);
  3467. // Server context
  3468. ctx_t create_server_context();
  3469. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3470. const char *password);
  3471. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3472. const char *key_path, const char *password);
  3473. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3474. void set_verify_client(ctx_t ctx, bool require);
  3475. // Session management
  3476. session_t create_session(ctx_t ctx, socket_t sock);
  3477. void free_session(session_t session);
  3478. bool set_sni(session_t session, const char *hostname);
  3479. bool set_hostname(session_t session, const char *hostname);
  3480. // Handshake (non-blocking capable)
  3481. TlsError connect(session_t session);
  3482. TlsError accept(session_t session);
  3483. // Handshake with timeout (blocking until timeout)
  3484. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3485. time_t timeout_usec, TlsError *err);
  3486. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3487. time_t timeout_usec, TlsError *err);
  3488. // I/O (non-blocking capable)
  3489. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3490. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3491. int pending(const_session_t session);
  3492. void shutdown(session_t session, bool graceful);
  3493. // Connection state
  3494. bool is_peer_closed(session_t session, socket_t sock);
  3495. // Certificate verification
  3496. cert_t get_peer_cert(const_session_t session);
  3497. void free_cert(cert_t cert);
  3498. bool verify_hostname(cert_t cert, const char *hostname);
  3499. uint64_t hostname_mismatch_code();
  3500. long get_verify_result(const_session_t session);
  3501. // Certificate introspection
  3502. std::string get_cert_subject_cn(cert_t cert);
  3503. std::string get_cert_issuer_name(cert_t cert);
  3504. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3505. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3506. std::string get_cert_serial(cert_t cert);
  3507. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3508. const char *get_sni(const_session_t session);
  3509. // CA store management
  3510. ca_store_t create_ca_store(const char *pem, size_t len);
  3511. void free_ca_store(ca_store_t store);
  3512. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3513. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3514. std::vector<std::string> get_ca_names(ctx_t ctx);
  3515. // Dynamic certificate update (for servers)
  3516. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3517. const char *password);
  3518. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3519. // Certificate verification callback
  3520. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3521. long get_verify_error(const_session_t session);
  3522. std::string verify_error_string(long error_code);
  3523. // TlsError information
  3524. uint64_t peek_error();
  3525. uint64_t get_error();
  3526. std::string error_string(uint64_t code);
  3527. } // namespace tls
  3528. #endif // CPPHTTPLIB_SSL_ENABLED
  3529. /*
  3530. * Group 1: detail namespace - Non-SSL utilities
  3531. */
  3532. namespace detail {
  3533. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3534. const void *optval, socklen_t optlen) {
  3535. return setsockopt(sock, level, optname,
  3536. #ifdef _WIN32
  3537. reinterpret_cast<const char *>(optval),
  3538. #else
  3539. optval,
  3540. #endif
  3541. optlen) == 0;
  3542. }
  3543. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  3544. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  3545. }
  3546. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3547. time_t sec, time_t usec) {
  3548. #ifdef _WIN32
  3549. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3550. #else
  3551. timeval timeout;
  3552. timeout.tv_sec = static_cast<long>(sec);
  3553. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3554. #endif
  3555. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3556. }
  3557. inline bool is_hex(char c, int &v) {
  3558. if (isdigit(c)) {
  3559. v = c - '0';
  3560. return true;
  3561. } else if ('A' <= c && c <= 'F') {
  3562. v = c - 'A' + 10;
  3563. return true;
  3564. } else if ('a' <= c && c <= 'f') {
  3565. v = c - 'a' + 10;
  3566. return true;
  3567. }
  3568. return false;
  3569. }
  3570. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3571. int &val) {
  3572. if (i >= s.size()) { return false; }
  3573. val = 0;
  3574. for (; cnt; i++, cnt--) {
  3575. if (!s[i]) { return false; }
  3576. auto v = 0;
  3577. if (is_hex(s[i], v)) {
  3578. val = val * 16 + v;
  3579. } else {
  3580. return false;
  3581. }
  3582. }
  3583. return true;
  3584. }
  3585. inline std::string from_i_to_hex(size_t n) {
  3586. static const auto charset = "0123456789abcdef";
  3587. std::string ret;
  3588. do {
  3589. ret = charset[n & 15] + ret;
  3590. n >>= 4;
  3591. } while (n > 0);
  3592. return ret;
  3593. }
  3594. inline std::string compute_etag(const FileStat &fs) {
  3595. if (!fs.is_file()) { return std::string(); }
  3596. // If mtime cannot be determined (negative value indicates an error
  3597. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3598. // value like 0 could collide with a real file that legitimately has
  3599. // mtime == 0 (epoch) and lead to misleading validators.
  3600. auto mtime_raw = fs.mtime();
  3601. if (mtime_raw < 0) { return std::string(); }
  3602. auto mtime = static_cast<size_t>(mtime_raw);
  3603. auto size = fs.size();
  3604. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3605. from_i_to_hex(size) + "\"";
  3606. }
  3607. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3608. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3609. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3610. inline std::string file_mtime_to_http_date(time_t mtime) {
  3611. if (mtime < 0) { return std::string(); }
  3612. struct tm tm_buf;
  3613. #ifdef _WIN32
  3614. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3615. #else
  3616. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3617. #endif
  3618. char buf[64];
  3619. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3620. return std::string();
  3621. }
  3622. return std::string(buf);
  3623. }
  3624. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3625. inline time_t parse_http_date(const std::string &date_str) {
  3626. struct tm tm_buf;
  3627. // Create a classic locale object once for all parsing attempts
  3628. const std::locale classic_locale = std::locale::classic();
  3629. // Try to parse using std::get_time (C++11, cross-platform)
  3630. auto try_parse = [&](const char *fmt) -> bool {
  3631. std::istringstream ss(date_str);
  3632. ss.imbue(classic_locale);
  3633. memset(&tm_buf, 0, sizeof(tm_buf));
  3634. ss >> std::get_time(&tm_buf, fmt);
  3635. return !ss.fail();
  3636. };
  3637. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3638. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3639. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3640. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3641. // asctime format: "Sun Nov 6 08:49:37 1994"
  3642. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3643. return static_cast<time_t>(-1);
  3644. }
  3645. }
  3646. }
  3647. #ifdef _WIN32
  3648. return _mkgmtime(&tm_buf);
  3649. #elif defined _AIX
  3650. return mktime(&tm_buf);
  3651. #else
  3652. return timegm(&tm_buf);
  3653. #endif
  3654. }
  3655. inline bool is_weak_etag(const std::string &s) {
  3656. // Check if the string is a weak ETag (starts with 'W/"')
  3657. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3658. }
  3659. inline bool is_strong_etag(const std::string &s) {
  3660. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3661. // chars)
  3662. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3663. }
  3664. inline size_t to_utf8(int code, char *buff) {
  3665. if (code < 0x0080) {
  3666. buff[0] = static_cast<char>(code & 0x7F);
  3667. return 1;
  3668. } else if (code < 0x0800) {
  3669. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3670. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3671. return 2;
  3672. } else if (code < 0xD800) {
  3673. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3674. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3675. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3676. return 3;
  3677. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3678. return 0;
  3679. } else if (code < 0x10000) {
  3680. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3681. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3682. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3683. return 3;
  3684. } else if (code < 0x110000) {
  3685. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3686. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3687. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3688. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3689. return 4;
  3690. }
  3691. // NOTREACHED
  3692. return 0;
  3693. }
  3694. } // namespace detail
  3695. namespace ws {
  3696. namespace impl {
  3697. inline bool is_valid_utf8(const std::string &s) {
  3698. size_t i = 0;
  3699. auto n = s.size();
  3700. while (i < n) {
  3701. auto c = static_cast<unsigned char>(s[i]);
  3702. size_t len;
  3703. uint32_t cp;
  3704. if (c < 0x80) {
  3705. i++;
  3706. continue;
  3707. } else if ((c & 0xE0) == 0xC0) {
  3708. len = 2;
  3709. cp = c & 0x1F;
  3710. } else if ((c & 0xF0) == 0xE0) {
  3711. len = 3;
  3712. cp = c & 0x0F;
  3713. } else if ((c & 0xF8) == 0xF0) {
  3714. len = 4;
  3715. cp = c & 0x07;
  3716. } else {
  3717. return false;
  3718. }
  3719. if (i + len > n) { return false; }
  3720. for (size_t j = 1; j < len; j++) {
  3721. auto b = static_cast<unsigned char>(s[i + j]);
  3722. if ((b & 0xC0) != 0x80) { return false; }
  3723. cp = (cp << 6) | (b & 0x3F);
  3724. }
  3725. // Overlong encoding check
  3726. if (len == 2 && cp < 0x80) { return false; }
  3727. if (len == 3 && cp < 0x800) { return false; }
  3728. if (len == 4 && cp < 0x10000) { return false; }
  3729. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3730. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3731. if (cp > 0x10FFFF) { return false; }
  3732. i += len;
  3733. }
  3734. return true;
  3735. }
  3736. } // namespace impl
  3737. } // namespace ws
  3738. namespace detail {
  3739. // NOTE: This code came up with the following stackoverflow post:
  3740. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3741. inline std::string base64_encode(const std::string &in) {
  3742. static const auto lookup =
  3743. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3744. std::string out;
  3745. out.reserve(in.size());
  3746. auto val = 0;
  3747. auto valb = -6;
  3748. for (auto c : in) {
  3749. val = (val << 8) + static_cast<uint8_t>(c);
  3750. valb += 8;
  3751. while (valb >= 0) {
  3752. out.push_back(lookup[(val >> valb) & 0x3F]);
  3753. valb -= 6;
  3754. }
  3755. }
  3756. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3757. while (out.size() % 4) {
  3758. out.push_back('=');
  3759. }
  3760. return out;
  3761. }
  3762. inline std::string sha1(const std::string &input) {
  3763. // RFC 3174 SHA-1 implementation
  3764. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3765. return (x << n) | (x >> (32 - n));
  3766. };
  3767. uint32_t h0 = 0x67452301;
  3768. uint32_t h1 = 0xEFCDAB89;
  3769. uint32_t h2 = 0x98BADCFE;
  3770. uint32_t h3 = 0x10325476;
  3771. uint32_t h4 = 0xC3D2E1F0;
  3772. // Pre-processing: adding padding bits
  3773. std::string msg = input;
  3774. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3775. msg.push_back(static_cast<char>(0x80));
  3776. while (msg.size() % 64 != 56) {
  3777. msg.push_back(0);
  3778. }
  3779. // Append original length in bits as 64-bit big-endian
  3780. for (int i = 56; i >= 0; i -= 8) {
  3781. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3782. }
  3783. // Process each 512-bit chunk
  3784. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3785. uint32_t w[80];
  3786. for (size_t i = 0; i < 16; i++) {
  3787. w[i] =
  3788. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3789. << 24) |
  3790. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3791. << 16) |
  3792. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3793. << 8) |
  3794. (static_cast<uint32_t>(
  3795. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3796. }
  3797. for (int i = 16; i < 80; i++) {
  3798. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3799. }
  3800. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3801. for (int i = 0; i < 80; i++) {
  3802. uint32_t f, k;
  3803. if (i < 20) {
  3804. f = (b & c) | ((~b) & d);
  3805. k = 0x5A827999;
  3806. } else if (i < 40) {
  3807. f = b ^ c ^ d;
  3808. k = 0x6ED9EBA1;
  3809. } else if (i < 60) {
  3810. f = (b & c) | (b & d) | (c & d);
  3811. k = 0x8F1BBCDC;
  3812. } else {
  3813. f = b ^ c ^ d;
  3814. k = 0xCA62C1D6;
  3815. }
  3816. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3817. e = d;
  3818. d = c;
  3819. c = left_rotate(b, 30);
  3820. b = a;
  3821. a = temp;
  3822. }
  3823. h0 += a;
  3824. h1 += b;
  3825. h2 += c;
  3826. h3 += d;
  3827. h4 += e;
  3828. }
  3829. // Produce the final hash as a 20-byte binary string
  3830. std::string hash(20, '\0');
  3831. for (size_t i = 0; i < 4; i++) {
  3832. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3833. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3834. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3835. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3836. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3837. }
  3838. return hash;
  3839. }
  3840. inline std::string websocket_accept_key(const std::string &client_key) {
  3841. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3842. return base64_encode(sha1(client_key + magic));
  3843. }
  3844. inline bool is_websocket_upgrade(const Request &req) {
  3845. if (req.method != "GET") { return false; }
  3846. // Check Upgrade: websocket (case-insensitive)
  3847. auto upgrade_it = req.headers.find("Upgrade");
  3848. if (upgrade_it == req.headers.end()) { return false; }
  3849. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3850. if (upgrade_val != "websocket") { return false; }
  3851. // Check Connection header contains "Upgrade"
  3852. auto connection_it = req.headers.find("Connection");
  3853. if (connection_it == req.headers.end()) { return false; }
  3854. auto connection_val = case_ignore::to_lower(connection_it->second);
  3855. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3856. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3857. // RFC 6455 Section 4.2.1
  3858. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3859. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3860. return false;
  3861. }
  3862. static const std::string b64chars =
  3863. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3864. for (size_t i = 0; i < 22; i++) {
  3865. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3866. }
  3867. // Check Sec-WebSocket-Version: 13
  3868. auto version = req.get_header_value("Sec-WebSocket-Version");
  3869. if (version != "13") { return false; }
  3870. return true;
  3871. }
  3872. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3873. const char *data, size_t len, bool fin,
  3874. bool mask) {
  3875. // First byte: FIN + opcode
  3876. uint8_t header[2];
  3877. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3878. (static_cast<uint8_t>(opcode) & 0x0F));
  3879. // Second byte: MASK + payload length
  3880. if (len < 126) {
  3881. header[1] = static_cast<uint8_t>(len);
  3882. if (mask) { header[1] |= 0x80; }
  3883. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3884. } else if (len <= 0xFFFF) {
  3885. header[1] = 126;
  3886. if (mask) { header[1] |= 0x80; }
  3887. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3888. uint8_t ext[2];
  3889. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  3890. ext[1] = static_cast<uint8_t>(len & 0xFF);
  3891. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  3892. } else {
  3893. header[1] = 127;
  3894. if (mask) { header[1] |= 0x80; }
  3895. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3896. uint8_t ext[8];
  3897. for (int i = 7; i >= 0; i--) {
  3898. ext[7 - i] = static_cast<uint8_t>((len >> (i * 8)) & 0xFF);
  3899. }
  3900. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  3901. }
  3902. if (mask) {
  3903. // Generate random mask key
  3904. thread_local std::mt19937 rng(std::random_device{}());
  3905. uint8_t mask_key[4];
  3906. auto r = rng();
  3907. std::memcpy(mask_key, &r, 4);
  3908. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  3909. // Write masked payload in chunks
  3910. const size_t chunk_size = 4096;
  3911. std::vector<char> buf((std::min)(len, chunk_size));
  3912. for (size_t offset = 0; offset < len; offset += chunk_size) {
  3913. size_t n = (std::min)(chunk_size, len - offset);
  3914. for (size_t i = 0; i < n; i++) {
  3915. buf[i] =
  3916. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  3917. }
  3918. if (strm.write(buf.data(), n) < 0) { return false; }
  3919. }
  3920. } else {
  3921. if (len > 0) {
  3922. if (strm.write(data, len) < 0) { return false; }
  3923. }
  3924. }
  3925. return true;
  3926. }
  3927. } // namespace detail
  3928. namespace ws {
  3929. namespace impl {
  3930. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  3931. std::string &payload, bool &fin,
  3932. bool expect_masked, size_t max_len) {
  3933. // Read first 2 bytes
  3934. uint8_t header[2];
  3935. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  3936. fin = (header[0] & 0x80) != 0;
  3937. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  3938. if (header[0] & 0x70) { return false; }
  3939. opcode = static_cast<Opcode>(header[0] & 0x0F);
  3940. bool masked = (header[1] & 0x80) != 0;
  3941. uint64_t payload_len = header[1] & 0x7F;
  3942. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  3943. // MUST have a payload length of 125 bytes or less
  3944. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  3945. if (is_control) {
  3946. if (!fin) { return false; }
  3947. if (payload_len > 125) { return false; }
  3948. }
  3949. if (masked != expect_masked) { return false; }
  3950. // Extended payload length
  3951. if (payload_len == 126) {
  3952. uint8_t ext[2];
  3953. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  3954. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  3955. } else if (payload_len == 127) {
  3956. uint8_t ext[8];
  3957. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  3958. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  3959. if (ext[0] & 0x80) { return false; }
  3960. payload_len = 0;
  3961. for (int i = 0; i < 8; i++) {
  3962. payload_len = (payload_len << 8) | ext[i];
  3963. }
  3964. }
  3965. if (payload_len > max_len) { return false; }
  3966. // Read mask key if present
  3967. uint8_t mask_key[4] = {0};
  3968. if (masked) {
  3969. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  3970. }
  3971. // Read payload
  3972. payload.resize(static_cast<size_t>(payload_len));
  3973. if (payload_len > 0) {
  3974. size_t total_read = 0;
  3975. while (total_read < payload_len) {
  3976. auto n = strm.read(&payload[total_read],
  3977. static_cast<size_t>(payload_len - total_read));
  3978. if (n <= 0) { return false; }
  3979. total_read += static_cast<size_t>(n);
  3980. }
  3981. }
  3982. // Unmask if needed
  3983. if (masked) {
  3984. for (size_t i = 0; i < payload.size(); i++) {
  3985. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  3986. }
  3987. }
  3988. return true;
  3989. }
  3990. } // namespace impl
  3991. } // namespace ws
  3992. namespace detail {
  3993. inline bool is_valid_path(const std::string &path) {
  3994. size_t level = 0;
  3995. size_t i = 0;
  3996. // Skip slash
  3997. while (i < path.size() && path[i] == '/') {
  3998. i++;
  3999. }
  4000. while (i < path.size()) {
  4001. // Read component
  4002. auto beg = i;
  4003. while (i < path.size() && path[i] != '/') {
  4004. if (path[i] == '\0') {
  4005. return false;
  4006. } else if (path[i] == '\\') {
  4007. return false;
  4008. }
  4009. i++;
  4010. }
  4011. auto len = i - beg;
  4012. assert(len > 0);
  4013. if (!path.compare(beg, len, ".")) {
  4014. ;
  4015. } else if (!path.compare(beg, len, "..")) {
  4016. if (level == 0) { return false; }
  4017. level--;
  4018. } else {
  4019. level++;
  4020. }
  4021. // Skip slash
  4022. while (i < path.size() && path[i] == '/') {
  4023. i++;
  4024. }
  4025. }
  4026. return true;
  4027. }
  4028. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4029. #if defined(_WIN32)
  4030. char buf[_MAX_PATH];
  4031. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4032. resolved = buf;
  4033. #else
  4034. char buf[PATH_MAX];
  4035. if (realpath(path, buf) == nullptr) { return false; }
  4036. resolved = buf;
  4037. #endif
  4038. return true;
  4039. }
  4040. inline bool is_path_within_base(const std::string &resolved_path,
  4041. const std::string &resolved_base) {
  4042. #if defined(_WIN32)
  4043. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4044. resolved_base.size()) == 0;
  4045. #else
  4046. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4047. resolved_base.size()) == 0;
  4048. #endif
  4049. }
  4050. inline FileStat::FileStat(const std::string &path) {
  4051. #if defined(_WIN32)
  4052. auto wpath = u8string_to_wstring(path.c_str());
  4053. ret_ = _wstat(wpath.c_str(), &st_);
  4054. #else
  4055. ret_ = stat(path.c_str(), &st_);
  4056. #endif
  4057. }
  4058. inline bool FileStat::is_file() const {
  4059. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4060. }
  4061. inline bool FileStat::is_dir() const {
  4062. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4063. }
  4064. inline time_t FileStat::mtime() const {
  4065. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4066. : static_cast<time_t>(-1);
  4067. }
  4068. inline size_t FileStat::size() const {
  4069. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4070. }
  4071. inline std::string encode_path(const std::string &s) {
  4072. std::string result;
  4073. result.reserve(s.size());
  4074. for (size_t i = 0; s[i]; i++) {
  4075. switch (s[i]) {
  4076. case ' ': result += "%20"; break;
  4077. case '+': result += "%2B"; break;
  4078. case '\r': result += "%0D"; break;
  4079. case '\n': result += "%0A"; break;
  4080. case '\'': result += "%27"; break;
  4081. case ',': result += "%2C"; break;
  4082. // case ':': result += "%3A"; break; // ok? probably...
  4083. case ';': result += "%3B"; break;
  4084. default:
  4085. auto c = static_cast<uint8_t>(s[i]);
  4086. if (c >= 0x80) {
  4087. result += '%';
  4088. char hex[4];
  4089. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4090. assert(len == 2);
  4091. result.append(hex, static_cast<size_t>(len));
  4092. } else {
  4093. result += s[i];
  4094. }
  4095. break;
  4096. }
  4097. }
  4098. return result;
  4099. }
  4100. inline std::string file_extension(const std::string &path) {
  4101. std::smatch m;
  4102. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4103. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4104. return std::string();
  4105. }
  4106. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4107. template <typename T>
  4108. inline bool parse_header(const char *beg, const char *end, T fn);
  4109. template <typename T>
  4110. inline bool parse_header(const char *beg, const char *end, T fn) {
  4111. // Skip trailing spaces and tabs.
  4112. while (beg < end && is_space_or_tab(end[-1])) {
  4113. end--;
  4114. }
  4115. auto p = beg;
  4116. while (p < end && *p != ':') {
  4117. p++;
  4118. }
  4119. auto name = std::string(beg, p);
  4120. if (!detail::fields::is_field_name(name)) { return false; }
  4121. if (p == end) { return false; }
  4122. auto key_end = p;
  4123. if (*p++ != ':') { return false; }
  4124. while (p < end && is_space_or_tab(*p)) {
  4125. p++;
  4126. }
  4127. if (p <= end) {
  4128. auto key_len = key_end - beg;
  4129. if (!key_len) { return false; }
  4130. auto key = std::string(beg, key_end);
  4131. auto val = std::string(p, end);
  4132. if (!detail::fields::is_field_value(val)) { return false; }
  4133. if (case_ignore::equal(key, "Location") ||
  4134. case_ignore::equal(key, "Referer")) {
  4135. fn(key, val);
  4136. } else {
  4137. fn(key, decode_path_component(val));
  4138. }
  4139. return true;
  4140. }
  4141. return false;
  4142. }
  4143. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4144. const Headers &src_headers) {
  4145. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4146. // transfer coding is complete when a chunk with a chunk-size of zero is
  4147. // received, possibly followed by a trailer section, and finally terminated by
  4148. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4149. //
  4150. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4151. // doesn't care for the existence of the final CRLF. In other words, it seems
  4152. // to be ok whether the final CRLF exists or not in the chunked data.
  4153. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4154. //
  4155. // According to the reference code in RFC 9112, cpp-httplib now allows
  4156. // chunked transfer coding data without the final CRLF.
  4157. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4158. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4159. "transfer-encoding",
  4160. "content-length",
  4161. "host",
  4162. "authorization",
  4163. "www-authenticate",
  4164. "proxy-authenticate",
  4165. "proxy-authorization",
  4166. "cookie",
  4167. "set-cookie",
  4168. "cache-control",
  4169. "expect",
  4170. "max-forwards",
  4171. "pragma",
  4172. "range",
  4173. "te",
  4174. "age",
  4175. "expires",
  4176. "date",
  4177. "location",
  4178. "retry-after",
  4179. "vary",
  4180. "warning",
  4181. "content-encoding",
  4182. "content-type",
  4183. "content-range",
  4184. "trailer"};
  4185. case_ignore::unordered_set<std::string> declared_trailers;
  4186. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4187. if (trailer_header && std::strlen(trailer_header)) {
  4188. auto len = std::strlen(trailer_header);
  4189. split(trailer_header, trailer_header + len, ',',
  4190. [&](const char *b, const char *e) {
  4191. const char *kbeg = b;
  4192. const char *kend = e;
  4193. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4194. ++kbeg;
  4195. }
  4196. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4197. --kend;
  4198. }
  4199. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4200. if (!key.empty() &&
  4201. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4202. declared_trailers.insert(key);
  4203. }
  4204. });
  4205. }
  4206. size_t trailer_header_count = 0;
  4207. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4208. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4209. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4210. constexpr auto line_terminator_len = 2;
  4211. auto line_beg = line_reader.ptr();
  4212. auto line_end =
  4213. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4214. if (!parse_header(line_beg, line_end,
  4215. [&](const std::string &key, const std::string &val) {
  4216. if (declared_trailers.find(key) !=
  4217. declared_trailers.end()) {
  4218. dest.emplace(key, val);
  4219. trailer_header_count++;
  4220. }
  4221. })) {
  4222. return false;
  4223. }
  4224. if (!line_reader.getline()) { return false; }
  4225. }
  4226. return true;
  4227. }
  4228. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4229. size_t right) {
  4230. while (b + left < e && is_space_or_tab(b[left])) {
  4231. left++;
  4232. }
  4233. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4234. right--;
  4235. }
  4236. return std::make_pair(left, right);
  4237. }
  4238. inline std::string trim_copy(const std::string &s) {
  4239. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4240. return s.substr(r.first, r.second - r.first);
  4241. }
  4242. inline std::string trim_double_quotes_copy(const std::string &s) {
  4243. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4244. return s.substr(1, s.size() - 2);
  4245. }
  4246. return s;
  4247. }
  4248. inline void
  4249. divide(const char *data, std::size_t size, char d,
  4250. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4251. fn) {
  4252. const auto it = std::find(data, data + size, d);
  4253. const auto found = static_cast<std::size_t>(it != data + size);
  4254. const auto lhs_data = data;
  4255. const auto lhs_size = static_cast<std::size_t>(it - data);
  4256. const auto rhs_data = it + found;
  4257. const auto rhs_size = size - lhs_size - found;
  4258. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4259. }
  4260. inline void
  4261. divide(const std::string &str, char d,
  4262. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4263. fn) {
  4264. divide(str.data(), str.size(), d, std::move(fn));
  4265. }
  4266. inline void split(const char *b, const char *e, char d,
  4267. std::function<void(const char *, const char *)> fn) {
  4268. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4269. }
  4270. inline void split(const char *b, const char *e, char d, size_t m,
  4271. std::function<void(const char *, const char *)> fn) {
  4272. size_t i = 0;
  4273. size_t beg = 0;
  4274. size_t count = 1;
  4275. while (e ? (b + i < e) : (b[i] != '\0')) {
  4276. if (b[i] == d && count < m) {
  4277. auto r = trim(b, e, beg, i);
  4278. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4279. beg = i + 1;
  4280. count++;
  4281. }
  4282. i++;
  4283. }
  4284. if (i) {
  4285. auto r = trim(b, e, beg, i);
  4286. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4287. }
  4288. }
  4289. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4290. std::function<bool(const char *, const char *)> fn) {
  4291. size_t i = 0;
  4292. size_t beg = 0;
  4293. size_t count = 1;
  4294. while (e ? (b + i < e) : (b[i] != '\0')) {
  4295. if (b[i] == d && count < m) {
  4296. auto r = trim(b, e, beg, i);
  4297. if (r.first < r.second) {
  4298. auto found = fn(&b[r.first], &b[r.second]);
  4299. if (found) { return true; }
  4300. }
  4301. beg = i + 1;
  4302. count++;
  4303. }
  4304. i++;
  4305. }
  4306. if (i) {
  4307. auto r = trim(b, e, beg, i);
  4308. if (r.first < r.second) {
  4309. auto found = fn(&b[r.first], &b[r.second]);
  4310. if (found) { return true; }
  4311. }
  4312. }
  4313. return false;
  4314. }
  4315. inline bool split_find(const char *b, const char *e, char d,
  4316. std::function<bool(const char *, const char *)> fn) {
  4317. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4318. std::move(fn));
  4319. }
  4320. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4321. size_t fixed_buffer_size)
  4322. : strm_(strm), fixed_buffer_(fixed_buffer),
  4323. fixed_buffer_size_(fixed_buffer_size) {}
  4324. inline const char *stream_line_reader::ptr() const {
  4325. if (growable_buffer_.empty()) {
  4326. return fixed_buffer_;
  4327. } else {
  4328. return growable_buffer_.data();
  4329. }
  4330. }
  4331. inline size_t stream_line_reader::size() const {
  4332. if (growable_buffer_.empty()) {
  4333. return fixed_buffer_used_size_;
  4334. } else {
  4335. return growable_buffer_.size();
  4336. }
  4337. }
  4338. inline bool stream_line_reader::end_with_crlf() const {
  4339. auto end = ptr() + size();
  4340. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4341. }
  4342. inline bool stream_line_reader::getline() {
  4343. fixed_buffer_used_size_ = 0;
  4344. growable_buffer_.clear();
  4345. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4346. char prev_byte = 0;
  4347. #endif
  4348. for (size_t i = 0;; i++) {
  4349. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4350. // Treat exceptionally long lines as an error to
  4351. // prevent infinite loops/memory exhaustion
  4352. return false;
  4353. }
  4354. char byte;
  4355. auto n = strm_.read(&byte, 1);
  4356. if (n < 0) {
  4357. return false;
  4358. } else if (n == 0) {
  4359. if (i == 0) {
  4360. return false;
  4361. } else {
  4362. break;
  4363. }
  4364. }
  4365. append(byte);
  4366. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4367. if (byte == '\n') { break; }
  4368. #else
  4369. if (prev_byte == '\r' && byte == '\n') { break; }
  4370. prev_byte = byte;
  4371. #endif
  4372. }
  4373. return true;
  4374. }
  4375. inline void stream_line_reader::append(char c) {
  4376. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4377. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4378. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4379. } else {
  4380. if (growable_buffer_.empty()) {
  4381. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4382. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4383. }
  4384. growable_buffer_ += c;
  4385. }
  4386. }
  4387. inline mmap::mmap(const char *path) { open(path); }
  4388. inline mmap::~mmap() { close(); }
  4389. inline bool mmap::open(const char *path) {
  4390. close();
  4391. #if defined(_WIN32)
  4392. auto wpath = u8string_to_wstring(path);
  4393. if (wpath.empty()) { return false; }
  4394. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  4395. OPEN_EXISTING, NULL);
  4396. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4397. LARGE_INTEGER size{};
  4398. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4399. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4400. // See:
  4401. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4402. if (static_cast<ULONGLONG>(size.QuadPart) >
  4403. (std::numeric_limits<decltype(size_)>::max)()) {
  4404. // `size_t` might be 32-bits, on 32-bits Windows.
  4405. return false;
  4406. }
  4407. size_ = static_cast<size_t>(size.QuadPart);
  4408. hMapping_ =
  4409. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4410. // Special treatment for an empty file...
  4411. if (hMapping_ == NULL && size_ == 0) {
  4412. close();
  4413. is_open_empty_file = true;
  4414. return true;
  4415. }
  4416. if (hMapping_ == NULL) {
  4417. close();
  4418. return false;
  4419. }
  4420. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4421. if (addr_ == nullptr) {
  4422. close();
  4423. return false;
  4424. }
  4425. #else
  4426. fd_ = ::open(path, O_RDONLY);
  4427. if (fd_ == -1) { return false; }
  4428. struct stat sb;
  4429. if (fstat(fd_, &sb) == -1) {
  4430. close();
  4431. return false;
  4432. }
  4433. size_ = static_cast<size_t>(sb.st_size);
  4434. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4435. // Special treatment for an empty file...
  4436. if (addr_ == MAP_FAILED && size_ == 0) {
  4437. close();
  4438. is_open_empty_file = true;
  4439. return false;
  4440. }
  4441. #endif
  4442. return true;
  4443. }
  4444. inline bool mmap::is_open() const {
  4445. return is_open_empty_file ? true : addr_ != nullptr;
  4446. }
  4447. inline size_t mmap::size() const { return size_; }
  4448. inline const char *mmap::data() const {
  4449. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4450. }
  4451. inline void mmap::close() {
  4452. #if defined(_WIN32)
  4453. if (addr_) {
  4454. ::UnmapViewOfFile(addr_);
  4455. addr_ = nullptr;
  4456. }
  4457. if (hMapping_) {
  4458. ::CloseHandle(hMapping_);
  4459. hMapping_ = NULL;
  4460. }
  4461. if (hFile_ != INVALID_HANDLE_VALUE) {
  4462. ::CloseHandle(hFile_);
  4463. hFile_ = INVALID_HANDLE_VALUE;
  4464. }
  4465. is_open_empty_file = false;
  4466. #else
  4467. if (addr_ != nullptr) {
  4468. munmap(addr_, size_);
  4469. addr_ = nullptr;
  4470. }
  4471. if (fd_ != -1) {
  4472. ::close(fd_);
  4473. fd_ = -1;
  4474. }
  4475. #endif
  4476. size_ = 0;
  4477. }
  4478. inline int close_socket(socket_t sock) {
  4479. #ifdef _WIN32
  4480. return closesocket(sock);
  4481. #else
  4482. return close(sock);
  4483. #endif
  4484. }
  4485. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4486. ssize_t res = 0;
  4487. while (true) {
  4488. res = fn();
  4489. if (res < 0 && errno == EINTR) {
  4490. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4491. continue;
  4492. }
  4493. break;
  4494. }
  4495. return res;
  4496. }
  4497. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4498. return handle_EINTR([&]() {
  4499. return recv(sock,
  4500. #ifdef _WIN32
  4501. static_cast<char *>(ptr), static_cast<int>(size),
  4502. #else
  4503. ptr, size,
  4504. #endif
  4505. flags);
  4506. });
  4507. }
  4508. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4509. int flags) {
  4510. return handle_EINTR([&]() {
  4511. return send(sock,
  4512. #ifdef _WIN32
  4513. static_cast<const char *>(ptr), static_cast<int>(size),
  4514. #else
  4515. ptr, size,
  4516. #endif
  4517. flags);
  4518. });
  4519. }
  4520. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4521. #ifdef _WIN32
  4522. return ::WSAPoll(fds, nfds, timeout);
  4523. #else
  4524. return ::poll(fds, nfds, timeout);
  4525. #endif
  4526. }
  4527. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4528. time_t usec) {
  4529. struct pollfd pfd;
  4530. pfd.fd = sock;
  4531. pfd.events = events;
  4532. pfd.revents = 0;
  4533. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4534. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4535. }
  4536. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4537. return select_impl(sock, POLLIN, sec, usec);
  4538. }
  4539. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4540. return select_impl(sock, POLLOUT, sec, usec);
  4541. }
  4542. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4543. time_t usec) {
  4544. struct pollfd pfd_read;
  4545. pfd_read.fd = sock;
  4546. pfd_read.events = POLLIN | POLLOUT;
  4547. pfd_read.revents = 0;
  4548. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4549. auto poll_res =
  4550. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4551. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4552. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4553. auto error = 0;
  4554. socklen_t len = sizeof(error);
  4555. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4556. reinterpret_cast<char *>(&error), &len);
  4557. auto successful = res >= 0 && !error;
  4558. return successful ? Error::Success : Error::Connection;
  4559. }
  4560. return Error::Connection;
  4561. }
  4562. inline bool is_socket_alive(socket_t sock) {
  4563. const auto val = detail::select_read(sock, 0, 0);
  4564. if (val == 0) {
  4565. return true;
  4566. } else if (val < 0 && errno == EBADF) {
  4567. return false;
  4568. }
  4569. char buf[1];
  4570. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4571. }
  4572. class SocketStream final : public Stream {
  4573. public:
  4574. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4575. time_t write_timeout_sec, time_t write_timeout_usec,
  4576. time_t max_timeout_msec = 0,
  4577. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4578. (std::chrono::steady_clock::time_point::min)());
  4579. ~SocketStream() override;
  4580. bool is_readable() const override;
  4581. bool wait_readable() const override;
  4582. bool wait_writable() const override;
  4583. bool is_peer_alive() const override;
  4584. ssize_t read(char *ptr, size_t size) override;
  4585. ssize_t write(const char *ptr, size_t size) override;
  4586. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4587. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4588. socket_t socket() const override;
  4589. time_t duration() const override;
  4590. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4591. private:
  4592. socket_t sock_;
  4593. time_t read_timeout_sec_;
  4594. time_t read_timeout_usec_;
  4595. time_t write_timeout_sec_;
  4596. time_t write_timeout_usec_;
  4597. time_t max_timeout_msec_;
  4598. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4599. std::vector<char> read_buff_;
  4600. size_t read_buff_off_ = 0;
  4601. size_t read_buff_content_size_ = 0;
  4602. static const size_t read_buff_size_ = 1024l * 4;
  4603. };
  4604. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4605. time_t keep_alive_timeout_sec) {
  4606. using namespace std::chrono;
  4607. const auto interval_usec =
  4608. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4609. // Avoid expensive `steady_clock::now()` call for the first time
  4610. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4611. const auto start = steady_clock::now() - microseconds{interval_usec};
  4612. const auto timeout = seconds{keep_alive_timeout_sec};
  4613. while (true) {
  4614. if (svr_sock == INVALID_SOCKET) {
  4615. break; // Server socket is closed
  4616. }
  4617. auto val = select_read(sock, 0, interval_usec);
  4618. if (val < 0) {
  4619. break; // Ssocket error
  4620. } else if (val == 0) {
  4621. if (steady_clock::now() - start > timeout) {
  4622. break; // Timeout
  4623. }
  4624. } else {
  4625. return true; // Ready for read
  4626. }
  4627. }
  4628. return false;
  4629. }
  4630. template <typename T>
  4631. inline bool
  4632. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4633. size_t keep_alive_max_count,
  4634. time_t keep_alive_timeout_sec, T callback) {
  4635. assert(keep_alive_max_count > 0);
  4636. auto ret = false;
  4637. auto count = keep_alive_max_count;
  4638. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4639. auto close_connection = count == 1;
  4640. auto connection_closed = false;
  4641. ret = callback(close_connection, connection_closed);
  4642. if (!ret || connection_closed) { break; }
  4643. count--;
  4644. }
  4645. return ret;
  4646. }
  4647. template <typename T>
  4648. inline bool
  4649. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4650. size_t keep_alive_max_count,
  4651. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4652. time_t read_timeout_usec, time_t write_timeout_sec,
  4653. time_t write_timeout_usec, T callback) {
  4654. return process_server_socket_core(
  4655. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4656. [&](bool close_connection, bool &connection_closed) {
  4657. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4658. write_timeout_sec, write_timeout_usec);
  4659. return callback(strm, close_connection, connection_closed);
  4660. });
  4661. }
  4662. inline bool process_client_socket(
  4663. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4664. time_t write_timeout_sec, time_t write_timeout_usec,
  4665. time_t max_timeout_msec,
  4666. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4667. std::function<bool(Stream &)> callback) {
  4668. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4669. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4670. start_time);
  4671. return callback(strm);
  4672. }
  4673. inline int shutdown_socket(socket_t sock) {
  4674. #ifdef _WIN32
  4675. return shutdown(sock, SD_BOTH);
  4676. #else
  4677. return shutdown(sock, SHUT_RDWR);
  4678. #endif
  4679. }
  4680. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4681. if (s.size() > 1 && s[0] == '\0') {
  4682. auto ret = s;
  4683. ret[0] = '@';
  4684. return ret;
  4685. }
  4686. return s;
  4687. }
  4688. inline std::string
  4689. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4690. if (s.size() > 1 && s[0] == '@') {
  4691. auto ret = s;
  4692. ret[0] = '\0';
  4693. return ret;
  4694. }
  4695. return s;
  4696. }
  4697. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4698. const struct addrinfo *hints,
  4699. struct addrinfo **res, time_t timeout_sec) {
  4700. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4701. if (timeout_sec <= 0) {
  4702. // No timeout specified, use standard getaddrinfo
  4703. return getaddrinfo(node, service, hints, res);
  4704. }
  4705. #ifdef _WIN32
  4706. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4707. OVERLAPPED overlapped = {0};
  4708. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4709. if (!event) { return EAI_FAIL; }
  4710. overlapped.hEvent = event;
  4711. PADDRINFOEXW result_addrinfo = nullptr;
  4712. HANDLE cancel_handle = nullptr;
  4713. ADDRINFOEXW hints_ex = {0};
  4714. if (hints) {
  4715. hints_ex.ai_flags = hints->ai_flags;
  4716. hints_ex.ai_family = hints->ai_family;
  4717. hints_ex.ai_socktype = hints->ai_socktype;
  4718. hints_ex.ai_protocol = hints->ai_protocol;
  4719. }
  4720. auto wnode = u8string_to_wstring(node);
  4721. auto wservice = u8string_to_wstring(service);
  4722. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4723. hints ? &hints_ex : nullptr, &result_addrinfo,
  4724. nullptr, &overlapped, nullptr, &cancel_handle);
  4725. if (ret == WSA_IO_PENDING) {
  4726. auto wait_result =
  4727. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4728. if (wait_result == WAIT_TIMEOUT) {
  4729. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4730. ::CloseHandle(event);
  4731. return EAI_AGAIN;
  4732. }
  4733. DWORD bytes_returned;
  4734. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4735. &bytes_returned, FALSE)) {
  4736. ::CloseHandle(event);
  4737. return ::WSAGetLastError();
  4738. }
  4739. }
  4740. ::CloseHandle(event);
  4741. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4742. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4743. return 0;
  4744. }
  4745. return ret;
  4746. #elif TARGET_OS_MAC
  4747. if (!node) { return EAI_NONAME; }
  4748. // macOS implementation using CFHost API for asynchronous DNS resolution
  4749. CFStringRef hostname_ref = CFStringCreateWithCString(
  4750. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4751. if (!hostname_ref) { return EAI_MEMORY; }
  4752. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4753. CFRelease(hostname_ref);
  4754. if (!host_ref) { return EAI_MEMORY; }
  4755. // Set up context for callback
  4756. struct CFHostContext {
  4757. bool completed = false;
  4758. bool success = false;
  4759. CFArrayRef addresses = nullptr;
  4760. std::mutex mutex;
  4761. std::condition_variable cv;
  4762. } context;
  4763. CFHostClientContext client_context;
  4764. memset(&client_context, 0, sizeof(client_context));
  4765. client_context.info = &context;
  4766. // Set callback
  4767. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4768. const CFStreamError *error, void *info) {
  4769. auto ctx = static_cast<CFHostContext *>(info);
  4770. std::lock_guard<std::mutex> lock(ctx->mutex);
  4771. if (error && error->error != 0) {
  4772. ctx->success = false;
  4773. } else {
  4774. Boolean hasBeenResolved;
  4775. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4776. if (ctx->addresses && hasBeenResolved) {
  4777. CFRetain(ctx->addresses);
  4778. ctx->success = true;
  4779. } else {
  4780. ctx->success = false;
  4781. }
  4782. }
  4783. ctx->completed = true;
  4784. ctx->cv.notify_one();
  4785. };
  4786. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4787. CFRelease(host_ref);
  4788. return EAI_SYSTEM;
  4789. }
  4790. // Schedule on run loop
  4791. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4792. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4793. // Start resolution
  4794. CFStreamError stream_error;
  4795. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4796. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4797. CFRelease(host_ref);
  4798. return EAI_FAIL;
  4799. }
  4800. // Wait for completion with timeout
  4801. auto timeout_time =
  4802. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4803. bool timed_out = false;
  4804. {
  4805. std::unique_lock<std::mutex> lock(context.mutex);
  4806. while (!context.completed) {
  4807. auto now = std::chrono::steady_clock::now();
  4808. if (now >= timeout_time) {
  4809. timed_out = true;
  4810. break;
  4811. }
  4812. // Run the runloop for a short time
  4813. lock.unlock();
  4814. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4815. lock.lock();
  4816. }
  4817. }
  4818. // Clean up
  4819. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4820. CFHostSetClient(host_ref, nullptr, nullptr);
  4821. if (timed_out || !context.completed) {
  4822. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4823. CFRelease(host_ref);
  4824. return EAI_AGAIN;
  4825. }
  4826. if (!context.success || !context.addresses) {
  4827. CFRelease(host_ref);
  4828. return EAI_NODATA;
  4829. }
  4830. // Convert CFArray to addrinfo
  4831. CFIndex count = CFArrayGetCount(context.addresses);
  4832. if (count == 0) {
  4833. CFRelease(context.addresses);
  4834. CFRelease(host_ref);
  4835. return EAI_NODATA;
  4836. }
  4837. struct addrinfo *result_addrinfo = nullptr;
  4838. struct addrinfo **current = &result_addrinfo;
  4839. for (CFIndex i = 0; i < count; i++) {
  4840. CFDataRef addr_data =
  4841. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4842. if (!addr_data) continue;
  4843. const struct sockaddr *sockaddr_ptr =
  4844. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4845. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4846. // Allocate addrinfo structure
  4847. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4848. if (!*current) {
  4849. freeaddrinfo(result_addrinfo);
  4850. CFRelease(context.addresses);
  4851. CFRelease(host_ref);
  4852. return EAI_MEMORY;
  4853. }
  4854. memset(*current, 0, sizeof(struct addrinfo));
  4855. // Set up addrinfo fields
  4856. (*current)->ai_family = sockaddr_ptr->sa_family;
  4857. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4858. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4859. (*current)->ai_addrlen = sockaddr_len;
  4860. // Copy sockaddr
  4861. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4862. if (!(*current)->ai_addr) {
  4863. freeaddrinfo(result_addrinfo);
  4864. CFRelease(context.addresses);
  4865. CFRelease(host_ref);
  4866. return EAI_MEMORY;
  4867. }
  4868. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4869. // Set port if service is specified
  4870. if (service && *service) {
  4871. int port = 0;
  4872. if (parse_port(service, strlen(service), port)) {
  4873. if (sockaddr_ptr->sa_family == AF_INET) {
  4874. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4875. ->sin_port = htons(static_cast<uint16_t>(port));
  4876. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4877. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4878. ->sin6_port = htons(static_cast<uint16_t>(port));
  4879. }
  4880. }
  4881. }
  4882. current = &((*current)->ai_next);
  4883. }
  4884. CFRelease(context.addresses);
  4885. CFRelease(host_ref);
  4886. *res = result_addrinfo;
  4887. return 0;
  4888. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4889. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4890. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4891. struct gaicb request;
  4892. struct gaicb *requests[1] = {&request};
  4893. struct sigevent sevp;
  4894. struct timespec timeout;
  4895. // Initialize the request structure
  4896. memset(&request, 0, sizeof(request));
  4897. request.ar_name = node;
  4898. request.ar_service = service;
  4899. request.ar_request = hints;
  4900. // Set up timeout
  4901. timeout.tv_sec = timeout_sec;
  4902. timeout.tv_nsec = 0;
  4903. // Initialize sigevent structure (not used, but required)
  4904. memset(&sevp, 0, sizeof(sevp));
  4905. sevp.sigev_notify = SIGEV_NONE;
  4906. // Start asynchronous resolution
  4907. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4908. if (start_result != 0) { return start_result; }
  4909. // Wait for completion with timeout
  4910. int wait_result =
  4911. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4912. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4913. // Completed successfully, get the result
  4914. int gai_result = gai_error(&request);
  4915. if (gai_result == 0) {
  4916. *res = request.ar_result;
  4917. return 0;
  4918. } else {
  4919. // Clean up on error
  4920. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4921. return gai_result;
  4922. }
  4923. } else if (wait_result == EAI_AGAIN) {
  4924. // Timeout occurred, cancel the request
  4925. gai_cancel(&request);
  4926. return EAI_AGAIN;
  4927. } else {
  4928. // Other error occurred
  4929. gai_cancel(&request);
  4930. return wait_result;
  4931. }
  4932. #else
  4933. // Fallback implementation using thread-based timeout for other Unix systems
  4934. struct GetAddrInfoState {
  4935. ~GetAddrInfoState() {
  4936. if (info) { freeaddrinfo(info); }
  4937. }
  4938. std::mutex mutex;
  4939. std::condition_variable result_cv;
  4940. bool completed = false;
  4941. int result = EAI_SYSTEM;
  4942. std::string node;
  4943. std::string service;
  4944. struct addrinfo hints;
  4945. struct addrinfo *info = nullptr;
  4946. };
  4947. // Allocate on the heap, so the resolver thread can keep using the data.
  4948. auto state = std::make_shared<GetAddrInfoState>();
  4949. if (node) { state->node = node; }
  4950. state->service = service;
  4951. state->hints = *hints;
  4952. std::thread resolve_thread([state]() {
  4953. auto thread_result =
  4954. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4955. &state->info);
  4956. std::lock_guard<std::mutex> lock(state->mutex);
  4957. state->result = thread_result;
  4958. state->completed = true;
  4959. state->result_cv.notify_one();
  4960. });
  4961. // Wait for completion or timeout
  4962. std::unique_lock<std::mutex> lock(state->mutex);
  4963. auto finished =
  4964. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4965. [&] { return state->completed; });
  4966. if (finished) {
  4967. // Operation completed within timeout
  4968. resolve_thread.join();
  4969. *res = state->info;
  4970. state->info = nullptr; // Pass ownership to caller
  4971. return state->result;
  4972. } else {
  4973. // Timeout occurred
  4974. resolve_thread.detach(); // Let the thread finish in background
  4975. return EAI_AGAIN; // Return timeout error
  4976. }
  4977. #endif
  4978. #else
  4979. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4980. return getaddrinfo(node, service, hints, res);
  4981. #endif
  4982. }
  4983. template <typename BindOrConnect>
  4984. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4985. int address_family, int socket_flags, bool tcp_nodelay,
  4986. bool ipv6_v6only, SocketOptions socket_options,
  4987. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4988. // Get address info
  4989. const char *node = nullptr;
  4990. struct addrinfo hints;
  4991. struct addrinfo *result;
  4992. memset(&hints, 0, sizeof(struct addrinfo));
  4993. hints.ai_socktype = SOCK_STREAM;
  4994. hints.ai_protocol = IPPROTO_IP;
  4995. if (!ip.empty()) {
  4996. node = ip.c_str();
  4997. // Ask getaddrinfo to convert IP in c-string to address
  4998. hints.ai_family = AF_UNSPEC;
  4999. hints.ai_flags = AI_NUMERICHOST;
  5000. } else {
  5001. if (!host.empty()) { node = host.c_str(); }
  5002. hints.ai_family = address_family;
  5003. hints.ai_flags = socket_flags;
  5004. }
  5005. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5006. if (hints.ai_family == AF_UNIX) {
  5007. const auto addrlen = host.length();
  5008. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5009. #ifdef SOCK_CLOEXEC
  5010. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5011. hints.ai_protocol);
  5012. #else
  5013. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5014. #endif
  5015. if (sock != INVALID_SOCKET) {
  5016. sockaddr_un addr{};
  5017. addr.sun_family = AF_UNIX;
  5018. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5019. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5020. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5021. hints.ai_addrlen = static_cast<socklen_t>(
  5022. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5023. #ifndef SOCK_CLOEXEC
  5024. #ifndef _WIN32
  5025. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5026. #endif
  5027. #endif
  5028. if (socket_options) { socket_options(sock); }
  5029. #ifdef _WIN32
  5030. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5031. // remove the option.
  5032. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5033. #endif
  5034. bool dummy;
  5035. if (!bind_or_connect(sock, hints, dummy)) {
  5036. close_socket(sock);
  5037. sock = INVALID_SOCKET;
  5038. }
  5039. }
  5040. return sock;
  5041. }
  5042. #endif
  5043. auto service = std::to_string(port);
  5044. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5045. timeout_sec)) {
  5046. #if defined __linux__ && !defined __ANDROID__
  5047. res_init();
  5048. #endif
  5049. return INVALID_SOCKET;
  5050. }
  5051. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5052. for (auto rp = result; rp; rp = rp->ai_next) {
  5053. // Create a socket
  5054. #ifdef _WIN32
  5055. auto sock =
  5056. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5057. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5058. /**
  5059. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5060. * and above the socket creation fails on older Windows Systems.
  5061. *
  5062. * Let's try to create a socket the old way in this case.
  5063. *
  5064. * Reference:
  5065. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5066. *
  5067. * WSA_FLAG_NO_HANDLE_INHERIT:
  5068. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5069. * SP1, and later
  5070. *
  5071. */
  5072. if (sock == INVALID_SOCKET) {
  5073. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5074. }
  5075. #else
  5076. #ifdef SOCK_CLOEXEC
  5077. auto sock =
  5078. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5079. #else
  5080. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5081. #endif
  5082. #endif
  5083. if (sock == INVALID_SOCKET) { continue; }
  5084. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5085. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5086. close_socket(sock);
  5087. continue;
  5088. }
  5089. #endif
  5090. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5091. if (rp->ai_family == AF_INET6) {
  5092. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5093. }
  5094. if (socket_options) { socket_options(sock); }
  5095. // bind or connect
  5096. auto quit = false;
  5097. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5098. close_socket(sock);
  5099. if (quit) { break; }
  5100. }
  5101. return INVALID_SOCKET;
  5102. }
  5103. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5104. #ifdef _WIN32
  5105. auto flags = nonblocking ? 1UL : 0UL;
  5106. ioctlsocket(sock, FIONBIO, &flags);
  5107. #else
  5108. auto flags = fcntl(sock, F_GETFL, 0);
  5109. fcntl(sock, F_SETFL,
  5110. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5111. #endif
  5112. }
  5113. inline bool is_connection_error() {
  5114. #ifdef _WIN32
  5115. return WSAGetLastError() != WSAEWOULDBLOCK;
  5116. #else
  5117. return errno != EINPROGRESS;
  5118. #endif
  5119. }
  5120. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5121. struct addrinfo hints;
  5122. struct addrinfo *result;
  5123. memset(&hints, 0, sizeof(struct addrinfo));
  5124. hints.ai_family = AF_UNSPEC;
  5125. hints.ai_socktype = SOCK_STREAM;
  5126. hints.ai_protocol = 0;
  5127. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5128. return false;
  5129. }
  5130. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5131. auto ret = false;
  5132. for (auto rp = result; rp; rp = rp->ai_next) {
  5133. const auto &ai = *rp;
  5134. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5135. ret = true;
  5136. break;
  5137. }
  5138. }
  5139. return ret;
  5140. }
  5141. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5142. #define USE_IF2IP
  5143. #endif
  5144. #ifdef USE_IF2IP
  5145. inline std::string if2ip(int address_family, const std::string &ifn) {
  5146. struct ifaddrs *ifap;
  5147. getifaddrs(&ifap);
  5148. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5149. std::string addr_candidate;
  5150. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5151. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5152. (AF_UNSPEC == address_family ||
  5153. ifa->ifa_addr->sa_family == address_family)) {
  5154. if (ifa->ifa_addr->sa_family == AF_INET) {
  5155. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5156. char buf[INET_ADDRSTRLEN];
  5157. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5158. return std::string(buf, INET_ADDRSTRLEN);
  5159. }
  5160. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5161. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5162. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5163. char buf[INET6_ADDRSTRLEN] = {};
  5164. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5165. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5166. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5167. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5168. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5169. } else {
  5170. return std::string(buf, INET6_ADDRSTRLEN);
  5171. }
  5172. }
  5173. }
  5174. }
  5175. }
  5176. }
  5177. return addr_candidate;
  5178. }
  5179. #endif
  5180. inline socket_t create_client_socket(
  5181. const std::string &host, const std::string &ip, int port,
  5182. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5183. SocketOptions socket_options, time_t connection_timeout_sec,
  5184. time_t connection_timeout_usec, time_t read_timeout_sec,
  5185. time_t read_timeout_usec, time_t write_timeout_sec,
  5186. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5187. auto sock = create_socket(
  5188. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5189. std::move(socket_options),
  5190. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5191. if (!intf.empty()) {
  5192. #ifdef USE_IF2IP
  5193. auto ip_from_if = if2ip(address_family, intf);
  5194. if (ip_from_if.empty()) { ip_from_if = intf; }
  5195. if (!bind_ip_address(sock2, ip_from_if)) {
  5196. error = Error::BindIPAddress;
  5197. return false;
  5198. }
  5199. #endif
  5200. }
  5201. set_nonblocking(sock2, true);
  5202. auto ret =
  5203. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5204. if (ret < 0) {
  5205. if (is_connection_error()) {
  5206. error = Error::Connection;
  5207. return false;
  5208. }
  5209. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5210. connection_timeout_usec);
  5211. if (error != Error::Success) {
  5212. if (error == Error::ConnectionTimeout) { quit = true; }
  5213. return false;
  5214. }
  5215. }
  5216. set_nonblocking(sock2, false);
  5217. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5218. read_timeout_usec);
  5219. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5220. write_timeout_usec);
  5221. error = Error::Success;
  5222. return true;
  5223. },
  5224. connection_timeout_sec); // Pass DNS timeout
  5225. if (sock != INVALID_SOCKET) {
  5226. error = Error::Success;
  5227. } else {
  5228. if (error == Error::Success) { error = Error::Connection; }
  5229. }
  5230. return sock;
  5231. }
  5232. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5233. socklen_t addr_len, std::string &ip, int &port) {
  5234. if (addr.ss_family == AF_INET) {
  5235. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5236. } else if (addr.ss_family == AF_INET6) {
  5237. port =
  5238. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5239. } else {
  5240. return false;
  5241. }
  5242. std::array<char, NI_MAXHOST> ipstr{};
  5243. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5244. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5245. 0, NI_NUMERICHOST)) {
  5246. return false;
  5247. }
  5248. ip = ipstr.data();
  5249. return true;
  5250. }
  5251. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5252. struct sockaddr_storage addr;
  5253. socklen_t addr_len = sizeof(addr);
  5254. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5255. &addr_len)) {
  5256. get_ip_and_port(addr, addr_len, ip, port);
  5257. }
  5258. }
  5259. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5260. struct sockaddr_storage addr;
  5261. socklen_t addr_len = sizeof(addr);
  5262. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5263. &addr_len)) {
  5264. #ifndef _WIN32
  5265. if (addr.ss_family == AF_UNIX) {
  5266. #if defined(__linux__)
  5267. struct ucred ucred;
  5268. socklen_t len = sizeof(ucred);
  5269. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5270. port = ucred.pid;
  5271. }
  5272. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5273. pid_t pid;
  5274. socklen_t len = sizeof(pid);
  5275. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5276. port = pid;
  5277. }
  5278. #endif
  5279. return;
  5280. }
  5281. #endif
  5282. get_ip_and_port(addr, addr_len, ip, port);
  5283. }
  5284. }
  5285. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5286. unsigned int h) {
  5287. return (l == 0)
  5288. ? h
  5289. : str2tag_core(
  5290. s + 1, l - 1,
  5291. // Unsets the 6 high bits of h, therefore no overflow happens
  5292. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5293. h * 33) ^
  5294. static_cast<unsigned char>(*s));
  5295. }
  5296. inline unsigned int str2tag(const std::string &s) {
  5297. return str2tag_core(s.data(), s.size(), 0);
  5298. }
  5299. namespace udl {
  5300. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5301. return str2tag_core(s, l, 0);
  5302. }
  5303. } // namespace udl
  5304. inline std::string
  5305. find_content_type(const std::string &path,
  5306. const std::map<std::string, std::string> &user_data,
  5307. const std::string &default_content_type) {
  5308. auto ext = file_extension(path);
  5309. auto it = user_data.find(ext);
  5310. if (it != user_data.end()) { return it->second; }
  5311. using udl::operator""_t;
  5312. switch (str2tag(ext)) {
  5313. default: return default_content_type;
  5314. case "css"_t: return "text/css";
  5315. case "csv"_t: return "text/csv";
  5316. case "htm"_t:
  5317. case "html"_t: return "text/html";
  5318. case "js"_t:
  5319. case "mjs"_t: return "text/javascript";
  5320. case "txt"_t: return "text/plain";
  5321. case "vtt"_t: return "text/vtt";
  5322. case "apng"_t: return "image/apng";
  5323. case "avif"_t: return "image/avif";
  5324. case "bmp"_t: return "image/bmp";
  5325. case "gif"_t: return "image/gif";
  5326. case "png"_t: return "image/png";
  5327. case "svg"_t: return "image/svg+xml";
  5328. case "webp"_t: return "image/webp";
  5329. case "ico"_t: return "image/x-icon";
  5330. case "tif"_t: return "image/tiff";
  5331. case "tiff"_t: return "image/tiff";
  5332. case "jpg"_t:
  5333. case "jpeg"_t: return "image/jpeg";
  5334. case "mp4"_t: return "video/mp4";
  5335. case "mpeg"_t: return "video/mpeg";
  5336. case "webm"_t: return "video/webm";
  5337. case "mp3"_t: return "audio/mp3";
  5338. case "mpga"_t: return "audio/mpeg";
  5339. case "weba"_t: return "audio/webm";
  5340. case "wav"_t: return "audio/wave";
  5341. case "otf"_t: return "font/otf";
  5342. case "ttf"_t: return "font/ttf";
  5343. case "woff"_t: return "font/woff";
  5344. case "woff2"_t: return "font/woff2";
  5345. case "7z"_t: return "application/x-7z-compressed";
  5346. case "atom"_t: return "application/atom+xml";
  5347. case "pdf"_t: return "application/pdf";
  5348. case "json"_t: return "application/json";
  5349. case "rss"_t: return "application/rss+xml";
  5350. case "tar"_t: return "application/x-tar";
  5351. case "xht"_t:
  5352. case "xhtml"_t: return "application/xhtml+xml";
  5353. case "xslt"_t: return "application/xslt+xml";
  5354. case "xml"_t: return "application/xml";
  5355. case "gz"_t: return "application/gzip";
  5356. case "zip"_t: return "application/zip";
  5357. case "wasm"_t: return "application/wasm";
  5358. }
  5359. }
  5360. inline std::string
  5361. extract_media_type(const std::string &content_type,
  5362. std::map<std::string, std::string> *params = nullptr) {
  5363. // Extract type/subtype from Content-Type value (RFC 2045)
  5364. // e.g. "application/json; charset=utf-8" -> "application/json"
  5365. auto media_type = content_type;
  5366. auto semicolon_pos = media_type.find(';');
  5367. if (semicolon_pos != std::string::npos) {
  5368. auto param_str = media_type.substr(semicolon_pos + 1);
  5369. media_type = media_type.substr(0, semicolon_pos);
  5370. if (params) {
  5371. // Parse parameters: key=value pairs separated by ';'
  5372. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5373. [&](const char *b, const char *e) {
  5374. std::string key;
  5375. std::string val;
  5376. split(b, e, '=', [&](const char *b2, const char *e2) {
  5377. if (key.empty()) {
  5378. key.assign(b2, e2);
  5379. } else {
  5380. val.assign(b2, e2);
  5381. }
  5382. });
  5383. if (!key.empty()) {
  5384. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5385. }
  5386. });
  5387. }
  5388. }
  5389. // Trim whitespace from media type
  5390. return trim_copy(media_type);
  5391. }
  5392. inline bool can_compress_content_type(const std::string &content_type) {
  5393. using udl::operator""_t;
  5394. auto mime_type = extract_media_type(content_type);
  5395. auto tag = str2tag(mime_type);
  5396. switch (tag) {
  5397. case "image/svg+xml"_t:
  5398. case "application/javascript"_t:
  5399. case "application/x-javascript"_t:
  5400. case "application/json"_t:
  5401. case "application/ld+json"_t:
  5402. case "application/xml"_t:
  5403. case "application/xhtml+xml"_t:
  5404. case "application/rss+xml"_t:
  5405. case "application/atom+xml"_t:
  5406. case "application/xslt+xml"_t:
  5407. case "application/protobuf"_t: return true;
  5408. case "text/event-stream"_t: return false;
  5409. default: return !mime_type.rfind("text/", 0);
  5410. }
  5411. }
  5412. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5413. double &quality) {
  5414. quality = 1.0;
  5415. token.clear();
  5416. // Split on first ';': left = token name, right = parameters
  5417. const char *params_b = nullptr;
  5418. std::size_t params_len = 0;
  5419. divide(
  5420. b, static_cast<std::size_t>(e - b), ';',
  5421. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5422. auto r = trim(lb, lb + llen, 0, llen);
  5423. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5424. params_b = rb;
  5425. params_len = rlen;
  5426. });
  5427. if (token.empty()) { return false; }
  5428. if (params_len == 0) { return true; }
  5429. // Scan parameters for q= (stops on first match)
  5430. bool invalid = false;
  5431. split_find(params_b, params_b + params_len, ';',
  5432. (std::numeric_limits<size_t>::max)(),
  5433. [&](const char *pb, const char *pe) -> bool {
  5434. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5435. auto len = static_cast<size_t>(pe - pb);
  5436. if (len < 2) { return false; }
  5437. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5438. return false;
  5439. }
  5440. // Trim the value portion
  5441. auto r = trim(pb, pe, 2, len);
  5442. if (r.first >= r.second) {
  5443. invalid = true;
  5444. return true;
  5445. }
  5446. double v = 0.0;
  5447. auto res = from_chars(pb + r.first, pb + r.second, v);
  5448. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5449. invalid = true;
  5450. return true;
  5451. }
  5452. quality = v;
  5453. return true;
  5454. });
  5455. return !invalid;
  5456. }
  5457. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5458. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5459. return EncodingType::None;
  5460. }
  5461. const auto &s = req.get_header_value("Accept-Encoding");
  5462. if (s.empty()) { return EncodingType::None; }
  5463. // Single-pass: iterate tokens and track the best supported encoding.
  5464. // Server preference breaks ties (br > gzip > zstd).
  5465. EncodingType best = EncodingType::None;
  5466. double best_q = 0.0; // q=0 means "not acceptable"
  5467. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5468. auto priority = [](EncodingType t) -> int {
  5469. switch (t) {
  5470. case EncodingType::Brotli: return 0;
  5471. case EncodingType::Gzip: return 1;
  5472. case EncodingType::Zstd: return 2;
  5473. default: return 3;
  5474. }
  5475. };
  5476. std::string name;
  5477. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5478. double quality = 1.0;
  5479. if (!parse_quality(b, e, name, quality)) { return; }
  5480. if (quality <= 0.0) { return; }
  5481. EncodingType type = EncodingType::None;
  5482. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5483. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5484. #endif
  5485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5486. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5487. type = EncodingType::Gzip;
  5488. }
  5489. #endif
  5490. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5491. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5492. type = EncodingType::Zstd;
  5493. }
  5494. #endif
  5495. if (type == EncodingType::None) { return; }
  5496. // Higher q-value wins; for equal q, server preference breaks ties
  5497. if (quality > best_q ||
  5498. (quality == best_q && priority(type) < priority(best))) {
  5499. best_q = quality;
  5500. best = type;
  5501. }
  5502. });
  5503. return best;
  5504. }
  5505. inline bool nocompressor::compress(const char *data, size_t data_length,
  5506. bool /*last*/, Callback callback) {
  5507. if (!data_length) { return true; }
  5508. return callback(data, data_length);
  5509. }
  5510. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5511. inline gzip_compressor::gzip_compressor() {
  5512. std::memset(&strm_, 0, sizeof(strm_));
  5513. strm_.zalloc = Z_NULL;
  5514. strm_.zfree = Z_NULL;
  5515. strm_.opaque = Z_NULL;
  5516. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5517. Z_DEFAULT_STRATEGY) == Z_OK;
  5518. }
  5519. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5520. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5521. bool last, Callback callback) {
  5522. assert(is_valid_);
  5523. do {
  5524. constexpr size_t max_avail_in =
  5525. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5526. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5527. (std::min)(data_length, max_avail_in));
  5528. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5529. data_length -= strm_.avail_in;
  5530. data += strm_.avail_in;
  5531. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5532. auto ret = Z_OK;
  5533. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5534. do {
  5535. strm_.avail_out = static_cast<uInt>(buff.size());
  5536. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5537. ret = deflate(&strm_, flush);
  5538. if (ret == Z_STREAM_ERROR) { return false; }
  5539. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5540. return false;
  5541. }
  5542. } while (strm_.avail_out == 0);
  5543. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5544. (flush == Z_NO_FLUSH && ret == Z_OK));
  5545. assert(strm_.avail_in == 0);
  5546. } while (data_length > 0);
  5547. return true;
  5548. }
  5549. inline gzip_decompressor::gzip_decompressor() {
  5550. std::memset(&strm_, 0, sizeof(strm_));
  5551. strm_.zalloc = Z_NULL;
  5552. strm_.zfree = Z_NULL;
  5553. strm_.opaque = Z_NULL;
  5554. // 15 is the value of wbits, which should be at the maximum possible value
  5555. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5556. // that the stream type should be automatically detected either gzip or
  5557. // deflate.
  5558. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5559. }
  5560. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5561. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5562. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5563. Callback callback) {
  5564. assert(is_valid_);
  5565. auto ret = Z_OK;
  5566. do {
  5567. constexpr size_t max_avail_in =
  5568. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5569. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5570. (std::min)(data_length, max_avail_in));
  5571. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5572. data_length -= strm_.avail_in;
  5573. data += strm_.avail_in;
  5574. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5575. while (strm_.avail_in > 0 && ret == Z_OK) {
  5576. strm_.avail_out = static_cast<uInt>(buff.size());
  5577. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5578. ret = inflate(&strm_, Z_NO_FLUSH);
  5579. assert(ret != Z_STREAM_ERROR);
  5580. switch (ret) {
  5581. case Z_NEED_DICT:
  5582. case Z_DATA_ERROR:
  5583. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5584. }
  5585. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5586. return false;
  5587. }
  5588. }
  5589. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5590. } while (data_length > 0);
  5591. return true;
  5592. }
  5593. #endif
  5594. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5595. inline brotli_compressor::brotli_compressor() {
  5596. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5597. }
  5598. inline brotli_compressor::~brotli_compressor() {
  5599. BrotliEncoderDestroyInstance(state_);
  5600. }
  5601. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5602. bool last, Callback callback) {
  5603. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5604. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5605. auto available_in = data_length;
  5606. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5607. for (;;) {
  5608. if (last) {
  5609. if (BrotliEncoderIsFinished(state_)) { break; }
  5610. } else {
  5611. if (!available_in) { break; }
  5612. }
  5613. auto available_out = buff.size();
  5614. auto next_out = buff.data();
  5615. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5616. &available_out, &next_out, nullptr)) {
  5617. return false;
  5618. }
  5619. auto output_bytes = buff.size() - available_out;
  5620. if (output_bytes) {
  5621. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5622. }
  5623. }
  5624. return true;
  5625. }
  5626. inline brotli_decompressor::brotli_decompressor() {
  5627. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5628. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5629. : BROTLI_DECODER_RESULT_ERROR;
  5630. }
  5631. inline brotli_decompressor::~brotli_decompressor() {
  5632. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5633. }
  5634. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5635. inline bool brotli_decompressor::decompress(const char *data,
  5636. size_t data_length,
  5637. Callback callback) {
  5638. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5639. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5640. return 0;
  5641. }
  5642. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5643. size_t avail_in = data_length;
  5644. size_t total_out;
  5645. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5646. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5647. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5648. char *next_out = buff.data();
  5649. size_t avail_out = buff.size();
  5650. decoder_r = BrotliDecoderDecompressStream(
  5651. decoder_s, &avail_in, &next_in, &avail_out,
  5652. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5653. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5654. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5655. }
  5656. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5657. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5658. }
  5659. #endif
  5660. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5661. inline zstd_compressor::zstd_compressor() {
  5662. ctx_ = ZSTD_createCCtx();
  5663. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5664. }
  5665. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5666. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5667. bool last, Callback callback) {
  5668. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5669. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5670. ZSTD_inBuffer input = {data, data_length, 0};
  5671. bool finished;
  5672. do {
  5673. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5674. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5675. if (ZSTD_isError(remaining)) { return false; }
  5676. if (!callback(buff.data(), output.pos)) { return false; }
  5677. finished = last ? (remaining == 0) : (input.pos == input.size);
  5678. } while (!finished);
  5679. return true;
  5680. }
  5681. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5682. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5683. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5684. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5685. Callback callback) {
  5686. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5687. ZSTD_inBuffer input = {data, data_length, 0};
  5688. while (input.pos < input.size) {
  5689. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5690. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5691. if (ZSTD_isError(remaining)) { return false; }
  5692. if (!callback(buff.data(), output.pos)) { return false; }
  5693. }
  5694. return true;
  5695. }
  5696. #endif
  5697. inline std::unique_ptr<decompressor>
  5698. create_decompressor(const std::string &encoding) {
  5699. std::unique_ptr<decompressor> decompressor;
  5700. if (encoding == "gzip" || encoding == "deflate") {
  5701. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5702. decompressor = detail::make_unique<gzip_decompressor>();
  5703. #endif
  5704. } else if (encoding.find("br") != std::string::npos) {
  5705. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5706. decompressor = detail::make_unique<brotli_decompressor>();
  5707. #endif
  5708. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5709. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5710. decompressor = detail::make_unique<zstd_decompressor>();
  5711. #endif
  5712. }
  5713. return decompressor;
  5714. }
  5715. // Returns the best available compressor and its Content-Encoding name.
  5716. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5717. inline std::pair<std::unique_ptr<compressor>, const char *>
  5718. create_compressor() {
  5719. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5720. return {detail::make_unique<brotli_compressor>(), "br"};
  5721. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5722. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5723. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5724. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5725. #else
  5726. return {nullptr, nullptr};
  5727. #endif
  5728. }
  5729. inline bool is_prohibited_header_name(const std::string &name) {
  5730. using udl::operator""_t;
  5731. switch (str2tag(name)) {
  5732. case "REMOTE_ADDR"_t:
  5733. case "REMOTE_PORT"_t:
  5734. case "LOCAL_ADDR"_t:
  5735. case "LOCAL_PORT"_t: return true;
  5736. default: return false;
  5737. }
  5738. }
  5739. inline bool has_header(const Headers &headers, const std::string &key) {
  5740. if (is_prohibited_header_name(key)) { return false; }
  5741. return headers.find(key) != headers.end();
  5742. }
  5743. inline const char *get_header_value(const Headers &headers,
  5744. const std::string &key, const char *def,
  5745. size_t id) {
  5746. if (is_prohibited_header_name(key)) {
  5747. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5748. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5749. throw std::invalid_argument(msg);
  5750. #else
  5751. return "";
  5752. #endif
  5753. }
  5754. auto rng = headers.equal_range(key);
  5755. auto it = rng.first;
  5756. std::advance(it, static_cast<ssize_t>(id));
  5757. if (it != rng.second) { return it->second.c_str(); }
  5758. return def;
  5759. }
  5760. inline bool read_headers(Stream &strm, Headers &headers) {
  5761. const auto bufsiz = 2048;
  5762. char buf[bufsiz];
  5763. stream_line_reader line_reader(strm, buf, bufsiz);
  5764. size_t header_count = 0;
  5765. for (;;) {
  5766. if (!line_reader.getline()) { return false; }
  5767. // Check if the line ends with CRLF.
  5768. auto line_terminator_len = 2;
  5769. if (line_reader.end_with_crlf()) {
  5770. // Blank line indicates end of headers.
  5771. if (line_reader.size() == 2) { break; }
  5772. } else {
  5773. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5774. // Blank line indicates end of headers.
  5775. if (line_reader.size() == 1) { break; }
  5776. line_terminator_len = 1;
  5777. #else
  5778. continue; // Skip invalid line.
  5779. #endif
  5780. }
  5781. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5782. // Check header count limit
  5783. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5784. // Exclude line terminator
  5785. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5786. if (!parse_header(line_reader.ptr(), end,
  5787. [&](const std::string &key, const std::string &val) {
  5788. headers.emplace(key, val);
  5789. })) {
  5790. return false;
  5791. }
  5792. header_count++;
  5793. }
  5794. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5795. // headers that have different values to prevent request smuggling.
  5796. auto cl_range = headers.equal_range("Content-Length");
  5797. if (cl_range.first != cl_range.second) {
  5798. const auto &first_val = cl_range.first->second;
  5799. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5800. if (it->second != first_val) { return false; }
  5801. }
  5802. }
  5803. return true;
  5804. }
  5805. inline bool read_websocket_upgrade_response(Stream &strm,
  5806. const std::string &expected_accept,
  5807. std::string &selected_subprotocol) {
  5808. // Read status line
  5809. const auto bufsiz = 2048;
  5810. char buf[bufsiz];
  5811. stream_line_reader line_reader(strm, buf, bufsiz);
  5812. if (!line_reader.getline()) { return false; }
  5813. // Check for "HTTP/1.1 101"
  5814. auto line = std::string(line_reader.ptr(), line_reader.size());
  5815. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5816. // Parse headers using existing read_headers
  5817. Headers headers;
  5818. if (!read_headers(strm, headers)) { return false; }
  5819. // Verify Upgrade: websocket (case-insensitive)
  5820. auto upgrade_it = headers.find("Upgrade");
  5821. if (upgrade_it == headers.end()) { return false; }
  5822. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  5823. if (upgrade_val != "websocket") { return false; }
  5824. // Verify Connection header contains "Upgrade" (case-insensitive)
  5825. auto connection_it = headers.find("Connection");
  5826. if (connection_it == headers.end()) { return false; }
  5827. auto connection_val = case_ignore::to_lower(connection_it->second);
  5828. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  5829. // Verify Sec-WebSocket-Accept header value
  5830. auto it = headers.find("Sec-WebSocket-Accept");
  5831. if (it == headers.end() || it->second != expected_accept) { return false; }
  5832. // Extract negotiated subprotocol
  5833. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  5834. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  5835. return true;
  5836. }
  5837. enum class ReadContentResult {
  5838. Success, // Successfully read the content
  5839. PayloadTooLarge, // The content exceeds the specified payload limit
  5840. Error // An error occurred while reading the content
  5841. };
  5842. inline ReadContentResult read_content_with_length(
  5843. Stream &strm, size_t len, DownloadProgress progress,
  5844. ContentReceiverWithProgress out,
  5845. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  5846. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5847. detail::BodyReader br;
  5848. br.stream = &strm;
  5849. br.has_content_length = true;
  5850. br.content_length = len;
  5851. br.payload_max_length = payload_max_length;
  5852. br.chunked = false;
  5853. br.bytes_read = 0;
  5854. br.last_error = Error::Success;
  5855. size_t r = 0;
  5856. while (r < len) {
  5857. auto read_len = static_cast<size_t>(len - r);
  5858. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  5859. auto n = detail::read_body_content(&strm, br, buf, to_read);
  5860. if (n <= 0) {
  5861. // Check if it was a payload size error
  5862. if (br.last_error == Error::ExceedMaxPayloadSize) {
  5863. return ReadContentResult::PayloadTooLarge;
  5864. }
  5865. return ReadContentResult::Error;
  5866. }
  5867. if (!out(buf, static_cast<size_t>(n), r, len)) {
  5868. return ReadContentResult::Error;
  5869. }
  5870. r += static_cast<size_t>(n);
  5871. if (progress) {
  5872. if (!progress(r, len)) { return ReadContentResult::Error; }
  5873. }
  5874. }
  5875. return ReadContentResult::Success;
  5876. }
  5877. inline ReadContentResult
  5878. read_content_without_length(Stream &strm, size_t payload_max_length,
  5879. ContentReceiverWithProgress out) {
  5880. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5881. size_t r = 0;
  5882. for (;;) {
  5883. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  5884. if (n == 0) { return ReadContentResult::Success; }
  5885. if (n < 0) { return ReadContentResult::Error; }
  5886. // Check if adding this data would exceed the payload limit
  5887. if (r > payload_max_length ||
  5888. payload_max_length - r < static_cast<size_t>(n)) {
  5889. return ReadContentResult::PayloadTooLarge;
  5890. }
  5891. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5892. return ReadContentResult::Error;
  5893. }
  5894. r += static_cast<size_t>(n);
  5895. }
  5896. return ReadContentResult::Success;
  5897. }
  5898. template <typename T>
  5899. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5900. size_t payload_max_length,
  5901. ContentReceiverWithProgress out) {
  5902. detail::ChunkedDecoder dec(strm);
  5903. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5904. size_t total_len = 0;
  5905. for (;;) {
  5906. size_t chunk_offset = 0;
  5907. size_t chunk_total = 0;
  5908. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5909. if (n < 0) { return ReadContentResult::Error; }
  5910. if (n == 0) {
  5911. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5912. return ReadContentResult::Error;
  5913. }
  5914. return ReadContentResult::Success;
  5915. }
  5916. if (total_len > payload_max_length ||
  5917. payload_max_length - total_len < static_cast<size_t>(n)) {
  5918. return ReadContentResult::PayloadTooLarge;
  5919. }
  5920. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5921. return ReadContentResult::Error;
  5922. }
  5923. total_len += static_cast<size_t>(n);
  5924. }
  5925. }
  5926. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5927. return case_ignore::equal(
  5928. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5929. }
  5930. template <typename T, typename U>
  5931. bool prepare_content_receiver(T &x, int &status,
  5932. ContentReceiverWithProgress receiver,
  5933. bool decompress, size_t payload_max_length,
  5934. bool &exceed_payload_max_length, U callback) {
  5935. if (decompress) {
  5936. std::string encoding = x.get_header_value("Content-Encoding");
  5937. std::unique_ptr<decompressor> decompressor;
  5938. if (!encoding.empty()) {
  5939. decompressor = detail::create_decompressor(encoding);
  5940. if (!decompressor) {
  5941. // Unsupported encoding or no support compiled in
  5942. status = StatusCode::UnsupportedMediaType_415;
  5943. return false;
  5944. }
  5945. }
  5946. if (decompressor) {
  5947. if (decompressor->is_valid()) {
  5948. size_t decompressed_size = 0;
  5949. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5950. size_t off, size_t len) {
  5951. return decompressor->decompress(
  5952. buf, n, [&](const char *buf2, size_t n2) {
  5953. // Guard against zip-bomb: check
  5954. // decompressed size against limit.
  5955. if (payload_max_length > 0 &&
  5956. (decompressed_size >= payload_max_length ||
  5957. n2 > payload_max_length - decompressed_size)) {
  5958. exceed_payload_max_length = true;
  5959. return false;
  5960. }
  5961. decompressed_size += n2;
  5962. return receiver(buf2, n2, off, len);
  5963. });
  5964. };
  5965. return callback(std::move(out));
  5966. } else {
  5967. status = StatusCode::InternalServerError_500;
  5968. return false;
  5969. }
  5970. }
  5971. }
  5972. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5973. size_t len) {
  5974. return receiver(buf, n, off, len);
  5975. };
  5976. return callback(std::move(out));
  5977. }
  5978. template <typename T>
  5979. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5980. DownloadProgress progress,
  5981. ContentReceiverWithProgress receiver, bool decompress) {
  5982. bool exceed_payload_max_length = false;
  5983. return prepare_content_receiver(
  5984. x, status, std::move(receiver), decompress, payload_max_length,
  5985. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  5986. auto ret = true;
  5987. // Note: exceed_payload_max_length may also be set by the decompressor
  5988. // wrapper in prepare_content_receiver when the decompressed payload
  5989. // size exceeds the limit.
  5990. if (is_chunked_transfer_encoding(x.headers)) {
  5991. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5992. if (result == ReadContentResult::Success) {
  5993. ret = true;
  5994. } else if (result == ReadContentResult::PayloadTooLarge) {
  5995. exceed_payload_max_length = true;
  5996. ret = false;
  5997. } else {
  5998. ret = false;
  5999. }
  6000. } else if (!has_header(x.headers, "Content-Length")) {
  6001. auto result =
  6002. read_content_without_length(strm, payload_max_length, out);
  6003. if (result == ReadContentResult::Success) {
  6004. ret = true;
  6005. } else if (result == ReadContentResult::PayloadTooLarge) {
  6006. exceed_payload_max_length = true;
  6007. ret = false;
  6008. } else {
  6009. ret = false;
  6010. }
  6011. } else {
  6012. auto is_invalid_value = false;
  6013. auto len = get_header_value_u64(x.headers, "Content-Length",
  6014. (std::numeric_limits<size_t>::max)(),
  6015. 0, is_invalid_value);
  6016. if (is_invalid_value) {
  6017. ret = false;
  6018. } else if (len > 0) {
  6019. auto result = read_content_with_length(
  6020. strm, len, std::move(progress), out, payload_max_length);
  6021. ret = (result == ReadContentResult::Success);
  6022. if (result == ReadContentResult::PayloadTooLarge) {
  6023. exceed_payload_max_length = true;
  6024. }
  6025. }
  6026. }
  6027. if (!ret) {
  6028. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6029. : StatusCode::BadRequest_400;
  6030. }
  6031. return ret;
  6032. });
  6033. }
  6034. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6035. const std::string &path) {
  6036. std::string s = method;
  6037. s += ' ';
  6038. s += path;
  6039. s += " HTTP/1.1\r\n";
  6040. return strm.write(s.data(), s.size());
  6041. }
  6042. inline ssize_t write_response_line(Stream &strm, int status) {
  6043. std::string s = "HTTP/1.1 ";
  6044. s += std::to_string(status);
  6045. s += ' ';
  6046. s += httplib::status_message(status);
  6047. s += "\r\n";
  6048. return strm.write(s.data(), s.size());
  6049. }
  6050. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6051. ssize_t write_len = 0;
  6052. for (const auto &x : headers) {
  6053. std::string s;
  6054. s = x.first;
  6055. s += ": ";
  6056. s += x.second;
  6057. s += "\r\n";
  6058. auto len = strm.write(s.data(), s.size());
  6059. if (len < 0) { return len; }
  6060. write_len += len;
  6061. }
  6062. auto len = strm.write("\r\n");
  6063. if (len < 0) { return len; }
  6064. write_len += len;
  6065. return write_len;
  6066. }
  6067. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6068. size_t offset = 0;
  6069. while (offset < l) {
  6070. auto length = strm.write(d + offset, l - offset);
  6071. if (length < 0) { return false; }
  6072. offset += static_cast<size_t>(length);
  6073. }
  6074. return true;
  6075. }
  6076. template <typename T>
  6077. inline bool write_content_with_progress(Stream &strm,
  6078. const ContentProvider &content_provider,
  6079. size_t offset, size_t length,
  6080. T is_shutting_down,
  6081. const UploadProgress &upload_progress,
  6082. Error &error) {
  6083. size_t end_offset = offset + length;
  6084. size_t start_offset = offset;
  6085. auto ok = true;
  6086. DataSink data_sink;
  6087. data_sink.write = [&](const char *d, size_t l) -> bool {
  6088. if (ok) {
  6089. if (write_data(strm, d, l)) {
  6090. offset += l;
  6091. if (upload_progress && length > 0) {
  6092. size_t current_written = offset - start_offset;
  6093. if (!upload_progress(current_written, length)) {
  6094. ok = false;
  6095. return false;
  6096. }
  6097. }
  6098. } else {
  6099. ok = false;
  6100. }
  6101. }
  6102. return ok;
  6103. };
  6104. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6105. while (offset < end_offset && !is_shutting_down()) {
  6106. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6107. error = Error::Write;
  6108. return false;
  6109. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6110. error = Error::Canceled;
  6111. return false;
  6112. } else if (!ok) {
  6113. error = Error::Write;
  6114. return false;
  6115. }
  6116. }
  6117. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6118. error = Error::Write;
  6119. return false;
  6120. }
  6121. error = Error::Success;
  6122. return true;
  6123. }
  6124. template <typename T>
  6125. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6126. size_t offset, size_t length, T is_shutting_down,
  6127. Error &error) {
  6128. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6129. is_shutting_down, nullptr, error);
  6130. }
  6131. template <typename T>
  6132. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6133. size_t offset, size_t length,
  6134. const T &is_shutting_down) {
  6135. auto error = Error::Success;
  6136. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6137. error);
  6138. }
  6139. template <typename T>
  6140. inline bool
  6141. write_content_without_length(Stream &strm,
  6142. const ContentProvider &content_provider,
  6143. const T &is_shutting_down) {
  6144. size_t offset = 0;
  6145. auto data_available = true;
  6146. auto ok = true;
  6147. DataSink data_sink;
  6148. data_sink.write = [&](const char *d, size_t l) -> bool {
  6149. if (ok) {
  6150. offset += l;
  6151. if (!write_data(strm, d, l)) { ok = false; }
  6152. }
  6153. return ok;
  6154. };
  6155. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6156. data_sink.done = [&](void) { data_available = false; };
  6157. while (data_available && !is_shutting_down()) {
  6158. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6159. return false;
  6160. } else if (!content_provider(offset, 0, data_sink)) {
  6161. return false;
  6162. } else if (!ok) {
  6163. return false;
  6164. }
  6165. }
  6166. return !data_available; // true only if done() was called, false if shutting
  6167. // down
  6168. }
  6169. template <typename T, typename U>
  6170. inline bool
  6171. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6172. const T &is_shutting_down, U &compressor, Error &error) {
  6173. size_t offset = 0;
  6174. auto data_available = true;
  6175. auto ok = true;
  6176. DataSink data_sink;
  6177. data_sink.write = [&](const char *d, size_t l) -> bool {
  6178. if (ok) {
  6179. data_available = l > 0;
  6180. offset += l;
  6181. std::string payload;
  6182. if (compressor.compress(d, l, false,
  6183. [&](const char *data, size_t data_len) {
  6184. payload.append(data, data_len);
  6185. return true;
  6186. })) {
  6187. if (!payload.empty()) {
  6188. // Emit chunked response header and footer for each chunk
  6189. auto chunk =
  6190. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6191. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6192. }
  6193. } else {
  6194. ok = false;
  6195. }
  6196. }
  6197. return ok;
  6198. };
  6199. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6200. auto done_with_trailer = [&](const Headers *trailer) {
  6201. if (!ok) { return; }
  6202. data_available = false;
  6203. std::string payload;
  6204. if (!compressor.compress(nullptr, 0, true,
  6205. [&](const char *data, size_t data_len) {
  6206. payload.append(data, data_len);
  6207. return true;
  6208. })) {
  6209. ok = false;
  6210. return;
  6211. }
  6212. if (!payload.empty()) {
  6213. // Emit chunked response header and footer for each chunk
  6214. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6215. if (!write_data(strm, chunk.data(), chunk.size())) {
  6216. ok = false;
  6217. return;
  6218. }
  6219. }
  6220. constexpr const char done_marker[] = "0\r\n";
  6221. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6222. // Trailer
  6223. if (trailer) {
  6224. for (const auto &kv : *trailer) {
  6225. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6226. if (!write_data(strm, field_line.data(), field_line.size())) {
  6227. ok = false;
  6228. }
  6229. }
  6230. }
  6231. constexpr const char crlf[] = "\r\n";
  6232. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6233. };
  6234. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6235. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6236. done_with_trailer(&trailer);
  6237. };
  6238. while (data_available && !is_shutting_down()) {
  6239. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6240. error = Error::Write;
  6241. return false;
  6242. } else if (!content_provider(offset, 0, data_sink)) {
  6243. error = Error::Canceled;
  6244. return false;
  6245. } else if (!ok) {
  6246. error = Error::Write;
  6247. return false;
  6248. }
  6249. }
  6250. if (data_available) { // exited due to is_shutting_down(), not done()
  6251. error = Error::Write;
  6252. return false;
  6253. }
  6254. error = Error::Success;
  6255. return true;
  6256. }
  6257. template <typename T, typename U>
  6258. inline bool write_content_chunked(Stream &strm,
  6259. const ContentProvider &content_provider,
  6260. const T &is_shutting_down, U &compressor) {
  6261. auto error = Error::Success;
  6262. return write_content_chunked(strm, content_provider, is_shutting_down,
  6263. compressor, error);
  6264. }
  6265. template <typename T>
  6266. inline bool redirect(T &cli, Request &req, Response &res,
  6267. const std::string &path, const std::string &location,
  6268. Error &error) {
  6269. Request new_req = req;
  6270. new_req.path = path;
  6271. new_req.redirect_count_ -= 1;
  6272. if (res.status == StatusCode::SeeOther_303 &&
  6273. (req.method != "GET" && req.method != "HEAD")) {
  6274. new_req.method = "GET";
  6275. new_req.body.clear();
  6276. new_req.headers.clear();
  6277. }
  6278. Response new_res;
  6279. auto ret = cli.send(new_req, new_res, error);
  6280. if (ret) {
  6281. req = std::move(new_req);
  6282. res = std::move(new_res);
  6283. if (res.location.empty()) { res.location = location; }
  6284. }
  6285. return ret;
  6286. }
  6287. inline std::string params_to_query_str(const Params &params) {
  6288. std::string query;
  6289. for (auto it = params.begin(); it != params.end(); ++it) {
  6290. if (it != params.begin()) { query += '&'; }
  6291. query += encode_query_component(it->first);
  6292. query += '=';
  6293. query += encode_query_component(it->second);
  6294. }
  6295. return query;
  6296. }
  6297. inline void parse_query_text(const char *data, std::size_t size,
  6298. Params &params) {
  6299. std::set<std::string> cache;
  6300. split(data, data + size, '&', [&](const char *b, const char *e) {
  6301. std::string kv(b, e);
  6302. if (cache.find(kv) != cache.end()) { return; }
  6303. cache.insert(std::move(kv));
  6304. std::string key;
  6305. std::string val;
  6306. divide(b, static_cast<std::size_t>(e - b), '=',
  6307. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6308. std::size_t rhs_size) {
  6309. key.assign(lhs_data, lhs_size);
  6310. val.assign(rhs_data, rhs_size);
  6311. });
  6312. if (!key.empty()) {
  6313. params.emplace(decode_query_component(key), decode_query_component(val));
  6314. }
  6315. });
  6316. }
  6317. inline void parse_query_text(const std::string &s, Params &params) {
  6318. parse_query_text(s.data(), s.size(), params);
  6319. }
  6320. // Normalize a query string by decoding and re-encoding each key/value pair
  6321. // while preserving the original parameter order. This avoids double-encoding
  6322. // and ensures consistent encoding without reordering (unlike Params which
  6323. // uses std::multimap and sorts keys).
  6324. inline std::string normalize_query_string(const std::string &query) {
  6325. std::string result;
  6326. split(query.data(), query.data() + query.size(), '&',
  6327. [&](const char *b, const char *e) {
  6328. std::string key;
  6329. std::string val;
  6330. divide(b, static_cast<std::size_t>(e - b), '=',
  6331. [&](const char *lhs_data, std::size_t lhs_size,
  6332. const char *rhs_data, std::size_t rhs_size) {
  6333. key.assign(lhs_data, lhs_size);
  6334. val.assign(rhs_data, rhs_size);
  6335. });
  6336. if (!key.empty()) {
  6337. auto dec_key = decode_query_component(key);
  6338. auto dec_val = decode_query_component(val);
  6339. if (!result.empty()) { result += '&'; }
  6340. result += encode_query_component(dec_key);
  6341. if (!val.empty() || std::find(b, e, '=') != e) {
  6342. result += '=';
  6343. result += encode_query_component(dec_val);
  6344. }
  6345. }
  6346. });
  6347. return result;
  6348. }
  6349. inline bool parse_multipart_boundary(const std::string &content_type,
  6350. std::string &boundary) {
  6351. std::map<std::string, std::string> params;
  6352. extract_media_type(content_type, &params);
  6353. auto it = params.find("boundary");
  6354. if (it == params.end()) { return false; }
  6355. boundary = it->second;
  6356. return !boundary.empty();
  6357. }
  6358. inline void parse_disposition_params(const std::string &s, Params &params) {
  6359. std::set<std::string> cache;
  6360. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6361. std::string kv(b, e);
  6362. if (cache.find(kv) != cache.end()) { return; }
  6363. cache.insert(kv);
  6364. std::string key;
  6365. std::string val;
  6366. split(b, e, '=', [&](const char *b2, const char *e2) {
  6367. if (key.empty()) {
  6368. key.assign(b2, e2);
  6369. } else {
  6370. val.assign(b2, e2);
  6371. }
  6372. });
  6373. if (!key.empty()) {
  6374. params.emplace(trim_double_quotes_copy((key)),
  6375. trim_double_quotes_copy((val)));
  6376. }
  6377. });
  6378. }
  6379. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6380. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6381. #else
  6382. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6383. #endif
  6384. auto is_valid = [](const std::string &str) {
  6385. return std::all_of(str.cbegin(), str.cend(),
  6386. [](unsigned char c) { return std::isdigit(c); });
  6387. };
  6388. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6389. const auto pos = static_cast<size_t>(6);
  6390. const auto len = static_cast<size_t>(s.size() - 6);
  6391. auto all_valid_ranges = true;
  6392. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6393. if (!all_valid_ranges) { return; }
  6394. const auto it = std::find(b, e, '-');
  6395. if (it == e) {
  6396. all_valid_ranges = false;
  6397. return;
  6398. }
  6399. const auto lhs = std::string(b, it);
  6400. const auto rhs = std::string(it + 1, e);
  6401. if (!is_valid(lhs) || !is_valid(rhs)) {
  6402. all_valid_ranges = false;
  6403. return;
  6404. }
  6405. ssize_t first = -1;
  6406. if (!lhs.empty()) {
  6407. ssize_t v;
  6408. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6409. if (res.ec == std::errc{}) { first = v; }
  6410. }
  6411. ssize_t last = -1;
  6412. if (!rhs.empty()) {
  6413. ssize_t v;
  6414. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6415. if (res.ec == std::errc{}) { last = v; }
  6416. }
  6417. if ((first == -1 && last == -1) ||
  6418. (first != -1 && last != -1 && first > last)) {
  6419. all_valid_ranges = false;
  6420. return;
  6421. }
  6422. ranges.emplace_back(first, last);
  6423. });
  6424. return all_valid_ranges && !ranges.empty();
  6425. }
  6426. return false;
  6427. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6428. }
  6429. #else
  6430. } catch (...) { return false; }
  6431. #endif
  6432. inline bool parse_accept_header(const std::string &s,
  6433. std::vector<std::string> &content_types) {
  6434. content_types.clear();
  6435. // Empty string is considered valid (no preference)
  6436. if (s.empty()) { return true; }
  6437. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6438. if (s.front() == ',' || s.back() == ',' ||
  6439. s.find(",,") != std::string::npos) {
  6440. return false;
  6441. }
  6442. struct AcceptEntry {
  6443. std::string media_type;
  6444. double quality;
  6445. int order;
  6446. };
  6447. std::vector<AcceptEntry> entries;
  6448. int order = 0;
  6449. bool has_invalid_entry = false;
  6450. // Split by comma and parse each entry
  6451. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6452. std::string entry(b, e);
  6453. entry = trim_copy(entry);
  6454. if (entry.empty()) {
  6455. has_invalid_entry = true;
  6456. return;
  6457. }
  6458. AcceptEntry accept_entry;
  6459. accept_entry.order = order++;
  6460. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6461. accept_entry.media_type, accept_entry.quality)) {
  6462. has_invalid_entry = true;
  6463. return;
  6464. }
  6465. // Remove additional parameters from media type
  6466. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6467. // Basic validation of media type format
  6468. if (accept_entry.media_type.empty()) {
  6469. has_invalid_entry = true;
  6470. return;
  6471. }
  6472. // Check for basic media type format (should contain '/' or be '*')
  6473. if (accept_entry.media_type != "*" &&
  6474. accept_entry.media_type.find('/') == std::string::npos) {
  6475. has_invalid_entry = true;
  6476. return;
  6477. }
  6478. entries.push_back(std::move(accept_entry));
  6479. });
  6480. // Return false if any invalid entry was found
  6481. if (has_invalid_entry) { return false; }
  6482. // Sort by quality (descending), then by original order (ascending)
  6483. std::sort(entries.begin(), entries.end(),
  6484. [](const AcceptEntry &a, const AcceptEntry &b) {
  6485. if (a.quality != b.quality) {
  6486. return a.quality > b.quality; // Higher quality first
  6487. }
  6488. return a.order < b.order; // Earlier order first for same quality
  6489. });
  6490. // Extract sorted media types
  6491. content_types.reserve(entries.size());
  6492. for (auto &entry : entries) {
  6493. content_types.push_back(std::move(entry.media_type));
  6494. }
  6495. return true;
  6496. }
  6497. class FormDataParser {
  6498. public:
  6499. FormDataParser() = default;
  6500. void set_boundary(std::string &&boundary) {
  6501. boundary_ = std::move(boundary);
  6502. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6503. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6504. }
  6505. bool is_valid() const { return is_valid_; }
  6506. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6507. const ContentReceiver &content_callback) {
  6508. buf_append(buf, n);
  6509. while (buf_size() > 0) {
  6510. switch (state_) {
  6511. case 0: { // Initial boundary
  6512. auto pos = buf_find(dash_boundary_crlf_);
  6513. if (pos == buf_size()) { return true; }
  6514. buf_erase(pos + dash_boundary_crlf_.size());
  6515. state_ = 1;
  6516. break;
  6517. }
  6518. case 1: { // New entry
  6519. clear_file_info();
  6520. state_ = 2;
  6521. break;
  6522. }
  6523. case 2: { // Headers
  6524. auto pos = buf_find(crlf_);
  6525. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6526. while (pos < buf_size()) {
  6527. // Empty line
  6528. if (pos == 0) {
  6529. if (!header_callback(file_)) {
  6530. is_valid_ = false;
  6531. return false;
  6532. }
  6533. buf_erase(crlf_.size());
  6534. state_ = 3;
  6535. break;
  6536. }
  6537. const auto header = buf_head(pos);
  6538. if (!parse_header(header.data(), header.data() + header.size(),
  6539. [&](const std::string &, const std::string &) {})) {
  6540. is_valid_ = false;
  6541. return false;
  6542. }
  6543. // Parse and emplace space trimmed headers into a map
  6544. if (!parse_header(
  6545. header.data(), header.data() + header.size(),
  6546. [&](const std::string &key, const std::string &val) {
  6547. file_.headers.emplace(key, val);
  6548. })) {
  6549. is_valid_ = false;
  6550. return false;
  6551. }
  6552. constexpr const char header_content_type[] = "Content-Type:";
  6553. if (start_with_case_ignore(header, header_content_type)) {
  6554. file_.content_type =
  6555. trim_copy(header.substr(str_len(header_content_type)));
  6556. } else {
  6557. std::string disposition_params;
  6558. if (parse_content_disposition(header, disposition_params)) {
  6559. Params params;
  6560. parse_disposition_params(disposition_params, params);
  6561. auto it = params.find("name");
  6562. if (it != params.end()) {
  6563. file_.name = it->second;
  6564. } else {
  6565. is_valid_ = false;
  6566. return false;
  6567. }
  6568. it = params.find("filename");
  6569. if (it != params.end()) { file_.filename = it->second; }
  6570. it = params.find("filename*");
  6571. if (it != params.end()) {
  6572. // RFC 5987: only UTF-8 encoding is allowed
  6573. const auto &val = it->second;
  6574. constexpr const char utf8_prefix[] = "UTF-8''";
  6575. constexpr size_t prefix_len = str_len(utf8_prefix);
  6576. if (val.size() > prefix_len &&
  6577. start_with_case_ignore(val, utf8_prefix)) {
  6578. file_.filename = decode_path_component(
  6579. val.substr(prefix_len)); // override...
  6580. } else {
  6581. is_valid_ = false;
  6582. return false;
  6583. }
  6584. }
  6585. }
  6586. }
  6587. buf_erase(pos + crlf_.size());
  6588. pos = buf_find(crlf_);
  6589. }
  6590. if (state_ != 3) { return true; }
  6591. break;
  6592. }
  6593. case 3: { // Body
  6594. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6595. auto pos = buf_find(crlf_dash_boundary_);
  6596. if (pos < buf_size()) {
  6597. if (!content_callback(buf_data(), pos)) {
  6598. is_valid_ = false;
  6599. return false;
  6600. }
  6601. buf_erase(pos + crlf_dash_boundary_.size());
  6602. state_ = 4;
  6603. } else {
  6604. auto len = buf_size() - crlf_dash_boundary_.size();
  6605. if (len > 0) {
  6606. if (!content_callback(buf_data(), len)) {
  6607. is_valid_ = false;
  6608. return false;
  6609. }
  6610. buf_erase(len);
  6611. }
  6612. return true;
  6613. }
  6614. break;
  6615. }
  6616. case 4: { // Boundary
  6617. if (crlf_.size() > buf_size()) { return true; }
  6618. if (buf_start_with(crlf_)) {
  6619. buf_erase(crlf_.size());
  6620. state_ = 1;
  6621. } else {
  6622. if (dash_.size() > buf_size()) { return true; }
  6623. if (buf_start_with(dash_)) {
  6624. buf_erase(dash_.size());
  6625. is_valid_ = true;
  6626. buf_erase(buf_size()); // Remove epilogue
  6627. } else {
  6628. return true;
  6629. }
  6630. }
  6631. break;
  6632. }
  6633. }
  6634. }
  6635. return true;
  6636. }
  6637. private:
  6638. void clear_file_info() {
  6639. file_.name.clear();
  6640. file_.filename.clear();
  6641. file_.content_type.clear();
  6642. file_.headers.clear();
  6643. }
  6644. bool start_with_case_ignore(const std::string &a, const char *b,
  6645. size_t offset = 0) const {
  6646. const auto b_len = strlen(b);
  6647. if (a.size() < offset + b_len) { return false; }
  6648. for (size_t i = 0; i < b_len; i++) {
  6649. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6650. return false;
  6651. }
  6652. }
  6653. return true;
  6654. }
  6655. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6656. // Returns true if header matches, with the params portion in `params_out`.
  6657. bool parse_content_disposition(const std::string &header,
  6658. std::string &params_out) const {
  6659. constexpr const char prefix[] = "Content-Disposition:";
  6660. constexpr size_t prefix_len = str_len(prefix);
  6661. if (!start_with_case_ignore(header, prefix)) { return false; }
  6662. // Skip whitespace after "Content-Disposition:"
  6663. auto pos = prefix_len;
  6664. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6665. pos++;
  6666. }
  6667. // Match "form-data;" (case-insensitive)
  6668. constexpr const char form_data[] = "form-data;";
  6669. constexpr size_t form_data_len = str_len(form_data);
  6670. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6671. pos += form_data_len;
  6672. // Skip whitespace after "form-data;"
  6673. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6674. pos++;
  6675. }
  6676. params_out = header.substr(pos);
  6677. return true;
  6678. }
  6679. const std::string dash_ = "--";
  6680. const std::string crlf_ = "\r\n";
  6681. std::string boundary_;
  6682. std::string dash_boundary_crlf_;
  6683. std::string crlf_dash_boundary_;
  6684. size_t state_ = 0;
  6685. bool is_valid_ = false;
  6686. FormData file_;
  6687. // Buffer
  6688. bool start_with(const std::string &a, size_t spos, size_t epos,
  6689. const std::string &b) const {
  6690. if (epos - spos < b.size()) { return false; }
  6691. for (size_t i = 0; i < b.size(); i++) {
  6692. if (a[i + spos] != b[i]) { return false; }
  6693. }
  6694. return true;
  6695. }
  6696. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6697. const char *buf_data() const { return &buf_[buf_spos_]; }
  6698. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6699. bool buf_start_with(const std::string &s) const {
  6700. return start_with(buf_, buf_spos_, buf_epos_, s);
  6701. }
  6702. size_t buf_find(const std::string &s) const {
  6703. auto c = s.front();
  6704. size_t off = buf_spos_;
  6705. while (off < buf_epos_) {
  6706. auto pos = off;
  6707. while (true) {
  6708. if (pos == buf_epos_) { return buf_size(); }
  6709. if (buf_[pos] == c) { break; }
  6710. pos++;
  6711. }
  6712. auto remaining_size = buf_epos_ - pos;
  6713. if (s.size() > remaining_size) { return buf_size(); }
  6714. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6715. off = pos + 1;
  6716. }
  6717. return buf_size();
  6718. }
  6719. void buf_append(const char *data, size_t n) {
  6720. auto remaining_size = buf_size();
  6721. if (remaining_size > 0 && buf_spos_ > 0) {
  6722. for (size_t i = 0; i < remaining_size; i++) {
  6723. buf_[i] = buf_[buf_spos_ + i];
  6724. }
  6725. }
  6726. buf_spos_ = 0;
  6727. buf_epos_ = remaining_size;
  6728. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6729. for (size_t i = 0; i < n; i++) {
  6730. buf_[buf_epos_ + i] = data[i];
  6731. }
  6732. buf_epos_ += n;
  6733. }
  6734. void buf_erase(size_t size) { buf_spos_ += size; }
  6735. std::string buf_;
  6736. size_t buf_spos_ = 0;
  6737. size_t buf_epos_ = 0;
  6738. };
  6739. inline std::string random_string(size_t length) {
  6740. constexpr const char data[] =
  6741. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6742. thread_local auto engine([]() {
  6743. // std::random_device might actually be deterministic on some
  6744. // platforms, but due to lack of support in the c++ standard library,
  6745. // doing better requires either some ugly hacks or breaking portability.
  6746. std::random_device seed_gen;
  6747. // Request 128 bits of entropy for initialization
  6748. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6749. return std::mt19937(seed_sequence);
  6750. }());
  6751. std::string result;
  6752. for (size_t i = 0; i < length; i++) {
  6753. result += data[engine() % (sizeof(data) - 1)];
  6754. }
  6755. return result;
  6756. }
  6757. inline std::string make_multipart_data_boundary() {
  6758. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6759. }
  6760. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6761. auto valid = true;
  6762. for (size_t i = 0; i < boundary.size(); i++) {
  6763. auto c = boundary[i];
  6764. if (!std::isalnum(c) && c != '-' && c != '_') {
  6765. valid = false;
  6766. break;
  6767. }
  6768. }
  6769. return valid;
  6770. }
  6771. template <typename T>
  6772. inline std::string
  6773. serialize_multipart_formdata_item_begin(const T &item,
  6774. const std::string &boundary) {
  6775. std::string body = "--" + boundary + "\r\n";
  6776. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6777. if (!item.filename.empty()) {
  6778. body += "; filename=\"" + item.filename + "\"";
  6779. }
  6780. body += "\r\n";
  6781. if (!item.content_type.empty()) {
  6782. body += "Content-Type: " + item.content_type + "\r\n";
  6783. }
  6784. body += "\r\n";
  6785. return body;
  6786. }
  6787. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6788. inline std::string
  6789. serialize_multipart_formdata_finish(const std::string &boundary) {
  6790. return "--" + boundary + "--\r\n";
  6791. }
  6792. inline std::string
  6793. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6794. return "multipart/form-data; boundary=" + boundary;
  6795. }
  6796. inline std::string
  6797. serialize_multipart_formdata(const UploadFormDataItems &items,
  6798. const std::string &boundary, bool finish = true) {
  6799. std::string body;
  6800. for (const auto &item : items) {
  6801. body += serialize_multipart_formdata_item_begin(item, boundary);
  6802. body += item.content + serialize_multipart_formdata_item_end();
  6803. }
  6804. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  6805. return body;
  6806. }
  6807. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  6808. const std::string &boundary) {
  6809. size_t total = 0;
  6810. for (const auto &item : items) {
  6811. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  6812. total += item.content.size();
  6813. total += serialize_multipart_formdata_item_end().size();
  6814. }
  6815. total += serialize_multipart_formdata_finish(boundary).size();
  6816. return total;
  6817. }
  6818. struct MultipartSegment {
  6819. const char *data;
  6820. size_t size;
  6821. };
  6822. // NOTE: items must outlive the returned ContentProvider
  6823. // (safe for synchronous use inside Post/Put/Patch)
  6824. inline ContentProvider
  6825. make_multipart_content_provider(const UploadFormDataItems &items,
  6826. const std::string &boundary) {
  6827. // Own the per-item header strings and the finish string
  6828. std::vector<std::string> owned;
  6829. owned.reserve(items.size() + 1);
  6830. for (const auto &item : items)
  6831. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  6832. owned.push_back(serialize_multipart_formdata_finish(boundary));
  6833. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  6834. std::vector<MultipartSegment> segs;
  6835. segs.reserve(items.size() * 3 + 1);
  6836. static const char crlf[] = "\r\n";
  6837. for (size_t i = 0; i < items.size(); i++) {
  6838. segs.push_back({owned[i].data(), owned[i].size()});
  6839. segs.push_back({items[i].content.data(), items[i].content.size()});
  6840. segs.push_back({crlf, 2});
  6841. }
  6842. segs.push_back({owned.back().data(), owned.back().size()});
  6843. struct MultipartState {
  6844. std::vector<std::string> owned;
  6845. std::vector<MultipartSegment> segs;
  6846. };
  6847. auto state = std::make_shared<MultipartState>();
  6848. state->owned = std::move(owned);
  6849. // `segs` holds raw pointers into owned strings; std::string move preserves
  6850. // the data pointer, so these pointers remain valid after the move above.
  6851. state->segs = std::move(segs);
  6852. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  6853. size_t pos = 0;
  6854. for (const auto &seg : state->segs) {
  6855. // Loop invariant: pos <= offset (proven by advancing pos only when
  6856. // offset - pos >= seg.size, i.e., the segment doesn't contain offset)
  6857. if (seg.size > 0 && offset - pos < seg.size) {
  6858. size_t seg_offset = offset - pos;
  6859. size_t available = seg.size - seg_offset;
  6860. size_t to_write = (std::min)(available, length);
  6861. return sink.write(seg.data + seg_offset, to_write);
  6862. }
  6863. pos += seg.size;
  6864. }
  6865. return true; // past end (shouldn't be reached when content_length is exact)
  6866. };
  6867. }
  6868. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  6869. if (ranges.size() <= 1) return;
  6870. // Sort ranges by start position
  6871. std::sort(ranges.begin(), ranges.end(),
  6872. [](const Range &a, const Range &b) { return a.first < b.first; });
  6873. Ranges coalesced;
  6874. coalesced.reserve(ranges.size());
  6875. for (auto &r : ranges) {
  6876. auto first_pos = r.first;
  6877. auto last_pos = r.second;
  6878. // Handle special cases like in range_error
  6879. if (first_pos == -1 && last_pos == -1) {
  6880. first_pos = 0;
  6881. last_pos = static_cast<ssize_t>(content_length);
  6882. }
  6883. if (first_pos == -1) {
  6884. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  6885. last_pos = static_cast<ssize_t>(content_length) - 1;
  6886. }
  6887. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  6888. last_pos = static_cast<ssize_t>(content_length) - 1;
  6889. }
  6890. // Skip invalid ranges
  6891. if (!(0 <= first_pos && first_pos <= last_pos &&
  6892. last_pos < static_cast<ssize_t>(content_length))) {
  6893. continue;
  6894. }
  6895. // Coalesce with previous range if overlapping or adjacent (but not
  6896. // identical)
  6897. if (!coalesced.empty()) {
  6898. auto &prev = coalesced.back();
  6899. // Check if current range overlaps or is adjacent to previous range
  6900. // but don't coalesce identical ranges (allow duplicates)
  6901. if (first_pos <= prev.second + 1 &&
  6902. !(first_pos == prev.first && last_pos == prev.second)) {
  6903. // Extend the previous range
  6904. prev.second = (std::max)(prev.second, last_pos);
  6905. continue;
  6906. }
  6907. }
  6908. // Add new range
  6909. coalesced.emplace_back(first_pos, last_pos);
  6910. }
  6911. ranges = std::move(coalesced);
  6912. }
  6913. inline bool range_error(Request &req, Response &res) {
  6914. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  6915. ssize_t content_len = static_cast<ssize_t>(
  6916. res.content_length_ ? res.content_length_ : res.body.size());
  6917. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  6918. size_t overwrapping_count = 0;
  6919. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  6920. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  6921. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  6922. // Too many ranges
  6923. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  6924. for (auto &r : req.ranges) {
  6925. auto &first_pos = r.first;
  6926. auto &last_pos = r.second;
  6927. if (first_pos == -1 && last_pos == -1) {
  6928. first_pos = 0;
  6929. last_pos = content_len;
  6930. }
  6931. if (first_pos == -1) {
  6932. first_pos = content_len - last_pos;
  6933. last_pos = content_len - 1;
  6934. }
  6935. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  6936. // A client can limit the number of bytes requested without knowing the
  6937. // size of the selected representation. If the last-pos value is absent,
  6938. // or if the value is greater than or equal to the current length of the
  6939. // representation data, the byte range is interpreted as the remainder of
  6940. // the representation (i.e., the server replaces the value of last-pos
  6941. // with a value that is one less than the current length of the selected
  6942. // representation).
  6943. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  6944. if (last_pos == -1 || last_pos >= content_len) {
  6945. last_pos = content_len - 1;
  6946. }
  6947. // Range must be within content length
  6948. if (!(0 <= first_pos && first_pos <= last_pos &&
  6949. last_pos <= content_len - 1)) {
  6950. return true;
  6951. }
  6952. // Request must not have more than two overlapping ranges
  6953. for (const auto &processed_range : processed_ranges) {
  6954. if (!(last_pos < processed_range.first ||
  6955. first_pos > processed_range.second)) {
  6956. overwrapping_count++;
  6957. if (overwrapping_count > 2) { return true; }
  6958. break; // Only count once per range
  6959. }
  6960. }
  6961. processed_ranges.emplace_back(first_pos, last_pos);
  6962. }
  6963. // After validation, coalesce overlapping ranges as per RFC 9110
  6964. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  6965. }
  6966. return false;
  6967. }
  6968. inline std::pair<size_t, size_t>
  6969. get_range_offset_and_length(Range r, size_t content_length) {
  6970. assert(r.first != -1 && r.second != -1);
  6971. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  6972. assert(r.first <= r.second &&
  6973. r.second < static_cast<ssize_t>(content_length));
  6974. (void)(content_length);
  6975. return std::make_pair(static_cast<size_t>(r.first),
  6976. static_cast<size_t>(r.second - r.first) + 1);
  6977. }
  6978. inline std::string make_content_range_header_field(
  6979. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  6980. auto st = offset_and_length.first;
  6981. auto ed = st + offset_and_length.second - 1;
  6982. std::string field = "bytes ";
  6983. field += std::to_string(st);
  6984. field += '-';
  6985. field += std::to_string(ed);
  6986. field += '/';
  6987. field += std::to_string(content_length);
  6988. return field;
  6989. }
  6990. template <typename SToken, typename CToken, typename Content>
  6991. bool process_multipart_ranges_data(const Request &req,
  6992. const std::string &boundary,
  6993. const std::string &content_type,
  6994. size_t content_length, SToken stoken,
  6995. CToken ctoken, Content content) {
  6996. for (size_t i = 0; i < req.ranges.size(); i++) {
  6997. ctoken("--");
  6998. stoken(boundary);
  6999. ctoken("\r\n");
  7000. if (!content_type.empty()) {
  7001. ctoken("Content-Type: ");
  7002. stoken(content_type);
  7003. ctoken("\r\n");
  7004. }
  7005. auto offset_and_length =
  7006. get_range_offset_and_length(req.ranges[i], content_length);
  7007. ctoken("Content-Range: ");
  7008. stoken(make_content_range_header_field(offset_and_length, content_length));
  7009. ctoken("\r\n");
  7010. ctoken("\r\n");
  7011. if (!content(offset_and_length.first, offset_and_length.second)) {
  7012. return false;
  7013. }
  7014. ctoken("\r\n");
  7015. }
  7016. ctoken("--");
  7017. stoken(boundary);
  7018. ctoken("--");
  7019. return true;
  7020. }
  7021. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7022. const std::string &boundary,
  7023. const std::string &content_type,
  7024. size_t content_length,
  7025. std::string &data) {
  7026. process_multipart_ranges_data(
  7027. req, boundary, content_type, content_length,
  7028. [&](const std::string &token) { data += token; },
  7029. [&](const std::string &token) { data += token; },
  7030. [&](size_t offset, size_t length) {
  7031. assert(offset + length <= content_length);
  7032. data += res.body.substr(offset, length);
  7033. return true;
  7034. });
  7035. }
  7036. inline size_t get_multipart_ranges_data_length(const Request &req,
  7037. const std::string &boundary,
  7038. const std::string &content_type,
  7039. size_t content_length) {
  7040. size_t data_length = 0;
  7041. process_multipart_ranges_data(
  7042. req, boundary, content_type, content_length,
  7043. [&](const std::string &token) { data_length += token.size(); },
  7044. [&](const std::string &token) { data_length += token.size(); },
  7045. [&](size_t /*offset*/, size_t length) {
  7046. data_length += length;
  7047. return true;
  7048. });
  7049. return data_length;
  7050. }
  7051. template <typename T>
  7052. inline bool
  7053. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7054. const std::string &boundary,
  7055. const std::string &content_type,
  7056. size_t content_length, const T &is_shutting_down) {
  7057. return process_multipart_ranges_data(
  7058. req, boundary, content_type, content_length,
  7059. [&](const std::string &token) { strm.write(token); },
  7060. [&](const std::string &token) { strm.write(token); },
  7061. [&](size_t offset, size_t length) {
  7062. return write_content(strm, res.content_provider_, offset, length,
  7063. is_shutting_down);
  7064. });
  7065. }
  7066. inline bool expect_content(const Request &req) {
  7067. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7068. req.method == "DELETE") {
  7069. return true;
  7070. }
  7071. if (req.has_header("Content-Length") &&
  7072. req.get_header_value_u64("Content-Length") > 0) {
  7073. return true;
  7074. }
  7075. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  7076. return false;
  7077. }
  7078. #ifdef _WIN32
  7079. class WSInit {
  7080. public:
  7081. WSInit() {
  7082. WSADATA wsaData;
  7083. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7084. }
  7085. ~WSInit() {
  7086. if (is_valid_) WSACleanup();
  7087. }
  7088. bool is_valid_ = false;
  7089. };
  7090. static WSInit wsinit_;
  7091. #endif
  7092. inline bool parse_www_authenticate(const Response &res,
  7093. std::map<std::string, std::string> &auth,
  7094. bool is_proxy) {
  7095. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7096. if (res.has_header(auth_key)) {
  7097. thread_local auto re =
  7098. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7099. auto s = res.get_header_value(auth_key);
  7100. auto pos = s.find(' ');
  7101. if (pos != std::string::npos) {
  7102. auto type = s.substr(0, pos);
  7103. if (type == "Basic") {
  7104. return false;
  7105. } else if (type == "Digest") {
  7106. s = s.substr(pos + 1);
  7107. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7108. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7109. const auto &m = *i;
  7110. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7111. static_cast<size_t>(m.length(1)));
  7112. auto val = m.length(2) > 0
  7113. ? s.substr(static_cast<size_t>(m.position(2)),
  7114. static_cast<size_t>(m.length(2)))
  7115. : s.substr(static_cast<size_t>(m.position(3)),
  7116. static_cast<size_t>(m.length(3)));
  7117. auth[std::move(key)] = std::move(val);
  7118. }
  7119. return true;
  7120. }
  7121. }
  7122. }
  7123. return false;
  7124. }
  7125. class ContentProviderAdapter {
  7126. public:
  7127. explicit ContentProviderAdapter(
  7128. ContentProviderWithoutLength &&content_provider)
  7129. : content_provider_(std::move(content_provider)) {}
  7130. bool operator()(size_t offset, size_t, DataSink &sink) {
  7131. return content_provider_(offset, sink);
  7132. }
  7133. private:
  7134. ContentProviderWithoutLength content_provider_;
  7135. };
  7136. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7137. namespace fields {
  7138. inline bool is_token_char(char c) {
  7139. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7140. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7141. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7142. }
  7143. inline bool is_token(const std::string &s) {
  7144. if (s.empty()) { return false; }
  7145. for (auto c : s) {
  7146. if (!is_token_char(c)) { return false; }
  7147. }
  7148. return true;
  7149. }
  7150. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7151. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7152. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7153. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7154. inline bool is_field_content(const std::string &s) {
  7155. if (s.empty()) { return true; }
  7156. if (s.size() == 1) {
  7157. return is_field_vchar(s[0]);
  7158. } else if (s.size() == 2) {
  7159. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7160. } else {
  7161. size_t i = 0;
  7162. if (!is_field_vchar(s[i])) { return false; }
  7163. i++;
  7164. while (i < s.size() - 1) {
  7165. auto c = s[i++];
  7166. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7167. } else {
  7168. return false;
  7169. }
  7170. }
  7171. return is_field_vchar(s[i]);
  7172. }
  7173. }
  7174. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7175. } // namespace fields
  7176. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7177. int port, const std::string &path,
  7178. const Headers &headers,
  7179. std::string &selected_subprotocol) {
  7180. // Validate path and host
  7181. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7182. return false;
  7183. }
  7184. // Validate user-provided headers
  7185. for (const auto &h : headers) {
  7186. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7187. return false;
  7188. }
  7189. }
  7190. // Generate random Sec-WebSocket-Key
  7191. thread_local std::mt19937 rng(std::random_device{}());
  7192. std::string key_bytes(16, '\0');
  7193. for (size_t i = 0; i < 16; i += 4) {
  7194. auto r = rng();
  7195. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7196. }
  7197. auto client_key = base64_encode(key_bytes);
  7198. // Build upgrade request
  7199. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7200. req_str += "Host: " + host + ":" + std::to_string(port) + "\r\n";
  7201. req_str += "Upgrade: websocket\r\n";
  7202. req_str += "Connection: Upgrade\r\n";
  7203. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7204. req_str += "Sec-WebSocket-Version: 13\r\n";
  7205. for (const auto &h : headers) {
  7206. req_str += h.first + ": " + h.second + "\r\n";
  7207. }
  7208. req_str += "\r\n";
  7209. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7210. // Verify 101 response and Sec-WebSocket-Accept header
  7211. auto expected_accept = websocket_accept_key(client_key);
  7212. return read_websocket_upgrade_response(strm, expected_accept,
  7213. selected_subprotocol);
  7214. }
  7215. } // namespace detail
  7216. /*
  7217. * Group 2: detail namespace - SSL common utilities
  7218. */
  7219. #ifdef CPPHTTPLIB_SSL_ENABLED
  7220. namespace detail {
  7221. class SSLSocketStream final : public Stream {
  7222. public:
  7223. SSLSocketStream(
  7224. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7225. time_t read_timeout_usec, time_t write_timeout_sec,
  7226. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7227. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7228. (std::chrono::steady_clock::time_point::min)());
  7229. ~SSLSocketStream() override;
  7230. bool is_readable() const override;
  7231. bool wait_readable() const override;
  7232. bool wait_writable() const override;
  7233. bool is_peer_alive() const override;
  7234. ssize_t read(char *ptr, size_t size) override;
  7235. ssize_t write(const char *ptr, size_t size) override;
  7236. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7237. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7238. socket_t socket() const override;
  7239. time_t duration() const override;
  7240. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7241. private:
  7242. socket_t sock_;
  7243. tls::session_t session_;
  7244. time_t read_timeout_sec_;
  7245. time_t read_timeout_usec_;
  7246. time_t write_timeout_sec_;
  7247. time_t write_timeout_usec_;
  7248. time_t max_timeout_msec_;
  7249. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7250. };
  7251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7252. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7253. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7254. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7255. unsigned int hash_length = 0;
  7256. unsigned char hash[EVP_MAX_MD_SIZE];
  7257. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7258. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7259. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7260. std::stringstream ss;
  7261. for (auto i = 0u; i < hash_length; ++i) {
  7262. ss << std::hex << std::setw(2) << std::setfill('0')
  7263. << static_cast<unsigned int>(hash[i]);
  7264. }
  7265. return ss.str();
  7266. }
  7267. inline std::string MD5(const std::string &s) {
  7268. return message_digest(s, EVP_md5());
  7269. }
  7270. inline std::string SHA_256(const std::string &s) {
  7271. return message_digest(s, EVP_sha256());
  7272. }
  7273. inline std::string SHA_512(const std::string &s) {
  7274. return message_digest(s, EVP_sha512());
  7275. }
  7276. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7277. namespace {
  7278. template <size_t N>
  7279. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7280. std::stringstream ss;
  7281. for (size_t i = 0; i < N; ++i) {
  7282. ss << std::hex << std::setw(2) << std::setfill('0')
  7283. << static_cast<unsigned int>(hash[i]);
  7284. }
  7285. return ss.str();
  7286. }
  7287. } // namespace
  7288. inline std::string MD5(const std::string &s) {
  7289. unsigned char hash[16];
  7290. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7291. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7292. hash);
  7293. #else
  7294. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7295. hash);
  7296. #endif
  7297. return hash_to_hex(hash);
  7298. }
  7299. inline std::string SHA_256(const std::string &s) {
  7300. unsigned char hash[32];
  7301. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7302. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7303. hash, 0);
  7304. #else
  7305. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7306. s.size(), hash, 0);
  7307. #endif
  7308. return hash_to_hex(hash);
  7309. }
  7310. inline std::string SHA_512(const std::string &s) {
  7311. unsigned char hash[64];
  7312. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7313. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7314. hash, 0);
  7315. #else
  7316. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7317. s.size(), hash, 0);
  7318. #endif
  7319. return hash_to_hex(hash);
  7320. }
  7321. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7322. namespace {
  7323. template <size_t N>
  7324. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7325. std::stringstream ss;
  7326. for (size_t i = 0; i < N; ++i) {
  7327. ss << std::hex << std::setw(2) << std::setfill('0')
  7328. << static_cast<unsigned int>(hash[i]);
  7329. }
  7330. return ss.str();
  7331. }
  7332. } // namespace
  7333. inline std::string MD5(const std::string &s) {
  7334. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7335. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7336. static_cast<word32>(s.size()), hash);
  7337. return hash_to_hex(hash);
  7338. }
  7339. inline std::string SHA_256(const std::string &s) {
  7340. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7341. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7342. static_cast<word32>(s.size()), hash);
  7343. return hash_to_hex(hash);
  7344. }
  7345. inline std::string SHA_512(const std::string &s) {
  7346. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7347. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7348. static_cast<word32>(s.size()), hash);
  7349. return hash_to_hex(hash);
  7350. }
  7351. #endif
  7352. inline bool is_ip_address(const std::string &host) {
  7353. struct in_addr addr4;
  7354. struct in6_addr addr6;
  7355. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7356. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7357. }
  7358. template <typename T>
  7359. inline bool process_server_socket_ssl(
  7360. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7361. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7362. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7363. time_t write_timeout_usec, T callback) {
  7364. return process_server_socket_core(
  7365. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7366. [&](bool close_connection, bool &connection_closed) {
  7367. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7368. write_timeout_sec, write_timeout_usec);
  7369. return callback(strm, close_connection, connection_closed);
  7370. });
  7371. }
  7372. template <typename T>
  7373. inline bool process_client_socket_ssl(
  7374. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7375. time_t read_timeout_usec, time_t write_timeout_sec,
  7376. time_t write_timeout_usec, time_t max_timeout_msec,
  7377. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7378. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7379. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7380. start_time);
  7381. return callback(strm);
  7382. }
  7383. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7384. const Request &req, const std::map<std::string, std::string> &auth,
  7385. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7386. const std::string &password, bool is_proxy = false) {
  7387. std::string nc;
  7388. {
  7389. std::stringstream ss;
  7390. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7391. nc = ss.str();
  7392. }
  7393. std::string qop;
  7394. if (auth.find("qop") != auth.end()) {
  7395. qop = auth.at("qop");
  7396. if (qop.find("auth-int") != std::string::npos) {
  7397. qop = "auth-int";
  7398. } else if (qop.find("auth") != std::string::npos) {
  7399. qop = "auth";
  7400. } else {
  7401. qop.clear();
  7402. }
  7403. }
  7404. std::string algo = "MD5";
  7405. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7406. std::string response;
  7407. {
  7408. auto H = algo == "SHA-256" ? detail::SHA_256
  7409. : algo == "SHA-512" ? detail::SHA_512
  7410. : detail::MD5;
  7411. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7412. auto A2 = req.method + ":" + req.path;
  7413. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7414. if (qop.empty()) {
  7415. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7416. } else {
  7417. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7418. ":" + qop + ":" + H(A2));
  7419. }
  7420. }
  7421. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7422. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7423. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7424. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7425. (qop.empty() ? ", response=\""
  7426. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7427. cnonce + "\", response=\"") +
  7428. response + "\"" +
  7429. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7430. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7431. return std::make_pair(key, field);
  7432. }
  7433. inline bool match_hostname(const std::string &pattern,
  7434. const std::string &hostname) {
  7435. // Exact match (case-insensitive)
  7436. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7437. // Split both pattern and hostname into components by '.'
  7438. std::vector<std::string> pattern_components;
  7439. if (!pattern.empty()) {
  7440. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7441. [&](const char *b, const char *e) {
  7442. pattern_components.emplace_back(b, e);
  7443. });
  7444. }
  7445. std::vector<std::string> host_components;
  7446. if (!hostname.empty()) {
  7447. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7448. [&](const char *b, const char *e) {
  7449. host_components.emplace_back(b, e);
  7450. });
  7451. }
  7452. // Component count must match
  7453. if (host_components.size() != pattern_components.size()) { return false; }
  7454. // Compare each component with wildcard support
  7455. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7456. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7457. auto itr = pattern_components.begin();
  7458. for (const auto &h : host_components) {
  7459. auto &p = *itr;
  7460. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7461. bool partial_match = false;
  7462. if (!p.empty() && p[p.size() - 1] == '*') {
  7463. const auto prefix_length = p.size() - 1;
  7464. if (prefix_length == 0) {
  7465. partial_match = true;
  7466. } else if (h.size() >= prefix_length) {
  7467. partial_match =
  7468. std::equal(p.begin(),
  7469. p.begin() + static_cast<std::string::difference_type>(
  7470. prefix_length),
  7471. h.begin(), [](const char ca, const char cb) {
  7472. return detail::case_ignore::to_lower(ca) ==
  7473. detail::case_ignore::to_lower(cb);
  7474. });
  7475. }
  7476. }
  7477. if (!partial_match) { return false; }
  7478. }
  7479. ++itr;
  7480. }
  7481. return true;
  7482. }
  7483. #ifdef _WIN32
  7484. // Verify certificate using Windows CertGetCertificateChain API.
  7485. // This provides real-time certificate validation with Windows Update
  7486. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7487. inline bool
  7488. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7489. const std::string &hostname,
  7490. bool verify_hostname, uint64_t &out_error) {
  7491. if (der_cert.empty()) { return false; }
  7492. out_error = 0;
  7493. // Create Windows certificate context from DER data
  7494. auto cert_context = CertCreateCertificateContext(
  7495. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7496. static_cast<DWORD>(der_cert.size()));
  7497. if (!cert_context) {
  7498. out_error = GetLastError();
  7499. return false;
  7500. }
  7501. auto cert_guard =
  7502. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7503. // Setup chain parameters
  7504. CERT_CHAIN_PARA chain_para = {};
  7505. chain_para.cbSize = sizeof(chain_para);
  7506. // Build certificate chain with revocation checking
  7507. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7508. auto chain_result = CertGetCertificateChain(
  7509. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7510. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7511. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7512. nullptr, &chain_context);
  7513. if (!chain_result || !chain_context) {
  7514. out_error = GetLastError();
  7515. return false;
  7516. }
  7517. auto chain_guard =
  7518. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7519. // Check if chain has errors
  7520. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7521. out_error = chain_context->TrustStatus.dwErrorStatus;
  7522. return false;
  7523. }
  7524. // Verify SSL policy
  7525. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7526. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7527. #ifdef AUTHTYPE_SERVER
  7528. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7529. #endif
  7530. std::wstring whost;
  7531. if (verify_hostname) {
  7532. whost = u8string_to_wstring(hostname.c_str());
  7533. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7534. }
  7535. CERT_CHAIN_POLICY_PARA policy_para = {};
  7536. policy_para.cbSize = sizeof(policy_para);
  7537. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7538. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7539. #else
  7540. policy_para.dwFlags = 0;
  7541. #endif
  7542. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7543. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7544. policy_status.cbSize = sizeof(policy_status);
  7545. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7546. &policy_para, &policy_status)) {
  7547. out_error = GetLastError();
  7548. return false;
  7549. }
  7550. if (policy_status.dwError != 0) {
  7551. out_error = policy_status.dwError;
  7552. return false;
  7553. }
  7554. return true;
  7555. }
  7556. #endif // _WIN32
  7557. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t &ctx,
  7558. tls::session_t &session, socket_t sock,
  7559. bool server_certificate_verification,
  7560. const std::string &ca_cert_file_path,
  7561. tls::ca_store_t ca_cert_store,
  7562. time_t timeout_sec, time_t timeout_usec) {
  7563. using namespace tls;
  7564. ctx = create_client_context();
  7565. if (!ctx) { return false; }
  7566. if (server_certificate_verification) {
  7567. if (!ca_cert_file_path.empty()) {
  7568. load_ca_file(ctx, ca_cert_file_path.c_str());
  7569. }
  7570. if (ca_cert_store) { set_ca_store(ctx, ca_cert_store); }
  7571. load_system_certs(ctx);
  7572. }
  7573. bool is_ip = is_ip_address(host);
  7574. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7575. if (is_ip && server_certificate_verification) {
  7576. set_verify_client(ctx, false);
  7577. } else {
  7578. set_verify_client(ctx, server_certificate_verification);
  7579. }
  7580. #endif
  7581. session = create_session(ctx, sock);
  7582. if (!session) { return false; }
  7583. // RFC 6066: SNI must not be set for IP addresses
  7584. if (!is_ip) { set_sni(session, host.c_str()); }
  7585. if (server_certificate_verification) { set_hostname(session, host.c_str()); }
  7586. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7587. return false;
  7588. }
  7589. if (server_certificate_verification) {
  7590. if (get_verify_result(session) != 0) { return false; }
  7591. }
  7592. return true;
  7593. }
  7594. } // namespace detail
  7595. #endif // CPPHTTPLIB_SSL_ENABLED
  7596. /*
  7597. * Group 3: httplib namespace - Non-SSL public API implementations
  7598. */
  7599. inline void default_socket_options(socket_t sock) {
  7600. detail::set_socket_opt(sock, SOL_SOCKET,
  7601. #ifdef SO_REUSEPORT
  7602. SO_REUSEPORT,
  7603. #else
  7604. SO_REUSEADDR,
  7605. #endif
  7606. 1);
  7607. }
  7608. inline std::string get_bearer_token_auth(const Request &req) {
  7609. if (req.has_header("Authorization")) {
  7610. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7611. return req.get_header_value("Authorization")
  7612. .substr(bearer_header_prefix_len);
  7613. }
  7614. return "";
  7615. }
  7616. inline const char *status_message(int status) {
  7617. switch (status) {
  7618. case StatusCode::Continue_100: return "Continue";
  7619. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7620. case StatusCode::Processing_102: return "Processing";
  7621. case StatusCode::EarlyHints_103: return "Early Hints";
  7622. case StatusCode::OK_200: return "OK";
  7623. case StatusCode::Created_201: return "Created";
  7624. case StatusCode::Accepted_202: return "Accepted";
  7625. case StatusCode::NonAuthoritativeInformation_203:
  7626. return "Non-Authoritative Information";
  7627. case StatusCode::NoContent_204: return "No Content";
  7628. case StatusCode::ResetContent_205: return "Reset Content";
  7629. case StatusCode::PartialContent_206: return "Partial Content";
  7630. case StatusCode::MultiStatus_207: return "Multi-Status";
  7631. case StatusCode::AlreadyReported_208: return "Already Reported";
  7632. case StatusCode::IMUsed_226: return "IM Used";
  7633. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7634. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7635. case StatusCode::Found_302: return "Found";
  7636. case StatusCode::SeeOther_303: return "See Other";
  7637. case StatusCode::NotModified_304: return "Not Modified";
  7638. case StatusCode::UseProxy_305: return "Use Proxy";
  7639. case StatusCode::unused_306: return "unused";
  7640. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7641. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7642. case StatusCode::BadRequest_400: return "Bad Request";
  7643. case StatusCode::Unauthorized_401: return "Unauthorized";
  7644. case StatusCode::PaymentRequired_402: return "Payment Required";
  7645. case StatusCode::Forbidden_403: return "Forbidden";
  7646. case StatusCode::NotFound_404: return "Not Found";
  7647. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7648. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7649. case StatusCode::ProxyAuthenticationRequired_407:
  7650. return "Proxy Authentication Required";
  7651. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7652. case StatusCode::Conflict_409: return "Conflict";
  7653. case StatusCode::Gone_410: return "Gone";
  7654. case StatusCode::LengthRequired_411: return "Length Required";
  7655. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7656. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7657. case StatusCode::UriTooLong_414: return "URI Too Long";
  7658. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7659. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7660. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7661. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7662. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7663. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7664. case StatusCode::Locked_423: return "Locked";
  7665. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7666. case StatusCode::TooEarly_425: return "Too Early";
  7667. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7668. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7669. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7670. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7671. return "Request Header Fields Too Large";
  7672. case StatusCode::UnavailableForLegalReasons_451:
  7673. return "Unavailable For Legal Reasons";
  7674. case StatusCode::NotImplemented_501: return "Not Implemented";
  7675. case StatusCode::BadGateway_502: return "Bad Gateway";
  7676. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7677. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7678. case StatusCode::HttpVersionNotSupported_505:
  7679. return "HTTP Version Not Supported";
  7680. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7681. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7682. case StatusCode::LoopDetected_508: return "Loop Detected";
  7683. case StatusCode::NotExtended_510: return "Not Extended";
  7684. case StatusCode::NetworkAuthenticationRequired_511:
  7685. return "Network Authentication Required";
  7686. default:
  7687. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7688. }
  7689. }
  7690. inline std::string to_string(const Error error) {
  7691. switch (error) {
  7692. case Error::Success: return "Success (no error)";
  7693. case Error::Unknown: return "Unknown";
  7694. case Error::Connection: return "Could not establish connection";
  7695. case Error::BindIPAddress: return "Failed to bind IP address";
  7696. case Error::Read: return "Failed to read connection";
  7697. case Error::Write: return "Failed to write connection";
  7698. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7699. case Error::Canceled: return "Connection handling canceled";
  7700. case Error::SSLConnection: return "SSL connection failed";
  7701. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7702. case Error::SSLServerVerification: return "SSL server verification failed";
  7703. case Error::SSLServerHostnameVerification:
  7704. return "SSL server hostname verification failed";
  7705. case Error::UnsupportedMultipartBoundaryChars:
  7706. return "Unsupported HTTP multipart boundary characters";
  7707. case Error::Compression: return "Compression failed";
  7708. case Error::ConnectionTimeout: return "Connection timed out";
  7709. case Error::ProxyConnection: return "Proxy connection failed";
  7710. case Error::ConnectionClosed: return "Connection closed by server";
  7711. case Error::Timeout: return "Read timeout";
  7712. case Error::ResourceExhaustion: return "Resource exhaustion";
  7713. case Error::TooManyFormDataFiles: return "Too many form data files";
  7714. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7715. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7716. case Error::ExceedMaxSocketDescriptorCount:
  7717. return "Exceeded maximum socket descriptor count";
  7718. case Error::InvalidRequestLine: return "Invalid request line";
  7719. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7720. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7721. case Error::InvalidHeaders: return "Invalid headers";
  7722. case Error::MultipartParsing: return "Multipart parsing failed";
  7723. case Error::OpenFile: return "Failed to open file";
  7724. case Error::Listen: return "Failed to listen on socket";
  7725. case Error::GetSockName: return "Failed to get socket name";
  7726. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  7727. case Error::HTTPParsing: return "HTTP parsing failed";
  7728. case Error::InvalidRangeHeader: return "Invalid Range header";
  7729. default: break;
  7730. }
  7731. return "Invalid";
  7732. }
  7733. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  7734. os << to_string(obj);
  7735. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  7736. return os;
  7737. }
  7738. inline std::string hosted_at(const std::string &hostname) {
  7739. std::vector<std::string> addrs;
  7740. hosted_at(hostname, addrs);
  7741. if (addrs.empty()) { return std::string(); }
  7742. return addrs[0];
  7743. }
  7744. inline void hosted_at(const std::string &hostname,
  7745. std::vector<std::string> &addrs) {
  7746. struct addrinfo hints;
  7747. struct addrinfo *result;
  7748. memset(&hints, 0, sizeof(struct addrinfo));
  7749. hints.ai_family = AF_UNSPEC;
  7750. hints.ai_socktype = SOCK_STREAM;
  7751. hints.ai_protocol = 0;
  7752. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  7753. &result, 0)) {
  7754. #if defined __linux__ && !defined __ANDROID__
  7755. res_init();
  7756. #endif
  7757. return;
  7758. }
  7759. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  7760. for (auto rp = result; rp; rp = rp->ai_next) {
  7761. const auto &addr =
  7762. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  7763. std::string ip;
  7764. auto dummy = -1;
  7765. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  7766. dummy)) {
  7767. addrs.emplace_back(std::move(ip));
  7768. }
  7769. }
  7770. }
  7771. inline std::string encode_uri_component(const std::string &value) {
  7772. std::ostringstream escaped;
  7773. escaped.fill('0');
  7774. escaped << std::hex;
  7775. for (auto c : value) {
  7776. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7777. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7778. c == ')') {
  7779. escaped << c;
  7780. } else {
  7781. escaped << std::uppercase;
  7782. escaped << '%' << std::setw(2)
  7783. << static_cast<int>(static_cast<unsigned char>(c));
  7784. escaped << std::nouppercase;
  7785. }
  7786. }
  7787. return escaped.str();
  7788. }
  7789. inline std::string encode_uri(const std::string &value) {
  7790. std::ostringstream escaped;
  7791. escaped.fill('0');
  7792. escaped << std::hex;
  7793. for (auto c : value) {
  7794. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7795. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7796. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  7797. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  7798. escaped << c;
  7799. } else {
  7800. escaped << std::uppercase;
  7801. escaped << '%' << std::setw(2)
  7802. << static_cast<int>(static_cast<unsigned char>(c));
  7803. escaped << std::nouppercase;
  7804. }
  7805. }
  7806. return escaped.str();
  7807. }
  7808. inline std::string decode_uri_component(const std::string &value) {
  7809. std::string result;
  7810. for (size_t i = 0; i < value.size(); i++) {
  7811. if (value[i] == '%' && i + 2 < value.size()) {
  7812. auto val = 0;
  7813. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7814. result += static_cast<char>(val);
  7815. i += 2;
  7816. } else {
  7817. result += value[i];
  7818. }
  7819. } else {
  7820. result += value[i];
  7821. }
  7822. }
  7823. return result;
  7824. }
  7825. inline std::string decode_uri(const std::string &value) {
  7826. std::string result;
  7827. for (size_t i = 0; i < value.size(); i++) {
  7828. if (value[i] == '%' && i + 2 < value.size()) {
  7829. auto val = 0;
  7830. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7831. result += static_cast<char>(val);
  7832. i += 2;
  7833. } else {
  7834. result += value[i];
  7835. }
  7836. } else {
  7837. result += value[i];
  7838. }
  7839. }
  7840. return result;
  7841. }
  7842. inline std::string encode_path_component(const std::string &component) {
  7843. std::string result;
  7844. result.reserve(component.size() * 3);
  7845. for (size_t i = 0; i < component.size(); i++) {
  7846. auto c = static_cast<unsigned char>(component[i]);
  7847. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  7848. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7849. result += static_cast<char>(c);
  7850. }
  7851. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  7852. // "," / ";" / "="
  7853. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  7854. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  7855. c == '=') {
  7856. result += static_cast<char>(c);
  7857. }
  7858. // Colon is allowed in path segments except first segment
  7859. else if (c == ':') {
  7860. result += static_cast<char>(c);
  7861. }
  7862. // @ is allowed in path
  7863. else if (c == '@') {
  7864. result += static_cast<char>(c);
  7865. } else {
  7866. result += '%';
  7867. char hex[3];
  7868. snprintf(hex, sizeof(hex), "%02X", c);
  7869. result.append(hex, 2);
  7870. }
  7871. }
  7872. return result;
  7873. }
  7874. inline std::string decode_path_component(const std::string &component) {
  7875. std::string result;
  7876. result.reserve(component.size());
  7877. for (size_t i = 0; i < component.size(); i++) {
  7878. if (component[i] == '%' && i + 1 < component.size()) {
  7879. if (component[i + 1] == 'u') {
  7880. // Unicode %uXXXX encoding
  7881. auto val = 0;
  7882. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  7883. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  7884. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  7885. char buff[4];
  7886. size_t len = detail::to_utf8(val, buff);
  7887. if (len > 0) { result.append(buff, len); }
  7888. i += 5; // 'u0000'
  7889. } else {
  7890. result += component[i];
  7891. }
  7892. } else {
  7893. // Standard %XX encoding
  7894. auto val = 0;
  7895. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  7896. // 2 digits hex codes
  7897. result += static_cast<char>(val);
  7898. i += 2; // 'XX'
  7899. } else {
  7900. result += component[i];
  7901. }
  7902. }
  7903. } else {
  7904. result += component[i];
  7905. }
  7906. }
  7907. return result;
  7908. }
  7909. inline std::string encode_query_component(const std::string &component,
  7910. bool space_as_plus) {
  7911. std::string result;
  7912. result.reserve(component.size() * 3);
  7913. for (size_t i = 0; i < component.size(); i++) {
  7914. auto c = static_cast<unsigned char>(component[i]);
  7915. // Unreserved characters per RFC 3986
  7916. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7917. result += static_cast<char>(c);
  7918. }
  7919. // Space handling
  7920. else if (c == ' ') {
  7921. if (space_as_plus) {
  7922. result += '+';
  7923. } else {
  7924. result += "%20";
  7925. }
  7926. }
  7927. // Plus sign handling
  7928. else if (c == '+') {
  7929. if (space_as_plus) {
  7930. result += "%2B";
  7931. } else {
  7932. result += static_cast<char>(c);
  7933. }
  7934. }
  7935. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  7936. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  7937. c == '*' || c == ',' || c == ';') {
  7938. result += static_cast<char>(c);
  7939. }
  7940. // Colon and @ are allowed in query
  7941. else if (c == ':' || c == '@') {
  7942. result += static_cast<char>(c);
  7943. }
  7944. // Forward slash is allowed in query values
  7945. else if (c == '/') {
  7946. result += static_cast<char>(c);
  7947. }
  7948. // Question mark is allowed in query values (after first ?)
  7949. else if (c == '?') {
  7950. result += static_cast<char>(c);
  7951. } else {
  7952. result += '%';
  7953. char hex[3];
  7954. snprintf(hex, sizeof(hex), "%02X", c);
  7955. result.append(hex, 2);
  7956. }
  7957. }
  7958. return result;
  7959. }
  7960. inline std::string decode_query_component(const std::string &component,
  7961. bool plus_as_space) {
  7962. std::string result;
  7963. result.reserve(component.size());
  7964. for (size_t i = 0; i < component.size(); i++) {
  7965. if (component[i] == '%' && i + 2 < component.size()) {
  7966. std::string hex = component.substr(i + 1, 2);
  7967. char *end;
  7968. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  7969. if (end == hex.c_str() + 2) {
  7970. result += static_cast<char>(value);
  7971. i += 2;
  7972. } else {
  7973. result += component[i];
  7974. }
  7975. } else if (component[i] == '+' && plus_as_space) {
  7976. result += ' '; // + becomes space in form-urlencoded
  7977. } else {
  7978. result += component[i];
  7979. }
  7980. }
  7981. return result;
  7982. }
  7983. inline std::string sanitize_filename(const std::string &filename) {
  7984. // Extract basename: find the last path separator (/ or \)
  7985. auto pos = filename.find_last_of("/\\");
  7986. auto result =
  7987. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  7988. // Strip null bytes
  7989. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  7990. // Trim whitespace
  7991. {
  7992. auto start = result.find_first_not_of(" \t");
  7993. auto end = result.find_last_not_of(" \t");
  7994. result = (start == std::string::npos)
  7995. ? ""
  7996. : result.substr(start, end - start + 1);
  7997. }
  7998. // Reject . and ..
  7999. if (result == "." || result == "..") { return ""; }
  8000. return result;
  8001. }
  8002. inline std::string append_query_params(const std::string &path,
  8003. const Params &params) {
  8004. std::string path_with_query = path;
  8005. thread_local const std::regex re("[^?]+\\?.*");
  8006. auto delm = std::regex_match(path, re) ? '&' : '?';
  8007. path_with_query += delm + detail::params_to_query_str(params);
  8008. return path_with_query;
  8009. }
  8010. // Header utilities
  8011. inline std::pair<std::string, std::string>
  8012. make_range_header(const Ranges &ranges) {
  8013. std::string field = "bytes=";
  8014. auto i = 0;
  8015. for (const auto &r : ranges) {
  8016. if (i != 0) { field += ", "; }
  8017. if (r.first != -1) { field += std::to_string(r.first); }
  8018. field += '-';
  8019. if (r.second != -1) { field += std::to_string(r.second); }
  8020. i++;
  8021. }
  8022. return std::make_pair("Range", std::move(field));
  8023. }
  8024. inline std::pair<std::string, std::string>
  8025. make_basic_authentication_header(const std::string &username,
  8026. const std::string &password, bool is_proxy) {
  8027. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8028. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8029. return std::make_pair(key, std::move(field));
  8030. }
  8031. inline std::pair<std::string, std::string>
  8032. make_bearer_token_authentication_header(const std::string &token,
  8033. bool is_proxy = false) {
  8034. auto field = "Bearer " + token;
  8035. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8036. return std::make_pair(key, std::move(field));
  8037. }
  8038. // Request implementation
  8039. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8040. size_t id) const {
  8041. return detail::get_header_value_u64(headers, key, def, id);
  8042. }
  8043. inline bool Request::has_header(const std::string &key) const {
  8044. return detail::has_header(headers, key);
  8045. }
  8046. inline std::string Request::get_header_value(const std::string &key,
  8047. const char *def, size_t id) const {
  8048. return detail::get_header_value(headers, key, def, id);
  8049. }
  8050. inline size_t Request::get_header_value_count(const std::string &key) const {
  8051. auto r = headers.equal_range(key);
  8052. return static_cast<size_t>(std::distance(r.first, r.second));
  8053. }
  8054. inline void Request::set_header(const std::string &key,
  8055. const std::string &val) {
  8056. if (detail::fields::is_field_name(key) &&
  8057. detail::fields::is_field_value(val)) {
  8058. headers.emplace(key, val);
  8059. }
  8060. }
  8061. inline bool Request::has_trailer(const std::string &key) const {
  8062. return trailers.find(key) != trailers.end();
  8063. }
  8064. inline std::string Request::get_trailer_value(const std::string &key,
  8065. size_t id) const {
  8066. auto rng = trailers.equal_range(key);
  8067. auto it = rng.first;
  8068. std::advance(it, static_cast<ssize_t>(id));
  8069. if (it != rng.second) { return it->second; }
  8070. return std::string();
  8071. }
  8072. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8073. auto r = trailers.equal_range(key);
  8074. return static_cast<size_t>(std::distance(r.first, r.second));
  8075. }
  8076. inline bool Request::has_param(const std::string &key) const {
  8077. return params.find(key) != params.end();
  8078. }
  8079. inline std::string Request::get_param_value(const std::string &key,
  8080. size_t id) const {
  8081. auto rng = params.equal_range(key);
  8082. auto it = rng.first;
  8083. std::advance(it, static_cast<ssize_t>(id));
  8084. if (it != rng.second) { return it->second; }
  8085. return std::string();
  8086. }
  8087. inline size_t Request::get_param_value_count(const std::string &key) const {
  8088. auto r = params.equal_range(key);
  8089. return static_cast<size_t>(std::distance(r.first, r.second));
  8090. }
  8091. inline bool Request::is_multipart_form_data() const {
  8092. const auto &content_type = get_header_value("Content-Type");
  8093. return detail::extract_media_type(content_type) == "multipart/form-data";
  8094. }
  8095. // Multipart FormData implementation
  8096. inline std::string MultipartFormData::get_field(const std::string &key,
  8097. size_t id) const {
  8098. auto rng = fields.equal_range(key);
  8099. auto it = rng.first;
  8100. std::advance(it, static_cast<ssize_t>(id));
  8101. if (it != rng.second) { return it->second.content; }
  8102. return std::string();
  8103. }
  8104. inline std::vector<std::string>
  8105. MultipartFormData::get_fields(const std::string &key) const {
  8106. std::vector<std::string> values;
  8107. auto rng = fields.equal_range(key);
  8108. for (auto it = rng.first; it != rng.second; it++) {
  8109. values.push_back(it->second.content);
  8110. }
  8111. return values;
  8112. }
  8113. inline bool MultipartFormData::has_field(const std::string &key) const {
  8114. return fields.find(key) != fields.end();
  8115. }
  8116. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8117. auto r = fields.equal_range(key);
  8118. return static_cast<size_t>(std::distance(r.first, r.second));
  8119. }
  8120. inline FormData MultipartFormData::get_file(const std::string &key,
  8121. size_t id) const {
  8122. auto rng = files.equal_range(key);
  8123. auto it = rng.first;
  8124. std::advance(it, static_cast<ssize_t>(id));
  8125. if (it != rng.second) { return it->second; }
  8126. return FormData();
  8127. }
  8128. inline std::vector<FormData>
  8129. MultipartFormData::get_files(const std::string &key) const {
  8130. std::vector<FormData> values;
  8131. auto rng = files.equal_range(key);
  8132. for (auto it = rng.first; it != rng.second; it++) {
  8133. values.push_back(it->second);
  8134. }
  8135. return values;
  8136. }
  8137. inline bool MultipartFormData::has_file(const std::string &key) const {
  8138. return files.find(key) != files.end();
  8139. }
  8140. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8141. auto r = files.equal_range(key);
  8142. return static_cast<size_t>(std::distance(r.first, r.second));
  8143. }
  8144. // Response implementation
  8145. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8146. size_t id) const {
  8147. return detail::get_header_value_u64(headers, key, def, id);
  8148. }
  8149. inline bool Response::has_header(const std::string &key) const {
  8150. return headers.find(key) != headers.end();
  8151. }
  8152. inline std::string Response::get_header_value(const std::string &key,
  8153. const char *def,
  8154. size_t id) const {
  8155. return detail::get_header_value(headers, key, def, id);
  8156. }
  8157. inline size_t Response::get_header_value_count(const std::string &key) const {
  8158. auto r = headers.equal_range(key);
  8159. return static_cast<size_t>(std::distance(r.first, r.second));
  8160. }
  8161. inline void Response::set_header(const std::string &key,
  8162. const std::string &val) {
  8163. if (detail::fields::is_field_name(key) &&
  8164. detail::fields::is_field_value(val)) {
  8165. headers.emplace(key, val);
  8166. }
  8167. }
  8168. inline bool Response::has_trailer(const std::string &key) const {
  8169. return trailers.find(key) != trailers.end();
  8170. }
  8171. inline std::string Response::get_trailer_value(const std::string &key,
  8172. size_t id) const {
  8173. auto rng = trailers.equal_range(key);
  8174. auto it = rng.first;
  8175. std::advance(it, static_cast<ssize_t>(id));
  8176. if (it != rng.second) { return it->second; }
  8177. return std::string();
  8178. }
  8179. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8180. auto r = trailers.equal_range(key);
  8181. return static_cast<size_t>(std::distance(r.first, r.second));
  8182. }
  8183. inline void Response::set_redirect(const std::string &url, int stat) {
  8184. if (detail::fields::is_field_value(url)) {
  8185. set_header("Location", url);
  8186. if (300 <= stat && stat < 400) {
  8187. this->status = stat;
  8188. } else {
  8189. this->status = StatusCode::Found_302;
  8190. }
  8191. }
  8192. }
  8193. inline void Response::set_content(const char *s, size_t n,
  8194. const std::string &content_type) {
  8195. body.assign(s, n);
  8196. auto rng = headers.equal_range("Content-Type");
  8197. headers.erase(rng.first, rng.second);
  8198. set_header("Content-Type", content_type);
  8199. }
  8200. inline void Response::set_content(const std::string &s,
  8201. const std::string &content_type) {
  8202. set_content(s.data(), s.size(), content_type);
  8203. }
  8204. inline void Response::set_content(std::string &&s,
  8205. const std::string &content_type) {
  8206. body = std::move(s);
  8207. auto rng = headers.equal_range("Content-Type");
  8208. headers.erase(rng.first, rng.second);
  8209. set_header("Content-Type", content_type);
  8210. }
  8211. inline void Response::set_content_provider(
  8212. size_t in_length, const std::string &content_type, ContentProvider provider,
  8213. ContentProviderResourceReleaser resource_releaser) {
  8214. set_header("Content-Type", content_type);
  8215. content_length_ = in_length;
  8216. if (in_length > 0) { content_provider_ = std::move(provider); }
  8217. content_provider_resource_releaser_ = std::move(resource_releaser);
  8218. is_chunked_content_provider_ = false;
  8219. }
  8220. inline void Response::set_content_provider(
  8221. const std::string &content_type, ContentProviderWithoutLength provider,
  8222. ContentProviderResourceReleaser resource_releaser) {
  8223. set_header("Content-Type", content_type);
  8224. content_length_ = 0;
  8225. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8226. content_provider_resource_releaser_ = std::move(resource_releaser);
  8227. is_chunked_content_provider_ = false;
  8228. }
  8229. inline void Response::set_chunked_content_provider(
  8230. const std::string &content_type, ContentProviderWithoutLength provider,
  8231. ContentProviderResourceReleaser resource_releaser) {
  8232. set_header("Content-Type", content_type);
  8233. content_length_ = 0;
  8234. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8235. content_provider_resource_releaser_ = std::move(resource_releaser);
  8236. is_chunked_content_provider_ = true;
  8237. }
  8238. inline void Response::set_file_content(const std::string &path,
  8239. const std::string &content_type) {
  8240. file_content_path_ = path;
  8241. file_content_content_type_ = content_type;
  8242. }
  8243. inline void Response::set_file_content(const std::string &path) {
  8244. file_content_path_ = path;
  8245. }
  8246. // Result implementation
  8247. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8248. size_t def,
  8249. size_t id) const {
  8250. return detail::get_header_value_u64(request_headers_, key, def, id);
  8251. }
  8252. inline bool Result::has_request_header(const std::string &key) const {
  8253. return request_headers_.find(key) != request_headers_.end();
  8254. }
  8255. inline std::string Result::get_request_header_value(const std::string &key,
  8256. const char *def,
  8257. size_t id) const {
  8258. return detail::get_header_value(request_headers_, key, def, id);
  8259. }
  8260. inline size_t
  8261. Result::get_request_header_value_count(const std::string &key) const {
  8262. auto r = request_headers_.equal_range(key);
  8263. return static_cast<size_t>(std::distance(r.first, r.second));
  8264. }
  8265. // Stream implementation
  8266. inline ssize_t Stream::write(const char *ptr) {
  8267. return write(ptr, strlen(ptr));
  8268. }
  8269. inline ssize_t Stream::write(const std::string &s) {
  8270. return write(s.data(), s.size());
  8271. }
  8272. // BodyReader implementation
  8273. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8274. if (!stream) {
  8275. last_error = Error::Connection;
  8276. return -1;
  8277. }
  8278. if (eof) { return 0; }
  8279. if (!chunked) {
  8280. // Content-Length based reading
  8281. if (has_content_length && bytes_read >= content_length) {
  8282. eof = true;
  8283. return 0;
  8284. }
  8285. auto to_read = len;
  8286. if (has_content_length) {
  8287. auto remaining = content_length - bytes_read;
  8288. to_read = (std::min)(len, remaining);
  8289. }
  8290. auto n = stream->read(buf, to_read);
  8291. if (n < 0) {
  8292. last_error = stream->get_error();
  8293. if (last_error == Error::Success) { last_error = Error::Read; }
  8294. eof = true;
  8295. return n;
  8296. }
  8297. if (n == 0) {
  8298. // Unexpected EOF before content_length
  8299. last_error = stream->get_error();
  8300. if (last_error == Error::Success) { last_error = Error::Read; }
  8301. eof = true;
  8302. return 0;
  8303. }
  8304. bytes_read += static_cast<size_t>(n);
  8305. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8306. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8307. last_error = Error::ExceedMaxPayloadSize;
  8308. eof = true;
  8309. return -1;
  8310. }
  8311. return n;
  8312. }
  8313. // Chunked transfer encoding: delegate to shared decoder instance.
  8314. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8315. size_t chunk_offset = 0;
  8316. size_t chunk_total = 0;
  8317. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8318. if (n < 0) {
  8319. last_error = stream->get_error();
  8320. if (last_error == Error::Success) { last_error = Error::Read; }
  8321. eof = true;
  8322. return n;
  8323. }
  8324. if (n == 0) {
  8325. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8326. eof = true;
  8327. return 0;
  8328. }
  8329. bytes_read += static_cast<size_t>(n);
  8330. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8331. last_error = Error::ExceedMaxPayloadSize;
  8332. eof = true;
  8333. return -1;
  8334. }
  8335. return n;
  8336. }
  8337. // ThreadPool implementation
  8338. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr)
  8339. : base_thread_count_(n), max_queued_requests_(mqr), idle_thread_count_(0),
  8340. shutdown_(false) {
  8341. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8342. if (max_n != 0 && max_n < n) {
  8343. std::string msg = "max_threads must be >= base_threads";
  8344. throw std::invalid_argument(msg);
  8345. }
  8346. #endif
  8347. max_thread_count_ = max_n == 0 ? n : max_n;
  8348. threads_.reserve(base_thread_count_);
  8349. for (size_t i = 0; i < base_thread_count_; i++) {
  8350. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8351. }
  8352. }
  8353. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8354. {
  8355. std::unique_lock<std::mutex> lock(mutex_);
  8356. if (shutdown_) { return false; }
  8357. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8358. return false;
  8359. }
  8360. jobs_.push_back(std::move(fn));
  8361. // Spawn a dynamic thread if no idle threads and under max
  8362. if (idle_thread_count_ == 0 &&
  8363. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8364. cleanup_finished_threads();
  8365. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8366. }
  8367. }
  8368. cond_.notify_one();
  8369. return true;
  8370. }
  8371. inline void ThreadPool::shutdown() {
  8372. {
  8373. std::unique_lock<std::mutex> lock(mutex_);
  8374. shutdown_ = true;
  8375. }
  8376. cond_.notify_all();
  8377. for (auto &t : threads_) {
  8378. if (t.joinable()) { t.join(); }
  8379. }
  8380. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8381. // with worker threads that call move_to_finished() concurrently.
  8382. std::list<std::thread> remaining_dynamic;
  8383. {
  8384. std::unique_lock<std::mutex> lock(mutex_);
  8385. remaining_dynamic = std::move(dynamic_threads_);
  8386. }
  8387. for (auto &t : remaining_dynamic) {
  8388. if (t.joinable()) { t.join(); }
  8389. }
  8390. std::unique_lock<std::mutex> lock(mutex_);
  8391. cleanup_finished_threads();
  8392. }
  8393. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8394. // Must be called with mutex_ held
  8395. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8396. if (it->get_id() == id) {
  8397. finished_threads_.push_back(std::move(*it));
  8398. dynamic_threads_.erase(it);
  8399. return;
  8400. }
  8401. }
  8402. }
  8403. inline void ThreadPool::cleanup_finished_threads() {
  8404. // Must be called with mutex_ held
  8405. for (auto &t : finished_threads_) {
  8406. if (t.joinable()) { t.join(); }
  8407. }
  8408. finished_threads_.clear();
  8409. }
  8410. inline void ThreadPool::worker(bool is_dynamic) {
  8411. for (;;) {
  8412. std::function<void()> fn;
  8413. {
  8414. std::unique_lock<std::mutex> lock(mutex_);
  8415. idle_thread_count_++;
  8416. if (is_dynamic) {
  8417. auto has_work = cond_.wait_for(
  8418. lock, std::chrono::seconds(CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT),
  8419. [&] { return !jobs_.empty() || shutdown_; });
  8420. if (!has_work) {
  8421. // Timed out with no work - exit this dynamic thread
  8422. idle_thread_count_--;
  8423. move_to_finished(std::this_thread::get_id());
  8424. break;
  8425. }
  8426. } else {
  8427. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8428. }
  8429. idle_thread_count_--;
  8430. if (shutdown_ && jobs_.empty()) { break; }
  8431. fn = std::move(jobs_.front());
  8432. jobs_.pop_front();
  8433. }
  8434. assert(true == static_cast<bool>(fn));
  8435. fn();
  8436. // Dynamic thread: exit if queue is empty after task completion
  8437. if (is_dynamic) {
  8438. std::unique_lock<std::mutex> lock(mutex_);
  8439. if (jobs_.empty()) {
  8440. move_to_finished(std::this_thread::get_id());
  8441. break;
  8442. }
  8443. }
  8444. }
  8445. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8446. !defined(LIBRESSL_VERSION_NUMBER)
  8447. OPENSSL_thread_stop();
  8448. #endif
  8449. }
  8450. /*
  8451. * Group 1 (continued): detail namespace - Stream implementations
  8452. */
  8453. namespace detail {
  8454. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8455. time_t timeout_sec, time_t timeout_usec,
  8456. time_t &actual_timeout_sec,
  8457. time_t &actual_timeout_usec) {
  8458. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8459. auto actual_timeout_msec =
  8460. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8461. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8462. actual_timeout_sec = actual_timeout_msec / 1000;
  8463. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8464. }
  8465. // Socket stream implementation
  8466. inline SocketStream::SocketStream(
  8467. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8468. time_t write_timeout_sec, time_t write_timeout_usec,
  8469. time_t max_timeout_msec,
  8470. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8471. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8472. read_timeout_usec_(read_timeout_usec),
  8473. write_timeout_sec_(write_timeout_sec),
  8474. write_timeout_usec_(write_timeout_usec),
  8475. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8476. read_buff_(read_buff_size_, 0) {}
  8477. inline SocketStream::~SocketStream() = default;
  8478. inline bool SocketStream::is_readable() const {
  8479. return read_buff_off_ < read_buff_content_size_;
  8480. }
  8481. inline bool SocketStream::wait_readable() const {
  8482. if (max_timeout_msec_ <= 0) {
  8483. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8484. }
  8485. time_t read_timeout_sec;
  8486. time_t read_timeout_usec;
  8487. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8488. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8489. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8490. }
  8491. inline bool SocketStream::wait_writable() const {
  8492. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8493. }
  8494. inline bool SocketStream::is_peer_alive() const {
  8495. return detail::is_socket_alive(sock_);
  8496. }
  8497. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8498. #ifdef _WIN32
  8499. size =
  8500. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8501. #else
  8502. size = (std::min)(size,
  8503. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8504. #endif
  8505. if (read_buff_off_ < read_buff_content_size_) {
  8506. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8507. if (size <= remaining_size) {
  8508. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8509. read_buff_off_ += size;
  8510. return static_cast<ssize_t>(size);
  8511. } else {
  8512. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8513. read_buff_off_ += remaining_size;
  8514. return static_cast<ssize_t>(remaining_size);
  8515. }
  8516. }
  8517. if (!wait_readable()) {
  8518. error_ = Error::Timeout;
  8519. return -1;
  8520. }
  8521. read_buff_off_ = 0;
  8522. read_buff_content_size_ = 0;
  8523. if (size < read_buff_size_) {
  8524. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8525. CPPHTTPLIB_RECV_FLAGS);
  8526. if (n <= 0) {
  8527. if (n == 0) {
  8528. error_ = Error::ConnectionClosed;
  8529. } else {
  8530. error_ = Error::Read;
  8531. }
  8532. return n;
  8533. } else if (n <= static_cast<ssize_t>(size)) {
  8534. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8535. return n;
  8536. } else {
  8537. memcpy(ptr, read_buff_.data(), size);
  8538. read_buff_off_ = size;
  8539. read_buff_content_size_ = static_cast<size_t>(n);
  8540. return static_cast<ssize_t>(size);
  8541. }
  8542. } else {
  8543. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8544. if (n <= 0) {
  8545. if (n == 0) {
  8546. error_ = Error::ConnectionClosed;
  8547. } else {
  8548. error_ = Error::Read;
  8549. }
  8550. }
  8551. return n;
  8552. }
  8553. }
  8554. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8555. if (!wait_writable()) { return -1; }
  8556. #if defined(_WIN32) && !defined(_WIN64)
  8557. size =
  8558. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8559. #endif
  8560. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8561. }
  8562. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8563. int &port) const {
  8564. return detail::get_remote_ip_and_port(sock_, ip, port);
  8565. }
  8566. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8567. int &port) const {
  8568. return detail::get_local_ip_and_port(sock_, ip, port);
  8569. }
  8570. inline socket_t SocketStream::socket() const { return sock_; }
  8571. inline time_t SocketStream::duration() const {
  8572. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8573. std::chrono::steady_clock::now() - start_time_)
  8574. .count();
  8575. }
  8576. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8577. read_timeout_sec_ = sec;
  8578. read_timeout_usec_ = usec;
  8579. }
  8580. // Buffer stream implementation
  8581. inline bool BufferStream::is_readable() const { return true; }
  8582. inline bool BufferStream::wait_readable() const { return true; }
  8583. inline bool BufferStream::wait_writable() const { return true; }
  8584. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8585. #if defined(_MSC_VER) && _MSC_VER < 1910
  8586. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8587. #else
  8588. auto len_read = buffer.copy(ptr, size, position);
  8589. #endif
  8590. position += static_cast<size_t>(len_read);
  8591. return static_cast<ssize_t>(len_read);
  8592. }
  8593. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8594. buffer.append(ptr, size);
  8595. return static_cast<ssize_t>(size);
  8596. }
  8597. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8598. int & /*port*/) const {}
  8599. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8600. int & /*port*/) const {}
  8601. inline socket_t BufferStream::socket() const { return 0; }
  8602. inline time_t BufferStream::duration() const { return 0; }
  8603. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8604. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8605. : MatcherBase(pattern) {
  8606. constexpr const char marker[] = "/:";
  8607. // One past the last ending position of a path param substring
  8608. std::size_t last_param_end = 0;
  8609. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8610. // Needed to ensure that parameter names are unique during matcher
  8611. // construction
  8612. // If exceptions are disabled, only last duplicate path
  8613. // parameter will be set
  8614. std::unordered_set<std::string> param_name_set;
  8615. #endif
  8616. while (true) {
  8617. const auto marker_pos = pattern.find(
  8618. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8619. if (marker_pos == std::string::npos) { break; }
  8620. static_fragments_.push_back(
  8621. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8622. const auto param_name_start = marker_pos + str_len(marker);
  8623. auto sep_pos = pattern.find(separator, param_name_start);
  8624. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8625. auto param_name =
  8626. pattern.substr(param_name_start, sep_pos - param_name_start);
  8627. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8628. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8629. std::string msg = "Encountered path parameter '" + param_name +
  8630. "' multiple times in route pattern '" + pattern + "'.";
  8631. throw std::invalid_argument(msg);
  8632. }
  8633. #endif
  8634. param_names_.push_back(std::move(param_name));
  8635. last_param_end = sep_pos + 1;
  8636. }
  8637. if (last_param_end < pattern.length()) {
  8638. static_fragments_.push_back(pattern.substr(last_param_end));
  8639. }
  8640. }
  8641. inline bool PathParamsMatcher::match(Request &request) const {
  8642. request.matches = std::smatch();
  8643. request.path_params.clear();
  8644. request.path_params.reserve(param_names_.size());
  8645. // One past the position at which the path matched the pattern last time
  8646. std::size_t starting_pos = 0;
  8647. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8648. const auto &fragment = static_fragments_[i];
  8649. if (starting_pos + fragment.length() > request.path.length()) {
  8650. return false;
  8651. }
  8652. // Avoid unnecessary allocation by using strncmp instead of substr +
  8653. // comparison
  8654. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8655. fragment.length()) != 0) {
  8656. return false;
  8657. }
  8658. starting_pos += fragment.length();
  8659. // Should only happen when we have a static fragment after a param
  8660. // Example: '/users/:id/subscriptions'
  8661. // The 'subscriptions' fragment here does not have a corresponding param
  8662. if (i >= param_names_.size()) { continue; }
  8663. auto sep_pos = request.path.find(separator, starting_pos);
  8664. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8665. const auto &param_name = param_names_[i];
  8666. request.path_params.emplace(
  8667. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8668. // Mark everything up to '/' as matched
  8669. starting_pos = sep_pos + 1;
  8670. }
  8671. // Returns false if the path is longer than the pattern
  8672. return starting_pos >= request.path.length();
  8673. }
  8674. inline bool RegexMatcher::match(Request &request) const {
  8675. request.path_params.clear();
  8676. return std::regex_match(request.path, request.matches, regex_);
  8677. }
  8678. // Enclose IPv6 address in brackets if needed
  8679. inline std::string prepare_host_string(const std::string &host) {
  8680. // Enclose IPv6 address in brackets (but not if already enclosed)
  8681. if (host.find(':') == std::string::npos ||
  8682. (!host.empty() && host[0] == '[')) {
  8683. // IPv4, hostname, or already bracketed IPv6
  8684. return host;
  8685. } else {
  8686. // IPv6 address without brackets
  8687. return "[" + host + "]";
  8688. }
  8689. }
  8690. inline std::string make_host_and_port_string(const std::string &host, int port,
  8691. bool is_ssl) {
  8692. auto result = prepare_host_string(host);
  8693. // Append port if not default
  8694. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  8695. ; // do nothing
  8696. } else {
  8697. result += ":" + std::to_string(port);
  8698. }
  8699. return result;
  8700. }
  8701. // Create "host:port" string always including port number (for CONNECT method)
  8702. inline std::string
  8703. make_host_and_port_string_always_port(const std::string &host, int port) {
  8704. return prepare_host_string(host) + ":" + std::to_string(port);
  8705. }
  8706. template <typename T>
  8707. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  8708. T header_writer, Error &error) {
  8709. for (const auto &h : headers) {
  8710. if (!detail::fields::is_field_name(h.first) ||
  8711. !detail::fields::is_field_value(h.second)) {
  8712. error = Error::InvalidHeaders;
  8713. return false;
  8714. }
  8715. }
  8716. if (header_writer(strm, headers) <= 0) {
  8717. error = Error::Write;
  8718. return false;
  8719. }
  8720. return true;
  8721. }
  8722. } // namespace detail
  8723. /*
  8724. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  8725. */
  8726. #ifdef CPPHTTPLIB_SSL_ENABLED
  8727. namespace detail {
  8728. // SSL socket stream implementation
  8729. inline SSLSocketStream::SSLSocketStream(
  8730. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8731. time_t read_timeout_usec, time_t write_timeout_sec,
  8732. time_t write_timeout_usec, time_t max_timeout_msec,
  8733. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8734. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  8735. read_timeout_usec_(read_timeout_usec),
  8736. write_timeout_sec_(write_timeout_sec),
  8737. write_timeout_usec_(write_timeout_usec),
  8738. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8739. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8740. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  8741. // Note: create_session() also clears this, but SSLClient currently
  8742. // uses ssl_new() which does not. Until full TLS API migration is complete,
  8743. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  8744. // SSL session was created.
  8745. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  8746. #endif
  8747. }
  8748. inline SSLSocketStream::~SSLSocketStream() = default;
  8749. inline bool SSLSocketStream::is_readable() const {
  8750. return tls::pending(session_) > 0;
  8751. }
  8752. inline bool SSLSocketStream::wait_readable() const {
  8753. if (max_timeout_msec_ <= 0) {
  8754. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8755. }
  8756. time_t read_timeout_sec;
  8757. time_t read_timeout_usec;
  8758. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8759. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8760. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8761. }
  8762. inline bool SSLSocketStream::wait_writable() const {
  8763. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8764. !tls::is_peer_closed(session_, sock_);
  8765. }
  8766. inline bool SSLSocketStream::is_peer_alive() const {
  8767. return !tls::is_peer_closed(session_, sock_);
  8768. }
  8769. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8770. if (tls::pending(session_) > 0) {
  8771. tls::TlsError err;
  8772. auto ret = tls::read(session_, ptr, size, err);
  8773. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8774. error_ = Error::ConnectionClosed;
  8775. }
  8776. return ret;
  8777. } else if (wait_readable()) {
  8778. tls::TlsError err;
  8779. auto ret = tls::read(session_, ptr, size, err);
  8780. if (ret < 0) {
  8781. auto n = 1000;
  8782. #ifdef _WIN32
  8783. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  8784. (err.code == tls::ErrorCode::SyscallError &&
  8785. WSAGetLastError() == WSAETIMEDOUT))) {
  8786. #else
  8787. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  8788. #endif
  8789. if (tls::pending(session_) > 0) {
  8790. return tls::read(session_, ptr, size, err);
  8791. } else if (wait_readable()) {
  8792. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8793. ret = tls::read(session_, ptr, size, err);
  8794. if (ret >= 0) { return ret; }
  8795. } else {
  8796. break;
  8797. }
  8798. }
  8799. assert(ret < 0);
  8800. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8801. error_ = Error::ConnectionClosed;
  8802. }
  8803. return ret;
  8804. } else {
  8805. error_ = Error::Timeout;
  8806. return -1;
  8807. }
  8808. }
  8809. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8810. if (wait_writable()) {
  8811. auto handle_size =
  8812. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  8813. tls::TlsError err;
  8814. auto ret = tls::write(session_, ptr, handle_size, err);
  8815. if (ret < 0) {
  8816. auto n = 1000;
  8817. #ifdef _WIN32
  8818. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  8819. (err.code == tls::ErrorCode::SyscallError &&
  8820. WSAGetLastError() == WSAETIMEDOUT))) {
  8821. #else
  8822. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  8823. #endif
  8824. if (wait_writable()) {
  8825. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8826. ret = tls::write(session_, ptr, handle_size, err);
  8827. if (ret >= 0) { return ret; }
  8828. } else {
  8829. break;
  8830. }
  8831. }
  8832. assert(ret < 0);
  8833. }
  8834. return ret;
  8835. }
  8836. return -1;
  8837. }
  8838. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8839. int &port) const {
  8840. detail::get_remote_ip_and_port(sock_, ip, port);
  8841. }
  8842. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8843. int &port) const {
  8844. detail::get_local_ip_and_port(sock_, ip, port);
  8845. }
  8846. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8847. inline time_t SSLSocketStream::duration() const {
  8848. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8849. std::chrono::steady_clock::now() - start_time_)
  8850. .count();
  8851. }
  8852. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  8853. read_timeout_sec_ = sec;
  8854. read_timeout_usec_ = usec;
  8855. }
  8856. } // namespace detail
  8857. #endif // CPPHTTPLIB_SSL_ENABLED
  8858. /*
  8859. * Group 4: Server implementation
  8860. */
  8861. // HTTP server implementation
  8862. inline Server::Server()
  8863. : new_task_queue([] {
  8864. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  8865. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  8866. }) {
  8867. #ifndef _WIN32
  8868. signal(SIGPIPE, SIG_IGN);
  8869. #endif
  8870. }
  8871. inline Server::~Server() = default;
  8872. inline std::unique_ptr<detail::MatcherBase>
  8873. Server::make_matcher(const std::string &pattern) {
  8874. if (pattern.find("/:") != std::string::npos) {
  8875. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  8876. } else {
  8877. return detail::make_unique<detail::RegexMatcher>(pattern);
  8878. }
  8879. }
  8880. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  8881. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8882. return *this;
  8883. }
  8884. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  8885. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8886. return *this;
  8887. }
  8888. inline Server &Server::Post(const std::string &pattern,
  8889. HandlerWithContentReader handler) {
  8890. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8891. std::move(handler));
  8892. return *this;
  8893. }
  8894. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  8895. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8896. return *this;
  8897. }
  8898. inline Server &Server::Put(const std::string &pattern,
  8899. HandlerWithContentReader handler) {
  8900. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8901. std::move(handler));
  8902. return *this;
  8903. }
  8904. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  8905. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8906. return *this;
  8907. }
  8908. inline Server &Server::Patch(const std::string &pattern,
  8909. HandlerWithContentReader handler) {
  8910. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8911. std::move(handler));
  8912. return *this;
  8913. }
  8914. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  8915. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8916. return *this;
  8917. }
  8918. inline Server &Server::Delete(const std::string &pattern,
  8919. HandlerWithContentReader handler) {
  8920. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8921. std::move(handler));
  8922. return *this;
  8923. }
  8924. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  8925. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8926. return *this;
  8927. }
  8928. inline Server &Server::WebSocket(const std::string &pattern,
  8929. WebSocketHandler handler) {
  8930. websocket_handlers_.push_back(
  8931. {make_matcher(pattern), std::move(handler), nullptr});
  8932. return *this;
  8933. }
  8934. inline Server &Server::WebSocket(const std::string &pattern,
  8935. WebSocketHandler handler,
  8936. SubProtocolSelector sub_protocol_selector) {
  8937. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  8938. std::move(sub_protocol_selector)});
  8939. return *this;
  8940. }
  8941. inline bool Server::set_base_dir(const std::string &dir,
  8942. const std::string &mount_point) {
  8943. return set_mount_point(mount_point, dir);
  8944. }
  8945. inline bool Server::set_mount_point(const std::string &mount_point,
  8946. const std::string &dir, Headers headers) {
  8947. detail::FileStat stat(dir);
  8948. if (stat.is_dir()) {
  8949. std::string mnt = !mount_point.empty() ? mount_point : "/";
  8950. if (!mnt.empty() && mnt[0] == '/') {
  8951. std::string resolved_base;
  8952. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  8953. #if defined(_WIN32)
  8954. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  8955. resolved_base += '\\';
  8956. }
  8957. #else
  8958. if (resolved_base.back() != '/') { resolved_base += '/'; }
  8959. #endif
  8960. }
  8961. base_dirs_.push_back(
  8962. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  8963. return true;
  8964. }
  8965. }
  8966. return false;
  8967. }
  8968. inline bool Server::remove_mount_point(const std::string &mount_point) {
  8969. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  8970. if (it->mount_point == mount_point) {
  8971. base_dirs_.erase(it);
  8972. return true;
  8973. }
  8974. }
  8975. return false;
  8976. }
  8977. inline Server &
  8978. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  8979. const std::string &mime) {
  8980. file_extension_and_mimetype_map_[ext] = mime;
  8981. return *this;
  8982. }
  8983. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  8984. default_file_mimetype_ = mime;
  8985. return *this;
  8986. }
  8987. inline Server &Server::set_file_request_handler(Handler handler) {
  8988. file_request_handler_ = std::move(handler);
  8989. return *this;
  8990. }
  8991. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  8992. std::true_type) {
  8993. error_handler_ = std::move(handler);
  8994. return *this;
  8995. }
  8996. inline Server &Server::set_error_handler_core(Handler handler,
  8997. std::false_type) {
  8998. error_handler_ = [handler](const Request &req, Response &res) {
  8999. handler(req, res);
  9000. return HandlerResponse::Handled;
  9001. };
  9002. return *this;
  9003. }
  9004. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9005. exception_handler_ = std::move(handler);
  9006. return *this;
  9007. }
  9008. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9009. pre_routing_handler_ = std::move(handler);
  9010. return *this;
  9011. }
  9012. inline Server &Server::set_post_routing_handler(Handler handler) {
  9013. post_routing_handler_ = std::move(handler);
  9014. return *this;
  9015. }
  9016. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9017. pre_request_handler_ = std::move(handler);
  9018. return *this;
  9019. }
  9020. inline Server &Server::set_logger(Logger logger) {
  9021. logger_ = std::move(logger);
  9022. return *this;
  9023. }
  9024. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9025. error_logger_ = std::move(error_logger);
  9026. return *this;
  9027. }
  9028. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9029. pre_compression_logger_ = std::move(logger);
  9030. return *this;
  9031. }
  9032. inline Server &
  9033. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9034. expect_100_continue_handler_ = std::move(handler);
  9035. return *this;
  9036. }
  9037. inline Server &Server::set_address_family(int family) {
  9038. address_family_ = family;
  9039. return *this;
  9040. }
  9041. inline Server &Server::set_tcp_nodelay(bool on) {
  9042. tcp_nodelay_ = on;
  9043. return *this;
  9044. }
  9045. inline Server &Server::set_ipv6_v6only(bool on) {
  9046. ipv6_v6only_ = on;
  9047. return *this;
  9048. }
  9049. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9050. socket_options_ = std::move(socket_options);
  9051. return *this;
  9052. }
  9053. inline Server &Server::set_default_headers(Headers headers) {
  9054. default_headers_ = std::move(headers);
  9055. return *this;
  9056. }
  9057. inline Server &Server::set_header_writer(
  9058. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9059. header_writer_ = writer;
  9060. return *this;
  9061. }
  9062. inline Server &
  9063. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9064. trusted_proxies_ = proxies;
  9065. return *this;
  9066. }
  9067. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9068. keep_alive_max_count_ = count;
  9069. return *this;
  9070. }
  9071. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9072. keep_alive_timeout_sec_ = sec;
  9073. return *this;
  9074. }
  9075. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9076. read_timeout_sec_ = sec;
  9077. read_timeout_usec_ = usec;
  9078. return *this;
  9079. }
  9080. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9081. write_timeout_sec_ = sec;
  9082. write_timeout_usec_ = usec;
  9083. return *this;
  9084. }
  9085. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9086. idle_interval_sec_ = sec;
  9087. idle_interval_usec_ = usec;
  9088. return *this;
  9089. }
  9090. inline Server &Server::set_payload_max_length(size_t length) {
  9091. payload_max_length_ = length;
  9092. return *this;
  9093. }
  9094. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9095. websocket_ping_interval_sec_ = sec;
  9096. return *this;
  9097. }
  9098. template <class Rep, class Period>
  9099. inline Server &Server::set_websocket_ping_interval(
  9100. const std::chrono::duration<Rep, Period> &duration) {
  9101. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9102. set_websocket_ping_interval(sec);
  9103. });
  9104. return *this;
  9105. }
  9106. inline bool Server::bind_to_port(const std::string &host, int port,
  9107. int socket_flags) {
  9108. auto ret = bind_internal(host, port, socket_flags);
  9109. if (ret == -1) { is_decommissioned = true; }
  9110. return ret >= 0;
  9111. }
  9112. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9113. auto ret = bind_internal(host, 0, socket_flags);
  9114. if (ret == -1) { is_decommissioned = true; }
  9115. return ret;
  9116. }
  9117. inline bool Server::listen_after_bind() { return listen_internal(); }
  9118. inline bool Server::listen(const std::string &host, int port,
  9119. int socket_flags) {
  9120. return bind_to_port(host, port, socket_flags) && listen_internal();
  9121. }
  9122. inline bool Server::is_running() const { return is_running_; }
  9123. inline void Server::wait_until_ready() const {
  9124. while (!is_running_ && !is_decommissioned) {
  9125. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9126. }
  9127. }
  9128. inline void Server::stop() {
  9129. if (is_running_) {
  9130. assert(svr_sock_ != INVALID_SOCKET);
  9131. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9132. detail::shutdown_socket(sock);
  9133. detail::close_socket(sock);
  9134. }
  9135. is_decommissioned = false;
  9136. }
  9137. inline void Server::decommission() { is_decommissioned = true; }
  9138. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9139. auto len = strlen(s);
  9140. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9141. len -= 2;
  9142. {
  9143. size_t count = 0;
  9144. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9145. switch (count) {
  9146. case 0: req.method = std::string(b, e); break;
  9147. case 1: req.target = std::string(b, e); break;
  9148. case 2: req.version = std::string(b, e); break;
  9149. default: break;
  9150. }
  9151. count++;
  9152. });
  9153. if (count != 3) { return false; }
  9154. }
  9155. thread_local const std::set<std::string> methods{
  9156. "GET", "HEAD", "POST", "PUT", "DELETE",
  9157. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9158. if (methods.find(req.method) == methods.end()) {
  9159. output_error_log(Error::InvalidHTTPMethod, &req);
  9160. return false;
  9161. }
  9162. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9163. output_error_log(Error::InvalidHTTPVersion, &req);
  9164. return false;
  9165. }
  9166. {
  9167. // Skip URL fragment
  9168. for (size_t i = 0; i < req.target.size(); i++) {
  9169. if (req.target[i] == '#') {
  9170. req.target.erase(i);
  9171. break;
  9172. }
  9173. }
  9174. detail::divide(req.target, '?',
  9175. [&](const char *lhs_data, std::size_t lhs_size,
  9176. const char *rhs_data, std::size_t rhs_size) {
  9177. req.path =
  9178. decode_path_component(std::string(lhs_data, lhs_size));
  9179. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9180. });
  9181. }
  9182. return true;
  9183. }
  9184. inline bool Server::write_response(Stream &strm, bool close_connection,
  9185. Request &req, Response &res) {
  9186. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9187. // incorrectly to the error content.
  9188. req.ranges.clear();
  9189. return write_response_core(strm, close_connection, req, res, false);
  9190. }
  9191. inline bool Server::write_response_with_content(Stream &strm,
  9192. bool close_connection,
  9193. const Request &req,
  9194. Response &res) {
  9195. return write_response_core(strm, close_connection, req, res, true);
  9196. }
  9197. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9198. const Request &req, Response &res,
  9199. bool need_apply_ranges) {
  9200. assert(res.status != -1);
  9201. if (400 <= res.status && error_handler_ &&
  9202. error_handler_(req, res) == HandlerResponse::Handled) {
  9203. need_apply_ranges = true;
  9204. }
  9205. std::string content_type;
  9206. std::string boundary;
  9207. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9208. // Prepare additional headers
  9209. if (close_connection || req.get_header_value("Connection") == "close" ||
  9210. 400 <= res.status) { // Don't leave connections open after errors
  9211. res.set_header("Connection", "close");
  9212. } else {
  9213. std::string s = "timeout=";
  9214. s += std::to_string(keep_alive_timeout_sec_);
  9215. s += ", max=";
  9216. s += std::to_string(keep_alive_max_count_);
  9217. res.set_header("Keep-Alive", s);
  9218. }
  9219. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9220. !res.has_header("Content-Type")) {
  9221. res.set_header("Content-Type", "text/plain");
  9222. }
  9223. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9224. !res.has_header("Content-Length")) {
  9225. res.set_header("Content-Length", "0");
  9226. }
  9227. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9228. res.set_header("Accept-Ranges", "bytes");
  9229. }
  9230. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9231. // Response line and headers
  9232. detail::BufferStream bstrm;
  9233. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9234. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9235. // Combine small body with headers to reduce write syscalls
  9236. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9237. bstrm.write(res.body.data(), res.body.size());
  9238. }
  9239. // Log before writing to avoid race condition with client-side code that
  9240. // accesses logger-captured data immediately after receiving the response.
  9241. output_log(req, res);
  9242. // Flush buffer
  9243. auto &data = bstrm.get_buffer();
  9244. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9245. // Streaming body
  9246. auto ret = true;
  9247. if (req.method != "HEAD" && res.content_provider_) {
  9248. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9249. res.content_provider_success_ = true;
  9250. } else {
  9251. ret = false;
  9252. }
  9253. }
  9254. return ret;
  9255. }
  9256. inline bool
  9257. Server::write_content_with_provider(Stream &strm, const Request &req,
  9258. Response &res, const std::string &boundary,
  9259. const std::string &content_type) {
  9260. auto is_shutting_down = [this]() {
  9261. return this->svr_sock_ == INVALID_SOCKET;
  9262. };
  9263. if (res.content_length_ > 0) {
  9264. if (req.ranges.empty()) {
  9265. return detail::write_content(strm, res.content_provider_, 0,
  9266. res.content_length_, is_shutting_down);
  9267. } else if (req.ranges.size() == 1) {
  9268. auto offset_and_length = detail::get_range_offset_and_length(
  9269. req.ranges[0], res.content_length_);
  9270. return detail::write_content(strm, res.content_provider_,
  9271. offset_and_length.first,
  9272. offset_and_length.second, is_shutting_down);
  9273. } else {
  9274. return detail::write_multipart_ranges_data(
  9275. strm, req, res, boundary, content_type, res.content_length_,
  9276. is_shutting_down);
  9277. }
  9278. } else {
  9279. if (res.is_chunked_content_provider_) {
  9280. auto type = detail::encoding_type(req, res);
  9281. std::unique_ptr<detail::compressor> compressor;
  9282. if (type == detail::EncodingType::Gzip) {
  9283. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9284. compressor = detail::make_unique<detail::gzip_compressor>();
  9285. #endif
  9286. } else if (type == detail::EncodingType::Brotli) {
  9287. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9288. compressor = detail::make_unique<detail::brotli_compressor>();
  9289. #endif
  9290. } else if (type == detail::EncodingType::Zstd) {
  9291. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9292. compressor = detail::make_unique<detail::zstd_compressor>();
  9293. #endif
  9294. } else {
  9295. compressor = detail::make_unique<detail::nocompressor>();
  9296. }
  9297. assert(compressor != nullptr);
  9298. return detail::write_content_chunked(strm, res.content_provider_,
  9299. is_shutting_down, *compressor);
  9300. } else {
  9301. return detail::write_content_without_length(strm, res.content_provider_,
  9302. is_shutting_down);
  9303. }
  9304. }
  9305. }
  9306. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9307. FormFields::iterator cur_field;
  9308. FormFiles::iterator cur_file;
  9309. auto is_text_field = false;
  9310. size_t count = 0;
  9311. if (read_content_core(
  9312. strm, req, res,
  9313. // Regular
  9314. [&](const char *buf, size_t n) {
  9315. // Prevent arithmetic overflow when checking sizes.
  9316. // Avoid computing (req.body.size() + n) directly because
  9317. // adding two unsigned `size_t` values can wrap around and
  9318. // produce a small result instead of indicating overflow.
  9319. // Instead, check using subtraction: ensure `n` does not
  9320. // exceed the remaining capacity `max_size() - size()`.
  9321. if (req.body.size() >= req.body.max_size() ||
  9322. n > req.body.max_size() - req.body.size()) {
  9323. return false;
  9324. }
  9325. // Limit decompressed body size to payload_max_length_ to protect
  9326. // against "zip bomb" attacks where a small compressed payload
  9327. // decompresses to a massive size.
  9328. if (payload_max_length_ > 0 &&
  9329. (req.body.size() >= payload_max_length_ ||
  9330. n > payload_max_length_ - req.body.size())) {
  9331. return false;
  9332. }
  9333. req.body.append(buf, n);
  9334. return true;
  9335. },
  9336. // Multipart FormData
  9337. [&](const FormData &file) {
  9338. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9339. output_error_log(Error::TooManyFormDataFiles, &req);
  9340. return false;
  9341. }
  9342. if (file.filename.empty()) {
  9343. cur_field = req.form.fields.emplace(
  9344. file.name, FormField{file.name, file.content, file.headers});
  9345. is_text_field = true;
  9346. } else {
  9347. cur_file = req.form.files.emplace(file.name, file);
  9348. is_text_field = false;
  9349. }
  9350. return true;
  9351. },
  9352. [&](const char *buf, size_t n) {
  9353. if (is_text_field) {
  9354. auto &content = cur_field->second.content;
  9355. if (content.size() + n > content.max_size()) { return false; }
  9356. content.append(buf, n);
  9357. } else {
  9358. auto &content = cur_file->second.content;
  9359. if (content.size() + n > content.max_size()) { return false; }
  9360. content.append(buf, n);
  9361. }
  9362. return true;
  9363. })) {
  9364. const auto &content_type = req.get_header_value("Content-Type");
  9365. if (detail::extract_media_type(content_type) ==
  9366. "application/x-www-form-urlencoded") {
  9367. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9368. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9369. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9370. return false;
  9371. }
  9372. detail::parse_query_text(req.body, req.params);
  9373. }
  9374. return true;
  9375. }
  9376. return false;
  9377. }
  9378. inline bool Server::read_content_with_content_receiver(
  9379. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9380. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9381. return read_content_core(strm, req, res, std::move(receiver),
  9382. std::move(multipart_header),
  9383. std::move(multipart_receiver));
  9384. }
  9385. inline bool Server::read_content_core(
  9386. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9387. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9388. detail::FormDataParser multipart_form_data_parser;
  9389. ContentReceiverWithProgress out;
  9390. if (req.is_multipart_form_data()) {
  9391. const auto &content_type = req.get_header_value("Content-Type");
  9392. std::string boundary;
  9393. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9394. res.status = StatusCode::BadRequest_400;
  9395. output_error_log(Error::MultipartParsing, &req);
  9396. return false;
  9397. }
  9398. multipart_form_data_parser.set_boundary(std::move(boundary));
  9399. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9400. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9401. multipart_receiver);
  9402. };
  9403. } else {
  9404. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9405. size_t /*len*/) { return receiver(buf, n); };
  9406. }
  9407. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  9408. // are true (no Transfer-Encoding and no Content-Length), then the message
  9409. // body length is zero (no message body is present).
  9410. //
  9411. // For non-SSL builds, detect clients that send a body without a
  9412. // Content-Length header (raw HTTP over TCP). Check both the stream's
  9413. // internal read buffer (data already read from the socket during header
  9414. // parsing) and the socket itself for pending data. If data is found and
  9415. // exceeds the configured payload limit, reject with 413.
  9416. // For SSL builds we cannot reliably peek the decrypted application bytes,
  9417. // so keep the original behaviour.
  9418. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9419. if (!req.has_header("Content-Length") &&
  9420. !detail::is_chunked_transfer_encoding(req.headers)) {
  9421. // Only check if payload_max_length is set to a finite value
  9422. if (payload_max_length_ > 0 &&
  9423. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9424. // Check if there is data already buffered in the stream (read during
  9425. // header parsing) or pending on the socket. Use a non-blocking socket
  9426. // check to avoid deadlock when the client sends no body.
  9427. bool has_data = strm.is_readable();
  9428. if (!has_data) {
  9429. socket_t s = strm.socket();
  9430. if (s != INVALID_SOCKET) {
  9431. has_data = detail::select_read(s, 0, 0) > 0;
  9432. }
  9433. }
  9434. if (has_data) {
  9435. auto result =
  9436. detail::read_content_without_length(strm, payload_max_length_, out);
  9437. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9438. res.status = StatusCode::PayloadTooLarge_413;
  9439. return false;
  9440. } else if (result != detail::ReadContentResult::Success) {
  9441. return false;
  9442. }
  9443. return true;
  9444. }
  9445. }
  9446. return true;
  9447. }
  9448. #else
  9449. if (!req.has_header("Content-Length") &&
  9450. !detail::is_chunked_transfer_encoding(req.headers)) {
  9451. return true;
  9452. }
  9453. #endif
  9454. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9455. out, true)) {
  9456. return false;
  9457. }
  9458. if (req.is_multipart_form_data()) {
  9459. if (!multipart_form_data_parser.is_valid()) {
  9460. res.status = StatusCode::BadRequest_400;
  9461. output_error_log(Error::MultipartParsing, &req);
  9462. return false;
  9463. }
  9464. }
  9465. return true;
  9466. }
  9467. inline bool Server::handle_file_request(Request &req, Response &res) {
  9468. for (const auto &entry : base_dirs_) {
  9469. // Prefix match
  9470. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9471. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9472. if (detail::is_valid_path(sub_path)) {
  9473. auto path = entry.base_dir + sub_path;
  9474. if (path.back() == '/') { path += "index.html"; }
  9475. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9476. // but symlinks/junctions can still escape the base directory.
  9477. if (!entry.resolved_base_dir.empty()) {
  9478. std::string resolved_path;
  9479. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9480. !detail::is_path_within_base(resolved_path,
  9481. entry.resolved_base_dir)) {
  9482. res.status = StatusCode::Forbidden_403;
  9483. return true;
  9484. }
  9485. }
  9486. detail::FileStat stat(path);
  9487. if (stat.is_dir()) {
  9488. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9489. return true;
  9490. }
  9491. if (stat.is_file()) {
  9492. for (const auto &kv : entry.headers) {
  9493. res.set_header(kv.first, kv.second);
  9494. }
  9495. auto etag = detail::compute_etag(stat);
  9496. if (!etag.empty()) { res.set_header("ETag", etag); }
  9497. auto mtime = stat.mtime();
  9498. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9499. if (!last_modified.empty()) {
  9500. res.set_header("Last-Modified", last_modified);
  9501. }
  9502. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9503. check_if_range(req, etag, mtime);
  9504. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9505. if (!mm->is_open()) {
  9506. output_error_log(Error::OpenFile, &req);
  9507. return false;
  9508. }
  9509. res.set_content_provider(
  9510. mm->size(),
  9511. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9512. default_file_mimetype_),
  9513. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9514. sink.write(mm->data() + offset, length);
  9515. return true;
  9516. });
  9517. if (req.method != "HEAD" && file_request_handler_) {
  9518. file_request_handler_(req, res);
  9519. }
  9520. return true;
  9521. } else {
  9522. output_error_log(Error::OpenFile, &req);
  9523. }
  9524. }
  9525. }
  9526. }
  9527. return false;
  9528. }
  9529. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9530. const std::string &etag,
  9531. time_t mtime) const {
  9532. // Handle conditional GET:
  9533. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9534. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9535. if (req.has_header("If-None-Match")) {
  9536. if (!etag.empty()) {
  9537. auto val = req.get_header_value("If-None-Match");
  9538. // NOTE: We use exact string matching here. This works correctly
  9539. // because our server always generates weak ETags (W/"..."), and
  9540. // clients typically send back the same ETag they received.
  9541. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9542. // If-None-Match, where W/"x" and "x" would match, but this
  9543. // simplified implementation requires exact matches.
  9544. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9545. [&](const char *b, const char *e) {
  9546. auto seg_len = static_cast<size_t>(e - b);
  9547. return (seg_len == 1 && *b == '*') ||
  9548. (seg_len == etag.size() &&
  9549. std::equal(b, e, etag.begin()));
  9550. });
  9551. if (ret) {
  9552. res.status = StatusCode::NotModified_304;
  9553. return true;
  9554. }
  9555. }
  9556. } else if (req.has_header("If-Modified-Since")) {
  9557. auto val = req.get_header_value("If-Modified-Since");
  9558. auto t = detail::parse_http_date(val);
  9559. if (t != static_cast<time_t>(-1) && mtime <= t) {
  9560. res.status = StatusCode::NotModified_304;
  9561. return true;
  9562. }
  9563. }
  9564. return false;
  9565. }
  9566. inline bool Server::check_if_range(Request &req, const std::string &etag,
  9567. time_t mtime) const {
  9568. // Handle If-Range for partial content requests (RFC 9110
  9569. // Section 13.1.5). If-Range is only evaluated when Range header is
  9570. // present. If the validator matches, serve partial content; otherwise
  9571. // serve full content.
  9572. if (!req.ranges.empty() && req.has_header("If-Range")) {
  9573. auto val = req.get_header_value("If-Range");
  9574. auto is_valid_range = [&]() {
  9575. if (detail::is_strong_etag(val)) {
  9576. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  9577. // comparison.
  9578. return (!etag.empty() && val == etag);
  9579. } else if (detail::is_weak_etag(val)) {
  9580. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  9581. return false;
  9582. } else {
  9583. // HTTP-date comparison
  9584. auto t = detail::parse_http_date(val);
  9585. return (t != static_cast<time_t>(-1) && mtime <= t);
  9586. }
  9587. };
  9588. if (!is_valid_range()) {
  9589. // Validator doesn't match: ignore Range and serve full content
  9590. req.ranges.clear();
  9591. return false;
  9592. }
  9593. }
  9594. return true;
  9595. }
  9596. inline socket_t
  9597. Server::create_server_socket(const std::string &host, int port,
  9598. int socket_flags,
  9599. SocketOptions socket_options) const {
  9600. return detail::create_socket(
  9601. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  9602. ipv6_v6only_, std::move(socket_options),
  9603. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  9604. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  9605. output_error_log(Error::BindIPAddress, nullptr);
  9606. return false;
  9607. }
  9608. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  9609. output_error_log(Error::Listen, nullptr);
  9610. return false;
  9611. }
  9612. return true;
  9613. });
  9614. }
  9615. inline int Server::bind_internal(const std::string &host, int port,
  9616. int socket_flags) {
  9617. if (is_decommissioned) { return -1; }
  9618. if (!is_valid()) { return -1; }
  9619. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  9620. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  9621. if (port == 0) {
  9622. struct sockaddr_storage addr;
  9623. socklen_t addr_len = sizeof(addr);
  9624. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  9625. &addr_len) == -1) {
  9626. output_error_log(Error::GetSockName, nullptr);
  9627. return -1;
  9628. }
  9629. if (addr.ss_family == AF_INET) {
  9630. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  9631. } else if (addr.ss_family == AF_INET6) {
  9632. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  9633. } else {
  9634. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  9635. return -1;
  9636. }
  9637. } else {
  9638. return port;
  9639. }
  9640. }
  9641. inline bool Server::listen_internal() {
  9642. if (is_decommissioned) { return false; }
  9643. auto ret = true;
  9644. is_running_ = true;
  9645. auto se = detail::scope_exit([&]() { is_running_ = false; });
  9646. {
  9647. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  9648. while (svr_sock_ != INVALID_SOCKET) {
  9649. #ifndef _WIN32
  9650. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  9651. #endif
  9652. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  9653. idle_interval_usec_);
  9654. if (val == 0) { // Timeout
  9655. task_queue->on_idle();
  9656. continue;
  9657. }
  9658. #ifndef _WIN32
  9659. }
  9660. #endif
  9661. #if defined _WIN32
  9662. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  9663. // OVERLAPPED
  9664. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  9665. #elif defined SOCK_CLOEXEC
  9666. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  9667. #else
  9668. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  9669. #endif
  9670. if (sock == INVALID_SOCKET) {
  9671. if (errno == EMFILE) {
  9672. // The per-process limit of open file descriptors has been reached.
  9673. // Try to accept new connections after a short sleep.
  9674. std::this_thread::sleep_for(std::chrono::microseconds{1});
  9675. continue;
  9676. } else if (errno == EINTR || errno == EAGAIN) {
  9677. continue;
  9678. }
  9679. if (svr_sock_ != INVALID_SOCKET) {
  9680. detail::close_socket(svr_sock_);
  9681. ret = false;
  9682. output_error_log(Error::Connection, nullptr);
  9683. } else {
  9684. ; // The server socket was closed by user.
  9685. }
  9686. break;
  9687. }
  9688. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  9689. read_timeout_sec_, read_timeout_usec_);
  9690. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  9691. write_timeout_sec_, write_timeout_usec_);
  9692. if (tcp_nodelay_) {
  9693. detail::set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
  9694. }
  9695. if (!task_queue->enqueue(
  9696. [this, sock]() { process_and_close_socket(sock); })) {
  9697. output_error_log(Error::ResourceExhaustion, nullptr);
  9698. detail::shutdown_socket(sock);
  9699. detail::close_socket(sock);
  9700. }
  9701. }
  9702. task_queue->shutdown();
  9703. }
  9704. is_decommissioned = !ret;
  9705. return ret;
  9706. }
  9707. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  9708. if (pre_routing_handler_ &&
  9709. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  9710. return true;
  9711. }
  9712. // File handler
  9713. if ((req.method == "GET" || req.method == "HEAD") &&
  9714. handle_file_request(req, res)) {
  9715. return true;
  9716. }
  9717. if (detail::expect_content(req)) {
  9718. // Content reader handler
  9719. {
  9720. // Track whether the ContentReader was aborted due to the decompressed
  9721. // payload exceeding `payload_max_length_`.
  9722. // The user handler runs after the lambda returns, so we must restore the
  9723. // 413 status if the handler overwrites it.
  9724. bool content_reader_payload_too_large = false;
  9725. ContentReader reader(
  9726. [&](ContentReceiver receiver) {
  9727. auto result = read_content_with_content_receiver(
  9728. strm, req, res, std::move(receiver), nullptr, nullptr);
  9729. if (!result) {
  9730. output_error_log(Error::Read, &req);
  9731. if (res.status == StatusCode::PayloadTooLarge_413) {
  9732. content_reader_payload_too_large = true;
  9733. }
  9734. }
  9735. return result;
  9736. },
  9737. [&](FormDataHeader header, ContentReceiver receiver) {
  9738. auto result = read_content_with_content_receiver(
  9739. strm, req, res, nullptr, std::move(header),
  9740. std::move(receiver));
  9741. if (!result) {
  9742. output_error_log(Error::Read, &req);
  9743. if (res.status == StatusCode::PayloadTooLarge_413) {
  9744. content_reader_payload_too_large = true;
  9745. }
  9746. }
  9747. return result;
  9748. });
  9749. bool dispatched = false;
  9750. if (req.method == "POST") {
  9751. dispatched = dispatch_request_for_content_reader(
  9752. req, res, std::move(reader), post_handlers_for_content_reader_);
  9753. } else if (req.method == "PUT") {
  9754. dispatched = dispatch_request_for_content_reader(
  9755. req, res, std::move(reader), put_handlers_for_content_reader_);
  9756. } else if (req.method == "PATCH") {
  9757. dispatched = dispatch_request_for_content_reader(
  9758. req, res, std::move(reader), patch_handlers_for_content_reader_);
  9759. } else if (req.method == "DELETE") {
  9760. dispatched = dispatch_request_for_content_reader(
  9761. req, res, std::move(reader), delete_handlers_for_content_reader_);
  9762. }
  9763. if (dispatched) {
  9764. if (content_reader_payload_too_large) {
  9765. // Enforce the limit: override any status the handler may have set
  9766. // and return false so the error path sends a plain 413 response.
  9767. res.status = StatusCode::PayloadTooLarge_413;
  9768. res.body.clear();
  9769. res.content_length_ = 0;
  9770. res.content_provider_ = nullptr;
  9771. return false;
  9772. }
  9773. return true;
  9774. }
  9775. }
  9776. // Read content into `req.body`
  9777. if (!read_content(strm, req, res)) {
  9778. output_error_log(Error::Read, &req);
  9779. return false;
  9780. }
  9781. }
  9782. // Regular handler
  9783. if (req.method == "GET" || req.method == "HEAD") {
  9784. return dispatch_request(req, res, get_handlers_);
  9785. } else if (req.method == "POST") {
  9786. return dispatch_request(req, res, post_handlers_);
  9787. } else if (req.method == "PUT") {
  9788. return dispatch_request(req, res, put_handlers_);
  9789. } else if (req.method == "DELETE") {
  9790. return dispatch_request(req, res, delete_handlers_);
  9791. } else if (req.method == "OPTIONS") {
  9792. return dispatch_request(req, res, options_handlers_);
  9793. } else if (req.method == "PATCH") {
  9794. return dispatch_request(req, res, patch_handlers_);
  9795. }
  9796. res.status = StatusCode::BadRequest_400;
  9797. return false;
  9798. }
  9799. inline bool Server::dispatch_request(Request &req, Response &res,
  9800. const Handlers &handlers) const {
  9801. for (const auto &x : handlers) {
  9802. const auto &matcher = x.first;
  9803. const auto &handler = x.second;
  9804. if (matcher->match(req)) {
  9805. req.matched_route = matcher->pattern();
  9806. if (!pre_request_handler_ ||
  9807. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9808. handler(req, res);
  9809. }
  9810. return true;
  9811. }
  9812. }
  9813. return false;
  9814. }
  9815. inline void Server::apply_ranges(const Request &req, Response &res,
  9816. std::string &content_type,
  9817. std::string &boundary) const {
  9818. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  9819. auto it = res.headers.find("Content-Type");
  9820. if (it != res.headers.end()) {
  9821. content_type = it->second;
  9822. res.headers.erase(it);
  9823. }
  9824. boundary = detail::make_multipart_data_boundary();
  9825. res.set_header("Content-Type",
  9826. "multipart/byteranges; boundary=" + boundary);
  9827. }
  9828. auto type = detail::encoding_type(req, res);
  9829. if (res.body.empty()) {
  9830. if (res.content_length_ > 0) {
  9831. size_t length = 0;
  9832. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9833. length = res.content_length_;
  9834. } else if (req.ranges.size() == 1) {
  9835. auto offset_and_length = detail::get_range_offset_and_length(
  9836. req.ranges[0], res.content_length_);
  9837. length = offset_and_length.second;
  9838. auto content_range = detail::make_content_range_header_field(
  9839. offset_and_length, res.content_length_);
  9840. res.set_header("Content-Range", content_range);
  9841. } else {
  9842. length = detail::get_multipart_ranges_data_length(
  9843. req, boundary, content_type, res.content_length_);
  9844. }
  9845. res.set_header("Content-Length", std::to_string(length));
  9846. } else {
  9847. if (res.content_provider_) {
  9848. if (res.is_chunked_content_provider_) {
  9849. res.set_header("Transfer-Encoding", "chunked");
  9850. if (type == detail::EncodingType::Gzip) {
  9851. res.set_header("Content-Encoding", "gzip");
  9852. res.set_header("Vary", "Accept-Encoding");
  9853. } else if (type == detail::EncodingType::Brotli) {
  9854. res.set_header("Content-Encoding", "br");
  9855. res.set_header("Vary", "Accept-Encoding");
  9856. } else if (type == detail::EncodingType::Zstd) {
  9857. res.set_header("Content-Encoding", "zstd");
  9858. res.set_header("Vary", "Accept-Encoding");
  9859. }
  9860. }
  9861. }
  9862. }
  9863. } else {
  9864. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9865. ;
  9866. } else if (req.ranges.size() == 1) {
  9867. auto offset_and_length =
  9868. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  9869. auto offset = offset_and_length.first;
  9870. auto length = offset_and_length.second;
  9871. auto content_range = detail::make_content_range_header_field(
  9872. offset_and_length, res.body.size());
  9873. res.set_header("Content-Range", content_range);
  9874. assert(offset + length <= res.body.size());
  9875. res.body = res.body.substr(offset, length);
  9876. } else {
  9877. std::string data;
  9878. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  9879. res.body.size(), data);
  9880. res.body.swap(data);
  9881. }
  9882. if (type != detail::EncodingType::None) {
  9883. output_pre_compression_log(req, res);
  9884. std::unique_ptr<detail::compressor> compressor;
  9885. std::string content_encoding;
  9886. if (type == detail::EncodingType::Gzip) {
  9887. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9888. compressor = detail::make_unique<detail::gzip_compressor>();
  9889. content_encoding = "gzip";
  9890. #endif
  9891. } else if (type == detail::EncodingType::Brotli) {
  9892. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9893. compressor = detail::make_unique<detail::brotli_compressor>();
  9894. content_encoding = "br";
  9895. #endif
  9896. } else if (type == detail::EncodingType::Zstd) {
  9897. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9898. compressor = detail::make_unique<detail::zstd_compressor>();
  9899. content_encoding = "zstd";
  9900. #endif
  9901. }
  9902. if (compressor) {
  9903. std::string compressed;
  9904. if (compressor->compress(res.body.data(), res.body.size(), true,
  9905. [&](const char *data, size_t data_len) {
  9906. compressed.append(data, data_len);
  9907. return true;
  9908. })) {
  9909. res.body.swap(compressed);
  9910. res.set_header("Content-Encoding", content_encoding);
  9911. res.set_header("Vary", "Accept-Encoding");
  9912. }
  9913. }
  9914. }
  9915. auto length = std::to_string(res.body.size());
  9916. res.set_header("Content-Length", length);
  9917. }
  9918. }
  9919. inline bool Server::dispatch_request_for_content_reader(
  9920. Request &req, Response &res, ContentReader content_reader,
  9921. const HandlersForContentReader &handlers) const {
  9922. for (const auto &x : handlers) {
  9923. const auto &matcher = x.first;
  9924. const auto &handler = x.second;
  9925. if (matcher->match(req)) {
  9926. req.matched_route = matcher->pattern();
  9927. if (!pre_request_handler_ ||
  9928. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9929. handler(req, res, content_reader);
  9930. }
  9931. return true;
  9932. }
  9933. }
  9934. return false;
  9935. }
  9936. inline std::string
  9937. get_client_ip(const std::string &x_forwarded_for,
  9938. const std::vector<std::string> &trusted_proxies) {
  9939. // X-Forwarded-For is a comma-separated list per RFC 7239
  9940. std::vector<std::string> ip_list;
  9941. detail::split(x_forwarded_for.data(),
  9942. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  9943. [&](const char *b, const char *e) {
  9944. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  9945. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  9946. });
  9947. for (size_t i = 0; i < ip_list.size(); ++i) {
  9948. auto ip = ip_list[i];
  9949. auto is_trusted_proxy =
  9950. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  9951. [&](const std::string &proxy) { return ip == proxy; });
  9952. if (is_trusted_proxy) {
  9953. if (i == 0) {
  9954. // If the trusted proxy is the first IP, there's no preceding client IP
  9955. return ip;
  9956. } else {
  9957. // Return the IP immediately before the trusted proxy
  9958. return ip_list[i - 1];
  9959. }
  9960. }
  9961. }
  9962. // If no trusted proxy is found, return the first IP in the list
  9963. return ip_list.front();
  9964. }
  9965. inline bool
  9966. Server::process_request(Stream &strm, const std::string &remote_addr,
  9967. int remote_port, const std::string &local_addr,
  9968. int local_port, bool close_connection,
  9969. bool &connection_closed,
  9970. const std::function<void(Request &)> &setup_request,
  9971. bool *websocket_upgraded) {
  9972. std::array<char, 2048> buf{};
  9973. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  9974. // Connection has been closed on client
  9975. if (!line_reader.getline()) { return false; }
  9976. Request req;
  9977. req.start_time_ = std::chrono::steady_clock::now();
  9978. req.remote_addr = remote_addr;
  9979. req.remote_port = remote_port;
  9980. req.local_addr = local_addr;
  9981. req.local_port = local_port;
  9982. Response res;
  9983. res.version = "HTTP/1.1";
  9984. res.headers = default_headers_;
  9985. // Request line and headers
  9986. if (!parse_request_line(line_reader.ptr(), req)) {
  9987. res.status = StatusCode::BadRequest_400;
  9988. output_error_log(Error::InvalidRequestLine, &req);
  9989. return write_response(strm, close_connection, req, res);
  9990. }
  9991. // Request headers
  9992. if (!detail::read_headers(strm, req.headers)) {
  9993. res.status = StatusCode::BadRequest_400;
  9994. output_error_log(Error::InvalidHeaders, &req);
  9995. return write_response(strm, close_connection, req, res);
  9996. }
  9997. // Check if the request URI doesn't exceed the limit
  9998. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9999. res.status = StatusCode::UriTooLong_414;
  10000. output_error_log(Error::ExceedUriMaxLength, &req);
  10001. return write_response(strm, close_connection, req, res);
  10002. }
  10003. if (req.get_header_value("Connection") == "close") {
  10004. connection_closed = true;
  10005. }
  10006. if (req.version == "HTTP/1.0" &&
  10007. req.get_header_value("Connection") != "Keep-Alive") {
  10008. connection_closed = true;
  10009. }
  10010. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10011. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10012. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  10013. } else {
  10014. req.remote_addr = remote_addr;
  10015. }
  10016. req.remote_port = remote_port;
  10017. req.local_addr = local_addr;
  10018. req.local_port = local_port;
  10019. if (req.has_header("Accept")) {
  10020. const auto &accept_header = req.get_header_value("Accept");
  10021. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10022. res.status = StatusCode::BadRequest_400;
  10023. output_error_log(Error::HTTPParsing, &req);
  10024. return write_response(strm, close_connection, req, res);
  10025. }
  10026. }
  10027. if (req.has_header("Range")) {
  10028. const auto &range_header_value = req.get_header_value("Range");
  10029. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10030. res.status = StatusCode::RangeNotSatisfiable_416;
  10031. output_error_log(Error::InvalidRangeHeader, &req);
  10032. return write_response(strm, close_connection, req, res);
  10033. }
  10034. }
  10035. if (setup_request) { setup_request(req); }
  10036. if (req.get_header_value("Expect") == "100-continue") {
  10037. int status = StatusCode::Continue_100;
  10038. if (expect_100_continue_handler_) {
  10039. status = expect_100_continue_handler_(req, res);
  10040. }
  10041. switch (status) {
  10042. case StatusCode::Continue_100:
  10043. case StatusCode::ExpectationFailed_417:
  10044. detail::write_response_line(strm, status);
  10045. strm.write("\r\n");
  10046. break;
  10047. default:
  10048. connection_closed = true;
  10049. return write_response(strm, true, req, res);
  10050. }
  10051. }
  10052. // Setup `is_connection_closed` method
  10053. auto sock = strm.socket();
  10054. req.is_connection_closed = [sock]() {
  10055. return !detail::is_socket_alive(sock);
  10056. };
  10057. // WebSocket upgrade
  10058. // Check pre_routing_handler_ before upgrading so that authentication
  10059. // and other middleware can reject the request with an HTTP response
  10060. // (e.g., 401) before the protocol switches.
  10061. if (detail::is_websocket_upgrade(req)) {
  10062. if (pre_routing_handler_ &&
  10063. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10064. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10065. return write_response(strm, close_connection, req, res);
  10066. }
  10067. // Find matching WebSocket handler
  10068. for (const auto &entry : websocket_handlers_) {
  10069. if (entry.matcher->match(req)) {
  10070. // Compute accept key
  10071. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10072. auto accept_key = detail::websocket_accept_key(client_key);
  10073. // Negotiate subprotocol
  10074. std::string selected_subprotocol;
  10075. if (entry.sub_protocol_selector) {
  10076. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10077. if (!protocol_header.empty()) {
  10078. std::vector<std::string> protocols;
  10079. std::istringstream iss(protocol_header);
  10080. std::string token;
  10081. while (std::getline(iss, token, ',')) {
  10082. // Trim whitespace
  10083. auto start = token.find_first_not_of(' ');
  10084. auto end = token.find_last_not_of(' ');
  10085. if (start != std::string::npos) {
  10086. protocols.push_back(token.substr(start, end - start + 1));
  10087. }
  10088. }
  10089. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10090. }
  10091. }
  10092. // Send 101 Switching Protocols
  10093. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10094. "Upgrade: websocket\r\n"
  10095. "Connection: Upgrade\r\n"
  10096. "Sec-WebSocket-Accept: " +
  10097. accept_key + "\r\n";
  10098. if (!selected_subprotocol.empty()) {
  10099. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10100. return false;
  10101. }
  10102. handshake_response +=
  10103. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10104. }
  10105. handshake_response += "\r\n";
  10106. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10107. 0) {
  10108. return false;
  10109. }
  10110. connection_closed = true;
  10111. if (websocket_upgraded) { *websocket_upgraded = true; }
  10112. {
  10113. // Use WebSocket-specific read timeout instead of HTTP timeout
  10114. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10115. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_);
  10116. entry.handler(req, ws);
  10117. }
  10118. return true;
  10119. }
  10120. }
  10121. // No matching handler - fall through to 404
  10122. }
  10123. // Routing
  10124. auto routed = false;
  10125. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10126. routed = routing(req, res, strm);
  10127. #else
  10128. try {
  10129. routed = routing(req, res, strm);
  10130. } catch (std::exception &) {
  10131. if (exception_handler_) {
  10132. auto ep = std::current_exception();
  10133. exception_handler_(req, res, ep);
  10134. routed = true;
  10135. } else {
  10136. res.status = StatusCode::InternalServerError_500;
  10137. }
  10138. } catch (...) {
  10139. if (exception_handler_) {
  10140. auto ep = std::current_exception();
  10141. exception_handler_(req, res, ep);
  10142. routed = true;
  10143. } else {
  10144. res.status = StatusCode::InternalServerError_500;
  10145. }
  10146. }
  10147. #endif
  10148. if (routed) {
  10149. if (res.status == -1) {
  10150. res.status = req.ranges.empty() ? StatusCode::OK_200
  10151. : StatusCode::PartialContent_206;
  10152. }
  10153. // Serve file content by using a content provider
  10154. if (!res.file_content_path_.empty()) {
  10155. const auto &path = res.file_content_path_;
  10156. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10157. if (!mm->is_open()) {
  10158. res.body.clear();
  10159. res.content_length_ = 0;
  10160. res.content_provider_ = nullptr;
  10161. res.status = StatusCode::NotFound_404;
  10162. output_error_log(Error::OpenFile, &req);
  10163. return write_response(strm, close_connection, req, res);
  10164. }
  10165. auto content_type = res.file_content_content_type_;
  10166. if (content_type.empty()) {
  10167. content_type = detail::find_content_type(
  10168. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10169. }
  10170. res.set_content_provider(
  10171. mm->size(), content_type,
  10172. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10173. sink.write(mm->data() + offset, length);
  10174. return true;
  10175. });
  10176. }
  10177. if (detail::range_error(req, res)) {
  10178. res.body.clear();
  10179. res.content_length_ = 0;
  10180. res.content_provider_ = nullptr;
  10181. res.status = StatusCode::RangeNotSatisfiable_416;
  10182. return write_response(strm, close_connection, req, res);
  10183. }
  10184. return write_response_with_content(strm, close_connection, req, res);
  10185. } else {
  10186. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10187. return write_response(strm, close_connection, req, res);
  10188. }
  10189. }
  10190. inline bool Server::is_valid() const { return true; }
  10191. inline bool Server::process_and_close_socket(socket_t sock) {
  10192. std::string remote_addr;
  10193. int remote_port = 0;
  10194. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10195. std::string local_addr;
  10196. int local_port = 0;
  10197. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10198. bool websocket_upgraded = false;
  10199. auto ret = detail::process_server_socket(
  10200. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10201. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10202. write_timeout_usec_,
  10203. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10204. return process_request(strm, remote_addr, remote_port, local_addr,
  10205. local_port, close_connection, connection_closed,
  10206. nullptr, &websocket_upgraded);
  10207. });
  10208. detail::shutdown_socket(sock);
  10209. detail::close_socket(sock);
  10210. return ret;
  10211. }
  10212. inline void Server::output_log(const Request &req, const Response &res) const {
  10213. if (logger_) {
  10214. std::lock_guard<std::mutex> guard(logger_mutex_);
  10215. logger_(req, res);
  10216. }
  10217. }
  10218. inline void Server::output_pre_compression_log(const Request &req,
  10219. const Response &res) const {
  10220. if (pre_compression_logger_) {
  10221. std::lock_guard<std::mutex> guard(logger_mutex_);
  10222. pre_compression_logger_(req, res);
  10223. }
  10224. }
  10225. inline void Server::output_error_log(const Error &err,
  10226. const Request *req) const {
  10227. if (error_logger_) {
  10228. std::lock_guard<std::mutex> guard(logger_mutex_);
  10229. error_logger_(err, req);
  10230. }
  10231. }
  10232. /*
  10233. * Group 5: ClientImpl and Client (Universal) implementation
  10234. */
  10235. // HTTP client implementation
  10236. inline ClientImpl::ClientImpl(const std::string &host)
  10237. : ClientImpl(host, 80, std::string(), std::string()) {}
  10238. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10239. : ClientImpl(host, port, std::string(), std::string()) {}
  10240. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10241. const std::string &client_cert_path,
  10242. const std::string &client_key_path)
  10243. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10244. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10245. inline ClientImpl::~ClientImpl() {
  10246. // Wait until all the requests in flight are handled.
  10247. size_t retry_count = 10;
  10248. while (retry_count-- > 0) {
  10249. {
  10250. std::lock_guard<std::mutex> guard(socket_mutex_);
  10251. if (socket_requests_in_flight_ == 0) { break; }
  10252. }
  10253. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10254. }
  10255. std::lock_guard<std::mutex> guard(socket_mutex_);
  10256. shutdown_socket(socket_);
  10257. close_socket(socket_);
  10258. }
  10259. inline bool ClientImpl::is_valid() const { return true; }
  10260. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10261. client_cert_path_ = rhs.client_cert_path_;
  10262. client_key_path_ = rhs.client_key_path_;
  10263. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10264. read_timeout_sec_ = rhs.read_timeout_sec_;
  10265. read_timeout_usec_ = rhs.read_timeout_usec_;
  10266. write_timeout_sec_ = rhs.write_timeout_sec_;
  10267. write_timeout_usec_ = rhs.write_timeout_usec_;
  10268. max_timeout_msec_ = rhs.max_timeout_msec_;
  10269. basic_auth_username_ = rhs.basic_auth_username_;
  10270. basic_auth_password_ = rhs.basic_auth_password_;
  10271. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10272. keep_alive_ = rhs.keep_alive_;
  10273. follow_location_ = rhs.follow_location_;
  10274. path_encode_ = rhs.path_encode_;
  10275. address_family_ = rhs.address_family_;
  10276. tcp_nodelay_ = rhs.tcp_nodelay_;
  10277. ipv6_v6only_ = rhs.ipv6_v6only_;
  10278. socket_options_ = rhs.socket_options_;
  10279. compress_ = rhs.compress_;
  10280. decompress_ = rhs.decompress_;
  10281. payload_max_length_ = rhs.payload_max_length_;
  10282. has_payload_max_length_ = rhs.has_payload_max_length_;
  10283. interface_ = rhs.interface_;
  10284. proxy_host_ = rhs.proxy_host_;
  10285. proxy_port_ = rhs.proxy_port_;
  10286. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10287. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10288. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10289. logger_ = rhs.logger_;
  10290. error_logger_ = rhs.error_logger_;
  10291. #ifdef CPPHTTPLIB_SSL_ENABLED
  10292. digest_auth_username_ = rhs.digest_auth_username_;
  10293. digest_auth_password_ = rhs.digest_auth_password_;
  10294. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10295. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10296. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10297. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10298. server_certificate_verification_ = rhs.server_certificate_verification_;
  10299. server_hostname_verification_ = rhs.server_hostname_verification_;
  10300. #endif
  10301. }
  10302. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10303. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10304. return detail::create_client_socket(
  10305. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10306. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10307. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10308. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10309. }
  10310. // Check is custom IP specified for host_
  10311. std::string ip;
  10312. auto it = addr_map_.find(host_);
  10313. if (it != addr_map_.end()) { ip = it->second; }
  10314. return detail::create_client_socket(
  10315. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10316. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10317. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10318. write_timeout_usec_, interface_, error);
  10319. }
  10320. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10321. Error &error) {
  10322. auto sock = create_client_socket(error);
  10323. if (sock == INVALID_SOCKET) { return false; }
  10324. socket.sock = sock;
  10325. return true;
  10326. }
  10327. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10328. return create_and_connect_socket(socket, error);
  10329. }
  10330. inline bool ClientImpl::setup_proxy_connection(
  10331. Socket & /*socket*/,
  10332. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10333. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10334. return true;
  10335. }
  10336. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10337. bool /*shutdown_gracefully*/) {
  10338. // If there are any requests in flight from threads other than us, then it's
  10339. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10340. assert(socket_requests_in_flight_ == 0 ||
  10341. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10342. }
  10343. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10344. if (socket.sock == INVALID_SOCKET) { return; }
  10345. detail::shutdown_socket(socket.sock);
  10346. }
  10347. inline void ClientImpl::close_socket(Socket &socket) {
  10348. // If there are requests in flight in another thread, usually closing
  10349. // the socket will be fine and they will simply receive an error when
  10350. // using the closed socket, but it is still a bug since rarely the OS
  10351. // may reassign the socket id to be used for a new socket, and then
  10352. // suddenly they will be operating on a live socket that is different
  10353. // than the one they intended!
  10354. assert(socket_requests_in_flight_ == 0 ||
  10355. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10356. // It is also a bug if this happens while SSL is still active
  10357. #ifdef CPPHTTPLIB_SSL_ENABLED
  10358. assert(socket.ssl == nullptr);
  10359. #endif
  10360. if (socket.sock == INVALID_SOCKET) { return; }
  10361. detail::close_socket(socket.sock);
  10362. socket.sock = INVALID_SOCKET;
  10363. }
  10364. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10365. Response &res,
  10366. bool skip_100_continue) const {
  10367. std::array<char, 2048> buf{};
  10368. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10369. if (!line_reader.getline()) { return false; }
  10370. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10371. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10372. #else
  10373. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10374. #endif
  10375. std::cmatch m;
  10376. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10377. return req.method == "CONNECT";
  10378. }
  10379. res.version = std::string(m[1]);
  10380. res.status = std::stoi(std::string(m[2]));
  10381. res.reason = std::string(m[3]);
  10382. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10383. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10384. if (!line_reader.getline()) { return false; } // CRLF
  10385. if (!line_reader.getline()) { return false; } // next response line
  10386. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10387. res.version = std::string(m[1]);
  10388. res.status = std::stoi(std::string(m[2]));
  10389. res.reason = std::string(m[3]);
  10390. }
  10391. return true;
  10392. }
  10393. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10394. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10395. auto ret = send_(req, res, error);
  10396. if (error == Error::SSLPeerCouldBeClosed_) {
  10397. assert(!ret);
  10398. ret = send_(req, res, error);
  10399. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10400. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10401. }
  10402. return ret;
  10403. }
  10404. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10405. {
  10406. std::lock_guard<std::mutex> guard(socket_mutex_);
  10407. // Set this to false immediately - if it ever gets set to true by the end
  10408. // of the request, we know another thread instructed us to close the
  10409. // socket.
  10410. socket_should_be_closed_when_request_is_done_ = false;
  10411. auto is_alive = false;
  10412. if (socket_.is_open()) {
  10413. is_alive = detail::is_socket_alive(socket_.sock);
  10414. #ifdef CPPHTTPLIB_SSL_ENABLED
  10415. if (is_alive && is_ssl()) {
  10416. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10417. is_alive = false;
  10418. }
  10419. }
  10420. #endif
  10421. if (!is_alive) {
  10422. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  10423. // seems like the other side has already closed the connection Also,
  10424. // there cannot be any requests in flight from other threads since we
  10425. // locked request_mutex_, so safe to close everything immediately
  10426. const bool shutdown_gracefully = false;
  10427. shutdown_ssl(socket_, shutdown_gracefully);
  10428. shutdown_socket(socket_);
  10429. close_socket(socket_);
  10430. }
  10431. }
  10432. if (!is_alive) {
  10433. if (!ensure_socket_connection(socket_, error)) {
  10434. output_error_log(error, &req);
  10435. return false;
  10436. }
  10437. {
  10438. auto success = true;
  10439. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10440. error)) {
  10441. if (!success) { output_error_log(error, &req); }
  10442. return success;
  10443. }
  10444. }
  10445. }
  10446. // Mark the current socket as being in use so that it cannot be closed by
  10447. // anyone else while this request is ongoing, even though we will be
  10448. // releasing the mutex.
  10449. if (socket_requests_in_flight_ > 1) {
  10450. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10451. }
  10452. socket_requests_in_flight_ += 1;
  10453. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10454. }
  10455. for (const auto &header : default_headers_) {
  10456. if (req.headers.find(header.first) == req.headers.end()) {
  10457. req.headers.insert(header);
  10458. }
  10459. }
  10460. auto ret = false;
  10461. auto close_connection = !keep_alive_;
  10462. auto se = detail::scope_exit([&]() {
  10463. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10464. std::lock_guard<std::mutex> guard(socket_mutex_);
  10465. socket_requests_in_flight_ -= 1;
  10466. if (socket_requests_in_flight_ <= 0) {
  10467. assert(socket_requests_in_flight_ == 0);
  10468. socket_requests_are_from_thread_ = std::thread::id();
  10469. }
  10470. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10471. !ret) {
  10472. shutdown_ssl(socket_, true);
  10473. shutdown_socket(socket_);
  10474. close_socket(socket_);
  10475. }
  10476. });
  10477. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10478. return handle_request(strm, req, res, close_connection, error);
  10479. });
  10480. if (!ret) {
  10481. if (error == Error::Success) {
  10482. error = Error::Unknown;
  10483. output_error_log(error, &req);
  10484. }
  10485. }
  10486. return ret;
  10487. }
  10488. inline Result ClientImpl::send(const Request &req) {
  10489. auto req2 = req;
  10490. return send_(std::move(req2));
  10491. }
  10492. inline Result ClientImpl::send_(Request &&req) {
  10493. auto res = detail::make_unique<Response>();
  10494. auto error = Error::Success;
  10495. auto ret = send(req, *res, error);
  10496. #ifdef CPPHTTPLIB_SSL_ENABLED
  10497. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10498. last_ssl_error_, last_backend_error_};
  10499. #else
  10500. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10501. #endif
  10502. }
  10503. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10504. const std::string &ct) {
  10505. (void)for_stream;
  10506. for (const auto &header : default_headers_) {
  10507. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10508. }
  10509. if (!r.has_header("Host")) {
  10510. if (address_family_ == AF_UNIX) {
  10511. r.headers.emplace("Host", "localhost");
  10512. } else {
  10513. r.headers.emplace(
  10514. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10515. }
  10516. }
  10517. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10518. if (!r.content_receiver) {
  10519. if (!r.has_header("Accept-Encoding")) {
  10520. std::string accept_encoding;
  10521. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10522. accept_encoding = "br";
  10523. #endif
  10524. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10525. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10526. accept_encoding += "gzip, deflate";
  10527. #endif
  10528. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10529. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10530. accept_encoding += "zstd";
  10531. #endif
  10532. r.set_header("Accept-Encoding", accept_encoding);
  10533. }
  10534. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10535. if (!r.has_header("User-Agent")) {
  10536. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  10537. r.set_header("User-Agent", agent);
  10538. }
  10539. #endif
  10540. }
  10541. if (!r.body.empty()) {
  10542. if (!ct.empty() && !r.has_header("Content-Type")) {
  10543. r.headers.emplace("Content-Type", ct);
  10544. }
  10545. if (!r.has_header("Content-Length")) {
  10546. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  10547. }
  10548. }
  10549. }
  10550. inline ClientImpl::StreamHandle
  10551. ClientImpl::open_stream(const std::string &method, const std::string &path,
  10552. const Params &params, const Headers &headers,
  10553. const std::string &body,
  10554. const std::string &content_type) {
  10555. StreamHandle handle;
  10556. handle.response = detail::make_unique<Response>();
  10557. handle.error = Error::Success;
  10558. auto query_path = params.empty() ? path : append_query_params(path, params);
  10559. handle.connection_ = detail::make_unique<ClientConnection>();
  10560. {
  10561. std::lock_guard<std::mutex> guard(socket_mutex_);
  10562. auto is_alive = false;
  10563. if (socket_.is_open()) {
  10564. is_alive = detail::is_socket_alive(socket_.sock);
  10565. #ifdef CPPHTTPLIB_SSL_ENABLED
  10566. if (is_alive && is_ssl()) {
  10567. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10568. is_alive = false;
  10569. }
  10570. }
  10571. #endif
  10572. if (!is_alive) {
  10573. shutdown_ssl(socket_, false);
  10574. shutdown_socket(socket_);
  10575. close_socket(socket_);
  10576. }
  10577. }
  10578. if (!is_alive) {
  10579. if (!ensure_socket_connection(socket_, handle.error)) {
  10580. handle.response.reset();
  10581. return handle;
  10582. }
  10583. {
  10584. auto success = true;
  10585. auto start_time = std::chrono::steady_clock::now();
  10586. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  10587. success, handle.error)) {
  10588. if (!success) { handle.response.reset(); }
  10589. return handle;
  10590. }
  10591. }
  10592. }
  10593. transfer_socket_ownership_to_handle(handle);
  10594. }
  10595. #ifdef CPPHTTPLIB_SSL_ENABLED
  10596. if (is_ssl() && handle.connection_->session) {
  10597. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  10598. handle.connection_->sock, handle.connection_->session,
  10599. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10600. write_timeout_usec_);
  10601. } else {
  10602. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10603. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10604. write_timeout_sec_, write_timeout_usec_);
  10605. }
  10606. #else
  10607. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10608. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10609. write_timeout_sec_, write_timeout_usec_);
  10610. #endif
  10611. handle.stream_ = handle.socket_stream_.get();
  10612. Request req;
  10613. req.method = method;
  10614. req.path = query_path;
  10615. req.headers = headers;
  10616. req.body = body;
  10617. prepare_default_headers(req, true, content_type);
  10618. auto &strm = *handle.stream_;
  10619. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  10620. handle.error = Error::Write;
  10621. handle.response.reset();
  10622. return handle;
  10623. }
  10624. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  10625. handle.error)) {
  10626. handle.response.reset();
  10627. return handle;
  10628. }
  10629. if (!body.empty()) {
  10630. if (strm.write(body.data(), body.size()) < 0) {
  10631. handle.error = Error::Write;
  10632. handle.response.reset();
  10633. return handle;
  10634. }
  10635. }
  10636. if (!read_response_line(strm, req, *handle.response) ||
  10637. !detail::read_headers(strm, handle.response->headers)) {
  10638. handle.error = Error::Read;
  10639. handle.response.reset();
  10640. return handle;
  10641. }
  10642. handle.body_reader_.stream = handle.stream_;
  10643. handle.body_reader_.payload_max_length = payload_max_length_;
  10644. if (handle.response->has_header("Content-Length")) {
  10645. bool is_invalid = false;
  10646. auto content_length = detail::get_header_value_u64(
  10647. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  10648. if (is_invalid) {
  10649. handle.error = Error::Read;
  10650. handle.response.reset();
  10651. return handle;
  10652. }
  10653. handle.body_reader_.has_content_length = true;
  10654. handle.body_reader_.content_length = content_length;
  10655. }
  10656. auto transfer_encoding =
  10657. handle.response->get_header_value("Transfer-Encoding");
  10658. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  10659. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  10660. if (!content_encoding.empty()) {
  10661. handle.decompressor_ = detail::create_decompressor(content_encoding);
  10662. }
  10663. return handle;
  10664. }
  10665. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  10666. if (!is_valid() || !response) { return -1; }
  10667. if (decompressor_) { return read_with_decompression(buf, len); }
  10668. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  10669. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  10670. trailers_parsed_ = true;
  10671. if (body_reader_.chunked_decoder) {
  10672. if (!body_reader_.chunked_decoder->parse_trailers_into(
  10673. response->trailers, response->headers)) {
  10674. return n;
  10675. }
  10676. } else {
  10677. detail::ChunkedDecoder dec(*stream_);
  10678. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  10679. return n;
  10680. }
  10681. }
  10682. }
  10683. return n;
  10684. }
  10685. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  10686. size_t len) {
  10687. if (decompress_offset_ < decompress_buffer_.size()) {
  10688. auto available = decompress_buffer_.size() - decompress_offset_;
  10689. auto to_copy = (std::min)(len, available);
  10690. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  10691. decompress_offset_ += to_copy;
  10692. decompressed_bytes_read_ += to_copy;
  10693. return static_cast<ssize_t>(to_copy);
  10694. }
  10695. decompress_buffer_.clear();
  10696. decompress_offset_ = 0;
  10697. constexpr size_t kDecompressionBufferSize = 8192;
  10698. char compressed_buf[kDecompressionBufferSize];
  10699. while (true) {
  10700. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  10701. sizeof(compressed_buf));
  10702. if (n <= 0) { return n; }
  10703. bool decompress_ok = decompressor_->decompress(
  10704. compressed_buf, static_cast<size_t>(n),
  10705. [this](const char *data, size_t data_len) {
  10706. decompress_buffer_.append(data, data_len);
  10707. auto limit = body_reader_.payload_max_length;
  10708. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  10709. return false;
  10710. }
  10711. return true;
  10712. });
  10713. if (!decompress_ok) {
  10714. body_reader_.last_error = Error::Read;
  10715. return -1;
  10716. }
  10717. if (!decompress_buffer_.empty()) { break; }
  10718. }
  10719. auto to_copy = (std::min)(len, decompress_buffer_.size());
  10720. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  10721. decompress_offset_ = to_copy;
  10722. decompressed_bytes_read_ += to_copy;
  10723. return static_cast<ssize_t>(to_copy);
  10724. }
  10725. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  10726. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  10727. return;
  10728. }
  10729. trailers_parsed_ = true;
  10730. const auto bufsiz = 128;
  10731. char line_buf[bufsiz];
  10732. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  10733. if (!line_reader.getline()) { return; }
  10734. if (!detail::parse_trailers(line_reader, response->trailers,
  10735. response->headers)) {
  10736. return;
  10737. }
  10738. }
  10739. namespace detail {
  10740. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  10741. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  10742. size_t &out_chunk_offset,
  10743. size_t &out_chunk_total) {
  10744. if (finished) { return 0; }
  10745. if (chunk_remaining == 0) {
  10746. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10747. if (!lr.getline()) { return -1; }
  10748. char *endptr = nullptr;
  10749. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  10750. if (endptr == lr.ptr()) { return -1; }
  10751. if (chunk_len == ULONG_MAX) { return -1; }
  10752. if (chunk_len == 0) {
  10753. chunk_remaining = 0;
  10754. finished = true;
  10755. out_chunk_offset = 0;
  10756. out_chunk_total = 0;
  10757. return 0;
  10758. }
  10759. chunk_remaining = static_cast<size_t>(chunk_len);
  10760. last_chunk_total = chunk_remaining;
  10761. last_chunk_offset = 0;
  10762. }
  10763. auto to_read = (std::min)(chunk_remaining, len);
  10764. auto n = strm.read(buf, to_read);
  10765. if (n <= 0) { return -1; }
  10766. auto offset_before = last_chunk_offset;
  10767. last_chunk_offset += static_cast<size_t>(n);
  10768. chunk_remaining -= static_cast<size_t>(n);
  10769. out_chunk_offset = offset_before;
  10770. out_chunk_total = last_chunk_total;
  10771. if (chunk_remaining == 0) {
  10772. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10773. if (!lr.getline()) { return -1; }
  10774. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  10775. }
  10776. return n;
  10777. }
  10778. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  10779. const Headers &src_headers) {
  10780. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10781. if (!lr.getline()) { return false; }
  10782. return parse_trailers(lr, dest, src_headers);
  10783. }
  10784. } // namespace detail
  10785. inline void
  10786. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  10787. handle.connection_->sock = socket_.sock;
  10788. #ifdef CPPHTTPLIB_SSL_ENABLED
  10789. handle.connection_->session = socket_.ssl;
  10790. socket_.ssl = nullptr;
  10791. #endif
  10792. socket_.sock = INVALID_SOCKET;
  10793. }
  10794. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  10795. Response &res, bool close_connection,
  10796. Error &error) {
  10797. if (req.path.empty()) {
  10798. error = Error::Connection;
  10799. output_error_log(error, &req);
  10800. return false;
  10801. }
  10802. auto req_save = req;
  10803. bool ret;
  10804. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  10805. auto req2 = req;
  10806. req2.path = "http://" +
  10807. detail::make_host_and_port_string(host_, port_, false) +
  10808. req.path;
  10809. ret = process_request(strm, req2, res, close_connection, error);
  10810. req = std::move(req2);
  10811. req.path = req_save.path;
  10812. } else {
  10813. ret = process_request(strm, req, res, close_connection, error);
  10814. }
  10815. if (!ret) { return false; }
  10816. if (res.get_header_value("Connection") == "close" ||
  10817. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  10818. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  10819. // for this to be safe.
  10820. // This is safe to call because handle_request is only called by send_
  10821. // which locks the request mutex during the process. It would be a bug
  10822. // to call it from a different thread since it's a thread-safety issue
  10823. // to do these things to the socket if another thread is using the socket.
  10824. std::lock_guard<std::mutex> guard(socket_mutex_);
  10825. shutdown_ssl(socket_, true);
  10826. shutdown_socket(socket_);
  10827. close_socket(socket_);
  10828. }
  10829. if (300 < res.status && res.status < 400 && follow_location_) {
  10830. req = std::move(req_save);
  10831. ret = redirect(req, res, error);
  10832. }
  10833. #ifdef CPPHTTPLIB_SSL_ENABLED
  10834. if ((res.status == StatusCode::Unauthorized_401 ||
  10835. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  10836. req.authorization_count_ < 5) {
  10837. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  10838. const auto &username =
  10839. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  10840. const auto &password =
  10841. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  10842. if (!username.empty() && !password.empty()) {
  10843. std::map<std::string, std::string> auth;
  10844. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  10845. Request new_req = req;
  10846. new_req.authorization_count_ += 1;
  10847. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  10848. : "Authorization");
  10849. new_req.headers.insert(detail::make_digest_authentication_header(
  10850. req, auth, new_req.authorization_count_, detail::random_string(10),
  10851. username, password, is_proxy));
  10852. Response new_res;
  10853. ret = send(new_req, new_res, error);
  10854. if (ret) { res = std::move(new_res); }
  10855. }
  10856. }
  10857. }
  10858. #endif
  10859. return ret;
  10860. }
  10861. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  10862. if (req.redirect_count_ == 0) {
  10863. error = Error::ExceedRedirectCount;
  10864. output_error_log(error, &req);
  10865. return false;
  10866. }
  10867. auto location = res.get_header_value("location");
  10868. if (location.empty()) { return false; }
  10869. thread_local const std::regex re(
  10870. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  10871. std::smatch m;
  10872. if (!std::regex_match(location, m, re)) { return false; }
  10873. auto scheme = is_ssl() ? "https" : "http";
  10874. auto next_scheme = m[1].str();
  10875. auto next_host = m[2].str();
  10876. if (next_host.empty()) { next_host = m[3].str(); }
  10877. auto port_str = m[4].str();
  10878. auto next_path = m[5].str();
  10879. auto next_query = m[6].str();
  10880. auto next_port = port_;
  10881. if (!port_str.empty()) {
  10882. if (!detail::parse_port(port_str, next_port)) { return false; }
  10883. } else if (!next_scheme.empty()) {
  10884. next_port = next_scheme == "https" ? 443 : 80;
  10885. }
  10886. if (next_scheme.empty()) { next_scheme = scheme; }
  10887. if (next_host.empty()) { next_host = host_; }
  10888. if (next_path.empty()) { next_path = "/"; }
  10889. auto path = decode_query_component(next_path, true) + next_query;
  10890. // Same host redirect - use current client
  10891. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  10892. return detail::redirect(*this, req, res, path, location, error);
  10893. }
  10894. // Cross-host/scheme redirect - create new client with robust setup
  10895. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  10896. path, location, error);
  10897. }
  10898. // New method for robust redirect client creation
  10899. inline bool ClientImpl::create_redirect_client(
  10900. const std::string &scheme, const std::string &host, int port, Request &req,
  10901. Response &res, const std::string &path, const std::string &location,
  10902. Error &error) {
  10903. // Determine if we need SSL
  10904. auto need_ssl = (scheme == "https");
  10905. // Clean up request headers that are host/client specific
  10906. // Remove headers that should not be carried over to new host
  10907. auto headers_to_remove =
  10908. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  10909. for (const auto &header_name : headers_to_remove) {
  10910. auto it = req.headers.find(header_name);
  10911. while (it != req.headers.end()) {
  10912. it = req.headers.erase(it);
  10913. it = req.headers.find(header_name);
  10914. }
  10915. }
  10916. // Create appropriate client type and handle redirect
  10917. if (need_ssl) {
  10918. #ifdef CPPHTTPLIB_SSL_ENABLED
  10919. // Create SSL client for HTTPS redirect
  10920. SSLClient redirect_client(host, port);
  10921. // Setup basic client configuration first
  10922. setup_redirect_client(redirect_client);
  10923. redirect_client.enable_server_certificate_verification(
  10924. server_certificate_verification_);
  10925. redirect_client.enable_server_hostname_verification(
  10926. server_hostname_verification_);
  10927. // Transfer CA certificate to redirect client
  10928. if (!ca_cert_pem_.empty()) {
  10929. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  10930. ca_cert_pem_.size());
  10931. }
  10932. if (!ca_cert_file_path_.empty()) {
  10933. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  10934. }
  10935. // Client certificates are set through constructor for SSLClient
  10936. // NOTE: SSLClient constructor already takes client_cert_path and
  10937. // client_key_path so we need to create it properly if client certs are
  10938. // needed
  10939. // Execute the redirect
  10940. return detail::redirect(redirect_client, req, res, path, location, error);
  10941. #else
  10942. // SSL not supported - set appropriate error
  10943. error = Error::SSLConnection;
  10944. output_error_log(error, &req);
  10945. return false;
  10946. #endif
  10947. } else {
  10948. // HTTP redirect
  10949. ClientImpl redirect_client(host, port);
  10950. // Setup client with robust configuration
  10951. setup_redirect_client(redirect_client);
  10952. // Execute the redirect
  10953. return detail::redirect(redirect_client, req, res, path, location, error);
  10954. }
  10955. }
  10956. // New method for robust client setup (based on basic_manual_redirect.cpp
  10957. // logic)
  10958. template <typename ClientType>
  10959. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  10960. // Copy basic settings first
  10961. client.set_connection_timeout(connection_timeout_sec_);
  10962. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  10963. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  10964. client.set_keep_alive(keep_alive_);
  10965. client.set_follow_location(
  10966. true); // Enable redirects to handle multi-step redirects
  10967. client.set_path_encode(path_encode_);
  10968. client.set_compress(compress_);
  10969. client.set_decompress(decompress_);
  10970. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  10971. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  10972. // 15.4, credentials must not be forwarded when redirecting to a different
  10973. // host. This function is only called for cross-host redirects; same-host
  10974. // redirects are handled directly in ClientImpl::redirect().
  10975. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  10976. // before proxy auth)
  10977. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10978. // First set proxy host and port
  10979. client.set_proxy(proxy_host_, proxy_port_);
  10980. // Then set proxy authentication (order matters!)
  10981. if (!proxy_basic_auth_username_.empty()) {
  10982. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  10983. proxy_basic_auth_password_);
  10984. }
  10985. if (!proxy_bearer_token_auth_token_.empty()) {
  10986. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  10987. }
  10988. #ifdef CPPHTTPLIB_SSL_ENABLED
  10989. if (!proxy_digest_auth_username_.empty()) {
  10990. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  10991. proxy_digest_auth_password_);
  10992. }
  10993. #endif
  10994. }
  10995. // Copy network and socket settings
  10996. client.set_address_family(address_family_);
  10997. client.set_tcp_nodelay(tcp_nodelay_);
  10998. client.set_ipv6_v6only(ipv6_v6only_);
  10999. if (socket_options_) { client.set_socket_options(socket_options_); }
  11000. if (!interface_.empty()) { client.set_interface(interface_); }
  11001. // Copy logging and headers
  11002. if (logger_) { client.set_logger(logger_); }
  11003. if (error_logger_) { client.set_error_logger(error_logger_); }
  11004. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11005. // Each new client should generate its own headers based on its target host
  11006. }
  11007. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11008. const Request &req,
  11009. Error &error) const {
  11010. auto is_shutting_down = []() { return false; };
  11011. if (req.is_chunked_content_provider_) {
  11012. auto compressor = compress_ ? detail::create_compressor().first
  11013. : std::unique_ptr<detail::compressor>();
  11014. if (!compressor) {
  11015. compressor = detail::make_unique<detail::nocompressor>();
  11016. }
  11017. return detail::write_content_chunked(strm, req.content_provider_,
  11018. is_shutting_down, *compressor, error);
  11019. } else {
  11020. return detail::write_content_with_progress(
  11021. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11022. req.upload_progress, error);
  11023. }
  11024. }
  11025. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11026. bool close_connection, Error &error,
  11027. bool skip_body) {
  11028. // Prepare additional headers
  11029. if (close_connection) {
  11030. if (!req.has_header("Connection")) {
  11031. req.set_header("Connection", "close");
  11032. }
  11033. }
  11034. std::string ct_for_defaults;
  11035. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11036. ct_for_defaults = "text/plain";
  11037. }
  11038. prepare_default_headers(req, false, ct_for_defaults);
  11039. if (req.body.empty()) {
  11040. if (req.content_provider_) {
  11041. if (!req.is_chunked_content_provider_) {
  11042. if (!req.has_header("Content-Length")) {
  11043. auto length = std::to_string(req.content_length_);
  11044. req.set_header("Content-Length", length);
  11045. }
  11046. }
  11047. } else {
  11048. if (req.method == "POST" || req.method == "PUT" ||
  11049. req.method == "PATCH") {
  11050. req.set_header("Content-Length", "0");
  11051. }
  11052. }
  11053. }
  11054. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11055. if (!req.has_header("Authorization")) {
  11056. req.headers.insert(make_basic_authentication_header(
  11057. basic_auth_username_, basic_auth_password_, false));
  11058. }
  11059. }
  11060. if (!proxy_basic_auth_username_.empty() &&
  11061. !proxy_basic_auth_password_.empty()) {
  11062. if (!req.has_header("Proxy-Authorization")) {
  11063. req.headers.insert(make_basic_authentication_header(
  11064. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11065. }
  11066. }
  11067. if (!bearer_token_auth_token_.empty()) {
  11068. if (!req.has_header("Authorization")) {
  11069. req.headers.insert(make_bearer_token_authentication_header(
  11070. bearer_token_auth_token_, false));
  11071. }
  11072. }
  11073. if (!proxy_bearer_token_auth_token_.empty()) {
  11074. if (!req.has_header("Proxy-Authorization")) {
  11075. req.headers.insert(make_bearer_token_authentication_header(
  11076. proxy_bearer_token_auth_token_, true));
  11077. }
  11078. }
  11079. // Request line and headers
  11080. {
  11081. detail::BufferStream bstrm;
  11082. // Extract path and query from req.path
  11083. std::string path_part, query_part;
  11084. auto query_pos = req.path.find('?');
  11085. if (query_pos != std::string::npos) {
  11086. path_part = req.path.substr(0, query_pos);
  11087. query_part = req.path.substr(query_pos + 1);
  11088. } else {
  11089. path_part = req.path;
  11090. query_part = "";
  11091. }
  11092. // Encode path part. If the original `req.path` already contained a
  11093. // query component, preserve its raw query string (including parameter
  11094. // order) instead of reparsing and reassembling it which may reorder
  11095. // parameters due to container ordering (e.g. `Params` uses
  11096. // `std::multimap`). When there is no query in `req.path`, fall back to
  11097. // building a query from `req.params` so existing callers that pass
  11098. // `Params` continue to work.
  11099. auto path_with_query =
  11100. path_encode_ ? detail::encode_path(path_part) : path_part;
  11101. if (!query_part.empty()) {
  11102. // Normalize the query string (decode then re-encode) while preserving
  11103. // the original parameter order.
  11104. auto normalized = detail::normalize_query_string(query_part);
  11105. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11106. // Still populate req.params for handlers/users who read them.
  11107. detail::parse_query_text(query_part, req.params);
  11108. } else {
  11109. // No query in path; parse any query_part (empty) and append params
  11110. // from `req.params` when present (preserves prior behavior for
  11111. // callers who provide Params separately).
  11112. detail::parse_query_text(query_part, req.params);
  11113. if (!req.params.empty()) {
  11114. path_with_query = append_query_params(path_with_query, req.params);
  11115. }
  11116. }
  11117. // Write request line and headers
  11118. detail::write_request_line(bstrm, req.method, path_with_query);
  11119. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11120. error)) {
  11121. output_error_log(error, &req);
  11122. return false;
  11123. }
  11124. // Flush buffer
  11125. auto &data = bstrm.get_buffer();
  11126. if (!detail::write_data(strm, data.data(), data.size())) {
  11127. error = Error::Write;
  11128. output_error_log(error, &req);
  11129. return false;
  11130. }
  11131. }
  11132. // After sending request line and headers, wait briefly for an early server
  11133. // response (e.g. 4xx) and avoid sending a potentially large request body
  11134. // unnecessarily. This workaround is only enabled on Windows because Unix
  11135. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11136. // buffering can accept large writes even when the peer already responded.
  11137. // Check the stream first (which covers SSL via `is_readable()`), then
  11138. // fall back to select on the socket. Only perform the wait for very large
  11139. // request bodies to avoid interfering with normal small requests and
  11140. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11141. // response. Skip this check when using Expect: 100-continue, as the protocol
  11142. // handles early responses properly.
  11143. #if defined(_WIN32)
  11144. if (!skip_body &&
  11145. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11146. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11147. auto start = std::chrono::high_resolution_clock::now();
  11148. for (;;) {
  11149. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11150. // from SSL internals. If the underlying socket is readable, assume an
  11151. // early response may be present.
  11152. auto sock = strm.socket();
  11153. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11154. return false;
  11155. }
  11156. // Fallback to stream-level check for non-socket streams or when the
  11157. // socket isn't reporting readable. Avoid using `is_readable()` for
  11158. // SSL, since `SSL_pending()` may report buffered records that do not
  11159. // indicate a complete application-level response yet.
  11160. if (!is_ssl() && strm.is_readable()) { return false; }
  11161. auto now = std::chrono::high_resolution_clock::now();
  11162. auto elapsed =
  11163. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11164. .count();
  11165. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11166. break;
  11167. }
  11168. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11169. }
  11170. }
  11171. #endif
  11172. // Body
  11173. if (skip_body) { return true; }
  11174. return write_request_body(strm, req, error);
  11175. }
  11176. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11177. Error &error) {
  11178. if (req.body.empty()) {
  11179. return write_content_with_provider(strm, req, error);
  11180. }
  11181. if (req.upload_progress) {
  11182. auto body_size = req.body.size();
  11183. size_t written = 0;
  11184. auto data = req.body.data();
  11185. while (written < body_size) {
  11186. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11187. if (!detail::write_data(strm, data + written, to_write)) {
  11188. error = Error::Write;
  11189. output_error_log(error, &req);
  11190. return false;
  11191. }
  11192. written += to_write;
  11193. if (!req.upload_progress(written, body_size)) {
  11194. error = Error::Canceled;
  11195. output_error_log(error, &req);
  11196. return false;
  11197. }
  11198. }
  11199. } else {
  11200. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11201. error = Error::Write;
  11202. output_error_log(error, &req);
  11203. return false;
  11204. }
  11205. }
  11206. return true;
  11207. }
  11208. inline std::unique_ptr<Response>
  11209. ClientImpl::send_with_content_provider_and_receiver(
  11210. Request &req, const char *body, size_t content_length,
  11211. ContentProvider content_provider,
  11212. ContentProviderWithoutLength content_provider_without_length,
  11213. const std::string &content_type, ContentReceiver content_receiver,
  11214. Error &error) {
  11215. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11216. auto enc = compress_
  11217. ? detail::create_compressor()
  11218. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11219. nullptr, nullptr);
  11220. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11221. if (enc.first && !content_provider_without_length) {
  11222. auto &compressor = enc.first;
  11223. if (content_provider) {
  11224. auto ok = true;
  11225. size_t offset = 0;
  11226. DataSink data_sink;
  11227. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11228. if (ok) {
  11229. auto last = offset + data_len == content_length;
  11230. auto ret = compressor->compress(
  11231. data, data_len, last,
  11232. [&](const char *compressed_data, size_t compressed_data_len) {
  11233. req.body.append(compressed_data, compressed_data_len);
  11234. return true;
  11235. });
  11236. if (ret) {
  11237. offset += data_len;
  11238. } else {
  11239. ok = false;
  11240. }
  11241. }
  11242. return ok;
  11243. };
  11244. while (ok && offset < content_length) {
  11245. if (!content_provider(offset, content_length - offset, data_sink)) {
  11246. error = Error::Canceled;
  11247. output_error_log(error, &req);
  11248. return nullptr;
  11249. }
  11250. }
  11251. } else {
  11252. if (!compressor->compress(body, content_length, true,
  11253. [&](const char *data, size_t data_len) {
  11254. req.body.append(data, data_len);
  11255. return true;
  11256. })) {
  11257. error = Error::Compression;
  11258. output_error_log(error, &req);
  11259. return nullptr;
  11260. }
  11261. }
  11262. } else {
  11263. if (content_provider) {
  11264. req.content_length_ = content_length;
  11265. req.content_provider_ = std::move(content_provider);
  11266. req.is_chunked_content_provider_ = false;
  11267. } else if (content_provider_without_length) {
  11268. req.content_length_ = 0;
  11269. req.content_provider_ = detail::ContentProviderAdapter(
  11270. std::move(content_provider_without_length));
  11271. req.is_chunked_content_provider_ = true;
  11272. req.set_header("Transfer-Encoding", "chunked");
  11273. } else {
  11274. req.body.assign(body, content_length);
  11275. }
  11276. }
  11277. if (content_receiver) {
  11278. req.content_receiver =
  11279. [content_receiver](const char *data, size_t data_length,
  11280. size_t /*offset*/, size_t /*total_length*/) {
  11281. return content_receiver(data, data_length);
  11282. };
  11283. }
  11284. auto res = detail::make_unique<Response>();
  11285. return send(req, *res, error) ? std::move(res) : nullptr;
  11286. }
  11287. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11288. const std::string &method, const std::string &path, const Headers &headers,
  11289. const char *body, size_t content_length, ContentProvider content_provider,
  11290. ContentProviderWithoutLength content_provider_without_length,
  11291. const std::string &content_type, ContentReceiver content_receiver,
  11292. UploadProgress progress) {
  11293. Request req;
  11294. req.method = method;
  11295. req.headers = headers;
  11296. req.path = path;
  11297. req.upload_progress = std::move(progress);
  11298. if (max_timeout_msec_ > 0) {
  11299. req.start_time_ = std::chrono::steady_clock::now();
  11300. }
  11301. auto error = Error::Success;
  11302. auto res = send_with_content_provider_and_receiver(
  11303. req, body, content_length, std::move(content_provider),
  11304. std::move(content_provider_without_length), content_type,
  11305. std::move(content_receiver), error);
  11306. #ifdef CPPHTTPLIB_SSL_ENABLED
  11307. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11308. last_backend_error_};
  11309. #else
  11310. return Result{std::move(res), error, std::move(req.headers)};
  11311. #endif
  11312. }
  11313. inline void ClientImpl::output_log(const Request &req,
  11314. const Response &res) const {
  11315. if (logger_) {
  11316. std::lock_guard<std::mutex> guard(logger_mutex_);
  11317. logger_(req, res);
  11318. }
  11319. }
  11320. inline void ClientImpl::output_error_log(const Error &err,
  11321. const Request *req) const {
  11322. if (error_logger_) {
  11323. std::lock_guard<std::mutex> guard(logger_mutex_);
  11324. error_logger_(err, req);
  11325. }
  11326. }
  11327. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11328. Response &res, bool close_connection,
  11329. Error &error) {
  11330. // Auto-add Expect: 100-continue for large bodies
  11331. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11332. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11333. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11334. req.set_header("Expect", "100-continue");
  11335. }
  11336. }
  11337. // Check for Expect: 100-continue
  11338. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11339. // Send request (skip body if using Expect: 100-continue)
  11340. auto write_request_success =
  11341. write_request(strm, req, close_connection, error, expect_100_continue);
  11342. #ifdef CPPHTTPLIB_SSL_ENABLED
  11343. if (is_ssl() && !expect_100_continue) {
  11344. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  11345. if (!is_proxy_enabled) {
  11346. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11347. error = Error::SSLPeerCouldBeClosed_;
  11348. output_error_log(error, &req);
  11349. return false;
  11350. }
  11351. }
  11352. }
  11353. #endif
  11354. // Handle Expect: 100-continue with timeout
  11355. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11356. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11357. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11358. auto ret = detail::select_read(strm.socket(), sec, usec);
  11359. if (ret <= 0) {
  11360. // Timeout or error: send body anyway (server didn't respond in time)
  11361. if (!write_request_body(strm, req, error)) { return false; }
  11362. expect_100_continue = false; // Switch to normal response handling
  11363. }
  11364. }
  11365. // Receive response and headers
  11366. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11367. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  11368. !detail::read_headers(strm, res.headers)) {
  11369. if (write_request_success) { error = Error::Read; }
  11370. output_error_log(error, &req);
  11371. return false;
  11372. }
  11373. if (!write_request_success) { return false; }
  11374. // Handle Expect: 100-continue response
  11375. if (expect_100_continue) {
  11376. if (res.status == StatusCode::Continue_100) {
  11377. // Server accepted, send the body
  11378. if (!write_request_body(strm, req, error)) { return false; }
  11379. // Read the actual response
  11380. res.headers.clear();
  11381. res.body.clear();
  11382. if (!read_response_line(strm, req, res) ||
  11383. !detail::read_headers(strm, res.headers)) {
  11384. error = Error::Read;
  11385. output_error_log(error, &req);
  11386. return false;
  11387. }
  11388. }
  11389. // If not 100 Continue, server returned an error; proceed with that response
  11390. }
  11391. // Body
  11392. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11393. req.method != "CONNECT") {
  11394. auto redirect = 300 < res.status && res.status < 400 &&
  11395. res.status != StatusCode::NotModified_304 &&
  11396. follow_location_;
  11397. if (req.response_handler && !redirect) {
  11398. if (!req.response_handler(res)) {
  11399. error = Error::Canceled;
  11400. output_error_log(error, &req);
  11401. return false;
  11402. }
  11403. }
  11404. auto out =
  11405. req.content_receiver
  11406. ? static_cast<ContentReceiverWithProgress>(
  11407. [&](const char *buf, size_t n, size_t off, size_t len) {
  11408. if (redirect) { return true; }
  11409. auto ret = req.content_receiver(buf, n, off, len);
  11410. if (!ret) {
  11411. error = Error::Canceled;
  11412. output_error_log(error, &req);
  11413. }
  11414. return ret;
  11415. })
  11416. : static_cast<ContentReceiverWithProgress>(
  11417. [&](const char *buf, size_t n, size_t /*off*/,
  11418. size_t /*len*/) {
  11419. assert(res.body.size() + n <= res.body.max_size());
  11420. if (payload_max_length_ > 0 &&
  11421. (res.body.size() >= payload_max_length_ ||
  11422. n > payload_max_length_ - res.body.size())) {
  11423. return false;
  11424. }
  11425. res.body.append(buf, n);
  11426. return true;
  11427. });
  11428. auto progress = [&](size_t current, size_t total) {
  11429. if (!req.download_progress || redirect) { return true; }
  11430. auto ret = req.download_progress(current, total);
  11431. if (!ret) {
  11432. error = Error::Canceled;
  11433. output_error_log(error, &req);
  11434. }
  11435. return ret;
  11436. };
  11437. if (res.has_header("Content-Length")) {
  11438. if (!req.content_receiver) {
  11439. auto len = res.get_header_value_u64("Content-Length");
  11440. if (len > res.body.max_size()) {
  11441. error = Error::Read;
  11442. output_error_log(error, &req);
  11443. return false;
  11444. }
  11445. res.body.reserve(static_cast<size_t>(len));
  11446. }
  11447. }
  11448. if (res.status != StatusCode::NotModified_304) {
  11449. int dummy_status;
  11450. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11451. ? (std::numeric_limits<size_t>::max)()
  11452. : payload_max_length_;
  11453. if (!detail::read_content(strm, res, max_length, dummy_status,
  11454. std::move(progress), std::move(out),
  11455. decompress_)) {
  11456. if (error != Error::Canceled) { error = Error::Read; }
  11457. output_error_log(error, &req);
  11458. return false;
  11459. }
  11460. }
  11461. }
  11462. // Log
  11463. output_log(req, res);
  11464. return true;
  11465. }
  11466. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11467. const std::string &boundary, const UploadFormDataItems &items,
  11468. const FormDataProviderItems &provider_items) const {
  11469. size_t cur_item = 0;
  11470. size_t cur_start = 0;
  11471. // cur_item and cur_start are copied to within the std::function and
  11472. // maintain state between successive calls
  11473. return [&, cur_item, cur_start](size_t offset,
  11474. DataSink &sink) mutable -> bool {
  11475. if (!offset && !items.empty()) {
  11476. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  11477. return true;
  11478. } else if (cur_item < provider_items.size()) {
  11479. if (!cur_start) {
  11480. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  11481. provider_items[cur_item], boundary);
  11482. offset += begin.size();
  11483. cur_start = offset;
  11484. sink.os << begin;
  11485. }
  11486. DataSink cur_sink;
  11487. auto has_data = true;
  11488. cur_sink.write = sink.write;
  11489. cur_sink.done = [&]() { has_data = false; };
  11490. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  11491. return false;
  11492. }
  11493. if (!has_data) {
  11494. sink.os << detail::serialize_multipart_formdata_item_end();
  11495. cur_item++;
  11496. cur_start = 0;
  11497. }
  11498. return true;
  11499. } else {
  11500. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  11501. sink.done();
  11502. return true;
  11503. }
  11504. };
  11505. }
  11506. inline bool ClientImpl::process_socket(
  11507. const Socket &socket,
  11508. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11509. std::function<bool(Stream &strm)> callback) {
  11510. return detail::process_client_socket(
  11511. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11512. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  11513. }
  11514. inline bool ClientImpl::is_ssl() const { return false; }
  11515. inline Result ClientImpl::Get(const std::string &path,
  11516. DownloadProgress progress) {
  11517. return Get(path, Headers(), std::move(progress));
  11518. }
  11519. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11520. const Headers &headers,
  11521. DownloadProgress progress) {
  11522. if (params.empty()) { return Get(path, headers); }
  11523. std::string path_with_query = append_query_params(path, params);
  11524. return Get(path_with_query, headers, std::move(progress));
  11525. }
  11526. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11527. DownloadProgress progress) {
  11528. Request req;
  11529. req.method = "GET";
  11530. req.path = path;
  11531. req.headers = headers;
  11532. req.download_progress = std::move(progress);
  11533. if (max_timeout_msec_ > 0) {
  11534. req.start_time_ = std::chrono::steady_clock::now();
  11535. }
  11536. return send_(std::move(req));
  11537. }
  11538. inline Result ClientImpl::Get(const std::string &path,
  11539. ContentReceiver content_receiver,
  11540. DownloadProgress progress) {
  11541. return Get(path, Headers(), nullptr, std::move(content_receiver),
  11542. std::move(progress));
  11543. }
  11544. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11545. ContentReceiver content_receiver,
  11546. DownloadProgress progress) {
  11547. return Get(path, headers, nullptr, std::move(content_receiver),
  11548. std::move(progress));
  11549. }
  11550. inline Result ClientImpl::Get(const std::string &path,
  11551. ResponseHandler response_handler,
  11552. ContentReceiver content_receiver,
  11553. DownloadProgress progress) {
  11554. return Get(path, Headers(), std::move(response_handler),
  11555. std::move(content_receiver), std::move(progress));
  11556. }
  11557. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11558. ResponseHandler response_handler,
  11559. ContentReceiver content_receiver,
  11560. DownloadProgress progress) {
  11561. Request req;
  11562. req.method = "GET";
  11563. req.path = path;
  11564. req.headers = headers;
  11565. req.response_handler = std::move(response_handler);
  11566. req.content_receiver =
  11567. [content_receiver](const char *data, size_t data_length,
  11568. size_t /*offset*/, size_t /*total_length*/) {
  11569. return content_receiver(data, data_length);
  11570. };
  11571. req.download_progress = std::move(progress);
  11572. if (max_timeout_msec_ > 0) {
  11573. req.start_time_ = std::chrono::steady_clock::now();
  11574. }
  11575. return send_(std::move(req));
  11576. }
  11577. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11578. const Headers &headers,
  11579. ContentReceiver content_receiver,
  11580. DownloadProgress progress) {
  11581. return Get(path, params, headers, nullptr, std::move(content_receiver),
  11582. std::move(progress));
  11583. }
  11584. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11585. const Headers &headers,
  11586. ResponseHandler response_handler,
  11587. ContentReceiver content_receiver,
  11588. DownloadProgress progress) {
  11589. if (params.empty()) {
  11590. return Get(path, headers, std::move(response_handler),
  11591. std::move(content_receiver), std::move(progress));
  11592. }
  11593. std::string path_with_query = append_query_params(path, params);
  11594. return Get(path_with_query, headers, std::move(response_handler),
  11595. std::move(content_receiver), std::move(progress));
  11596. }
  11597. inline Result ClientImpl::Head(const std::string &path) {
  11598. return Head(path, Headers());
  11599. }
  11600. inline Result ClientImpl::Head(const std::string &path,
  11601. const Headers &headers) {
  11602. Request req;
  11603. req.method = "HEAD";
  11604. req.headers = headers;
  11605. req.path = path;
  11606. if (max_timeout_msec_ > 0) {
  11607. req.start_time_ = std::chrono::steady_clock::now();
  11608. }
  11609. return send_(std::move(req));
  11610. }
  11611. inline Result ClientImpl::Post(const std::string &path) {
  11612. return Post(path, std::string(), std::string());
  11613. }
  11614. inline Result ClientImpl::Post(const std::string &path,
  11615. const Headers &headers) {
  11616. return Post(path, headers, nullptr, 0, std::string());
  11617. }
  11618. inline Result ClientImpl::Post(const std::string &path, const char *body,
  11619. size_t content_length,
  11620. const std::string &content_type,
  11621. UploadProgress progress) {
  11622. return Post(path, Headers(), body, content_length, content_type, progress);
  11623. }
  11624. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  11625. const std::string &content_type,
  11626. UploadProgress progress) {
  11627. return Post(path, Headers(), body, content_type, progress);
  11628. }
  11629. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  11630. return Post(path, Headers(), params);
  11631. }
  11632. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11633. ContentProvider content_provider,
  11634. const std::string &content_type,
  11635. UploadProgress progress) {
  11636. return Post(path, Headers(), content_length, std::move(content_provider),
  11637. content_type, progress);
  11638. }
  11639. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11640. ContentProvider content_provider,
  11641. const std::string &content_type,
  11642. ContentReceiver content_receiver,
  11643. UploadProgress progress) {
  11644. return Post(path, Headers(), content_length, std::move(content_provider),
  11645. content_type, std::move(content_receiver), progress);
  11646. }
  11647. inline Result ClientImpl::Post(const std::string &path,
  11648. ContentProviderWithoutLength content_provider,
  11649. const std::string &content_type,
  11650. UploadProgress progress) {
  11651. return Post(path, Headers(), std::move(content_provider), content_type,
  11652. progress);
  11653. }
  11654. inline Result ClientImpl::Post(const std::string &path,
  11655. ContentProviderWithoutLength content_provider,
  11656. const std::string &content_type,
  11657. ContentReceiver content_receiver,
  11658. UploadProgress progress) {
  11659. return Post(path, Headers(), std::move(content_provider), content_type,
  11660. std::move(content_receiver), progress);
  11661. }
  11662. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11663. const Params &params) {
  11664. auto query = detail::params_to_query_str(params);
  11665. return Post(path, headers, query, "application/x-www-form-urlencoded");
  11666. }
  11667. inline Result ClientImpl::Post(const std::string &path,
  11668. const UploadFormDataItems &items,
  11669. UploadProgress progress) {
  11670. return Post(path, Headers(), items, progress);
  11671. }
  11672. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11673. const UploadFormDataItems &items,
  11674. UploadProgress progress) {
  11675. const auto &boundary = detail::make_multipart_data_boundary();
  11676. const auto &content_type =
  11677. detail::serialize_multipart_formdata_get_content_type(boundary);
  11678. auto content_length = detail::get_multipart_content_length(items, boundary);
  11679. return Post(path, headers, content_length,
  11680. detail::make_multipart_content_provider(items, boundary),
  11681. content_type, progress);
  11682. }
  11683. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11684. const UploadFormDataItems &items,
  11685. const std::string &boundary,
  11686. UploadProgress progress) {
  11687. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11688. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11689. }
  11690. const auto &content_type =
  11691. detail::serialize_multipart_formdata_get_content_type(boundary);
  11692. auto content_length = detail::get_multipart_content_length(items, boundary);
  11693. return Post(path, headers, content_length,
  11694. detail::make_multipart_content_provider(items, boundary),
  11695. content_type, progress);
  11696. }
  11697. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11698. const char *body, size_t content_length,
  11699. const std::string &content_type,
  11700. UploadProgress progress) {
  11701. return send_with_content_provider_and_receiver(
  11702. "POST", path, headers, body, content_length, nullptr, nullptr,
  11703. content_type, nullptr, progress);
  11704. }
  11705. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11706. const std::string &body,
  11707. const std::string &content_type,
  11708. UploadProgress progress) {
  11709. return send_with_content_provider_and_receiver(
  11710. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  11711. content_type, nullptr, progress);
  11712. }
  11713. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11714. size_t content_length,
  11715. ContentProvider content_provider,
  11716. const std::string &content_type,
  11717. UploadProgress progress) {
  11718. return send_with_content_provider_and_receiver(
  11719. "POST", path, headers, nullptr, content_length,
  11720. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11721. }
  11722. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11723. size_t content_length,
  11724. ContentProvider content_provider,
  11725. const std::string &content_type,
  11726. ContentReceiver content_receiver,
  11727. DownloadProgress progress) {
  11728. return send_with_content_provider_and_receiver(
  11729. "POST", path, headers, nullptr, content_length,
  11730. std::move(content_provider), nullptr, content_type,
  11731. std::move(content_receiver), std::move(progress));
  11732. }
  11733. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11734. ContentProviderWithoutLength content_provider,
  11735. const std::string &content_type,
  11736. UploadProgress progress) {
  11737. return send_with_content_provider_and_receiver(
  11738. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11739. content_type, nullptr, progress);
  11740. }
  11741. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11742. ContentProviderWithoutLength content_provider,
  11743. const std::string &content_type,
  11744. ContentReceiver content_receiver,
  11745. DownloadProgress progress) {
  11746. return send_with_content_provider_and_receiver(
  11747. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11748. content_type, std::move(content_receiver), std::move(progress));
  11749. }
  11750. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11751. const UploadFormDataItems &items,
  11752. const FormDataProviderItems &provider_items,
  11753. UploadProgress progress) {
  11754. const auto &boundary = detail::make_multipart_data_boundary();
  11755. const auto &content_type =
  11756. detail::serialize_multipart_formdata_get_content_type(boundary);
  11757. return send_with_content_provider_and_receiver(
  11758. "POST", path, headers, nullptr, 0, nullptr,
  11759. get_multipart_content_provider(boundary, items, provider_items),
  11760. content_type, nullptr, progress);
  11761. }
  11762. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11763. const std::string &body,
  11764. const std::string &content_type,
  11765. ContentReceiver content_receiver,
  11766. DownloadProgress progress) {
  11767. Request req;
  11768. req.method = "POST";
  11769. req.path = path;
  11770. req.headers = headers;
  11771. req.body = body;
  11772. req.content_receiver =
  11773. [content_receiver](const char *data, size_t data_length,
  11774. size_t /*offset*/, size_t /*total_length*/) {
  11775. return content_receiver(data, data_length);
  11776. };
  11777. req.download_progress = std::move(progress);
  11778. if (max_timeout_msec_ > 0) {
  11779. req.start_time_ = std::chrono::steady_clock::now();
  11780. }
  11781. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11782. return send_(std::move(req));
  11783. }
  11784. inline Result ClientImpl::Put(const std::string &path) {
  11785. return Put(path, std::string(), std::string());
  11786. }
  11787. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  11788. return Put(path, headers, nullptr, 0, std::string());
  11789. }
  11790. inline Result ClientImpl::Put(const std::string &path, const char *body,
  11791. size_t content_length,
  11792. const std::string &content_type,
  11793. UploadProgress progress) {
  11794. return Put(path, Headers(), body, content_length, content_type, progress);
  11795. }
  11796. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  11797. const std::string &content_type,
  11798. UploadProgress progress) {
  11799. return Put(path, Headers(), body, content_type, progress);
  11800. }
  11801. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  11802. return Put(path, Headers(), params);
  11803. }
  11804. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11805. ContentProvider content_provider,
  11806. const std::string &content_type,
  11807. UploadProgress progress) {
  11808. return Put(path, Headers(), content_length, std::move(content_provider),
  11809. content_type, progress);
  11810. }
  11811. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11812. ContentProvider content_provider,
  11813. const std::string &content_type,
  11814. ContentReceiver content_receiver,
  11815. UploadProgress progress) {
  11816. return Put(path, Headers(), content_length, std::move(content_provider),
  11817. content_type, std::move(content_receiver), progress);
  11818. }
  11819. inline Result ClientImpl::Put(const std::string &path,
  11820. ContentProviderWithoutLength content_provider,
  11821. const std::string &content_type,
  11822. UploadProgress progress) {
  11823. return Put(path, Headers(), std::move(content_provider), content_type,
  11824. progress);
  11825. }
  11826. inline Result ClientImpl::Put(const std::string &path,
  11827. ContentProviderWithoutLength content_provider,
  11828. const std::string &content_type,
  11829. ContentReceiver content_receiver,
  11830. UploadProgress progress) {
  11831. return Put(path, Headers(), std::move(content_provider), content_type,
  11832. std::move(content_receiver), progress);
  11833. }
  11834. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11835. const Params &params) {
  11836. auto query = detail::params_to_query_str(params);
  11837. return Put(path, headers, query, "application/x-www-form-urlencoded");
  11838. }
  11839. inline Result ClientImpl::Put(const std::string &path,
  11840. const UploadFormDataItems &items,
  11841. UploadProgress progress) {
  11842. return Put(path, Headers(), items, progress);
  11843. }
  11844. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11845. const UploadFormDataItems &items,
  11846. UploadProgress progress) {
  11847. const auto &boundary = detail::make_multipart_data_boundary();
  11848. const auto &content_type =
  11849. detail::serialize_multipart_formdata_get_content_type(boundary);
  11850. auto content_length = detail::get_multipart_content_length(items, boundary);
  11851. return Put(path, headers, content_length,
  11852. detail::make_multipart_content_provider(items, boundary),
  11853. content_type, progress);
  11854. }
  11855. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11856. const UploadFormDataItems &items,
  11857. const std::string &boundary,
  11858. UploadProgress progress) {
  11859. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11860. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11861. }
  11862. const auto &content_type =
  11863. detail::serialize_multipart_formdata_get_content_type(boundary);
  11864. auto content_length = detail::get_multipart_content_length(items, boundary);
  11865. return Put(path, headers, content_length,
  11866. detail::make_multipart_content_provider(items, boundary),
  11867. content_type, progress);
  11868. }
  11869. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11870. const char *body, size_t content_length,
  11871. const std::string &content_type,
  11872. UploadProgress progress) {
  11873. return send_with_content_provider_and_receiver(
  11874. "PUT", path, headers, body, content_length, nullptr, nullptr,
  11875. content_type, nullptr, progress);
  11876. }
  11877. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11878. const std::string &body,
  11879. const std::string &content_type,
  11880. UploadProgress progress) {
  11881. return send_with_content_provider_and_receiver(
  11882. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  11883. content_type, nullptr, progress);
  11884. }
  11885. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11886. size_t content_length,
  11887. ContentProvider content_provider,
  11888. const std::string &content_type,
  11889. UploadProgress progress) {
  11890. return send_with_content_provider_and_receiver(
  11891. "PUT", path, headers, nullptr, content_length,
  11892. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11893. }
  11894. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11895. size_t content_length,
  11896. ContentProvider content_provider,
  11897. const std::string &content_type,
  11898. ContentReceiver content_receiver,
  11899. UploadProgress progress) {
  11900. return send_with_content_provider_and_receiver(
  11901. "PUT", path, headers, nullptr, content_length,
  11902. std::move(content_provider), nullptr, content_type,
  11903. std::move(content_receiver), progress);
  11904. }
  11905. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11906. ContentProviderWithoutLength content_provider,
  11907. const std::string &content_type,
  11908. UploadProgress progress) {
  11909. return send_with_content_provider_and_receiver(
  11910. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11911. content_type, nullptr, progress);
  11912. }
  11913. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11914. ContentProviderWithoutLength content_provider,
  11915. const std::string &content_type,
  11916. ContentReceiver content_receiver,
  11917. UploadProgress progress) {
  11918. return send_with_content_provider_and_receiver(
  11919. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11920. content_type, std::move(content_receiver), progress);
  11921. }
  11922. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11923. const UploadFormDataItems &items,
  11924. const FormDataProviderItems &provider_items,
  11925. UploadProgress progress) {
  11926. const auto &boundary = detail::make_multipart_data_boundary();
  11927. const auto &content_type =
  11928. detail::serialize_multipart_formdata_get_content_type(boundary);
  11929. return send_with_content_provider_and_receiver(
  11930. "PUT", path, headers, nullptr, 0, nullptr,
  11931. get_multipart_content_provider(boundary, items, provider_items),
  11932. content_type, nullptr, progress);
  11933. }
  11934. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11935. const std::string &body,
  11936. const std::string &content_type,
  11937. ContentReceiver content_receiver,
  11938. DownloadProgress progress) {
  11939. Request req;
  11940. req.method = "PUT";
  11941. req.path = path;
  11942. req.headers = headers;
  11943. req.body = body;
  11944. req.content_receiver =
  11945. [content_receiver](const char *data, size_t data_length,
  11946. size_t /*offset*/, size_t /*total_length*/) {
  11947. return content_receiver(data, data_length);
  11948. };
  11949. req.download_progress = std::move(progress);
  11950. if (max_timeout_msec_ > 0) {
  11951. req.start_time_ = std::chrono::steady_clock::now();
  11952. }
  11953. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11954. return send_(std::move(req));
  11955. }
  11956. inline Result ClientImpl::Patch(const std::string &path) {
  11957. return Patch(path, std::string(), std::string());
  11958. }
  11959. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11960. UploadProgress progress) {
  11961. return Patch(path, headers, nullptr, 0, std::string(), progress);
  11962. }
  11963. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  11964. size_t content_length,
  11965. const std::string &content_type,
  11966. UploadProgress progress) {
  11967. return Patch(path, Headers(), body, content_length, content_type, progress);
  11968. }
  11969. inline Result ClientImpl::Patch(const std::string &path,
  11970. const std::string &body,
  11971. const std::string &content_type,
  11972. UploadProgress progress) {
  11973. return Patch(path, Headers(), body, content_type, progress);
  11974. }
  11975. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  11976. return Patch(path, Headers(), params);
  11977. }
  11978. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  11979. ContentProvider content_provider,
  11980. const std::string &content_type,
  11981. UploadProgress progress) {
  11982. return Patch(path, Headers(), content_length, std::move(content_provider),
  11983. content_type, progress);
  11984. }
  11985. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  11986. ContentProvider content_provider,
  11987. const std::string &content_type,
  11988. ContentReceiver content_receiver,
  11989. UploadProgress progress) {
  11990. return Patch(path, Headers(), content_length, std::move(content_provider),
  11991. content_type, std::move(content_receiver), progress);
  11992. }
  11993. inline Result ClientImpl::Patch(const std::string &path,
  11994. ContentProviderWithoutLength content_provider,
  11995. const std::string &content_type,
  11996. UploadProgress progress) {
  11997. return Patch(path, Headers(), std::move(content_provider), content_type,
  11998. progress);
  11999. }
  12000. inline Result ClientImpl::Patch(const std::string &path,
  12001. ContentProviderWithoutLength content_provider,
  12002. const std::string &content_type,
  12003. ContentReceiver content_receiver,
  12004. UploadProgress progress) {
  12005. return Patch(path, Headers(), std::move(content_provider), content_type,
  12006. std::move(content_receiver), progress);
  12007. }
  12008. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12009. const Params &params) {
  12010. auto query = detail::params_to_query_str(params);
  12011. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12012. }
  12013. inline Result ClientImpl::Patch(const std::string &path,
  12014. const UploadFormDataItems &items,
  12015. UploadProgress progress) {
  12016. return Patch(path, Headers(), items, progress);
  12017. }
  12018. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12019. const UploadFormDataItems &items,
  12020. UploadProgress progress) {
  12021. const auto &boundary = detail::make_multipart_data_boundary();
  12022. const auto &content_type =
  12023. detail::serialize_multipart_formdata_get_content_type(boundary);
  12024. auto content_length = detail::get_multipart_content_length(items, boundary);
  12025. return Patch(path, headers, content_length,
  12026. detail::make_multipart_content_provider(items, boundary),
  12027. content_type, progress);
  12028. }
  12029. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12030. const UploadFormDataItems &items,
  12031. const std::string &boundary,
  12032. UploadProgress progress) {
  12033. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12034. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12035. }
  12036. const auto &content_type =
  12037. detail::serialize_multipart_formdata_get_content_type(boundary);
  12038. auto content_length = detail::get_multipart_content_length(items, boundary);
  12039. return Patch(path, headers, content_length,
  12040. detail::make_multipart_content_provider(items, boundary),
  12041. content_type, progress);
  12042. }
  12043. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12044. const char *body, size_t content_length,
  12045. const std::string &content_type,
  12046. UploadProgress progress) {
  12047. return send_with_content_provider_and_receiver(
  12048. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12049. content_type, nullptr, progress);
  12050. }
  12051. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12052. const std::string &body,
  12053. const std::string &content_type,
  12054. UploadProgress progress) {
  12055. return send_with_content_provider_and_receiver(
  12056. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12057. content_type, nullptr, progress);
  12058. }
  12059. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12060. size_t content_length,
  12061. ContentProvider content_provider,
  12062. const std::string &content_type,
  12063. UploadProgress progress) {
  12064. return send_with_content_provider_and_receiver(
  12065. "PATCH", path, headers, nullptr, content_length,
  12066. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12067. }
  12068. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12069. size_t content_length,
  12070. ContentProvider content_provider,
  12071. const std::string &content_type,
  12072. ContentReceiver content_receiver,
  12073. UploadProgress progress) {
  12074. return send_with_content_provider_and_receiver(
  12075. "PATCH", path, headers, nullptr, content_length,
  12076. std::move(content_provider), nullptr, content_type,
  12077. std::move(content_receiver), progress);
  12078. }
  12079. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12080. ContentProviderWithoutLength content_provider,
  12081. const std::string &content_type,
  12082. UploadProgress progress) {
  12083. return send_with_content_provider_and_receiver(
  12084. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12085. content_type, nullptr, progress);
  12086. }
  12087. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12088. ContentProviderWithoutLength content_provider,
  12089. const std::string &content_type,
  12090. ContentReceiver content_receiver,
  12091. UploadProgress progress) {
  12092. return send_with_content_provider_and_receiver(
  12093. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12094. content_type, std::move(content_receiver), progress);
  12095. }
  12096. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12097. const UploadFormDataItems &items,
  12098. const FormDataProviderItems &provider_items,
  12099. UploadProgress progress) {
  12100. const auto &boundary = detail::make_multipart_data_boundary();
  12101. const auto &content_type =
  12102. detail::serialize_multipart_formdata_get_content_type(boundary);
  12103. return send_with_content_provider_and_receiver(
  12104. "PATCH", path, headers, nullptr, 0, nullptr,
  12105. get_multipart_content_provider(boundary, items, provider_items),
  12106. content_type, nullptr, progress);
  12107. }
  12108. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12109. const std::string &body,
  12110. const std::string &content_type,
  12111. ContentReceiver content_receiver,
  12112. DownloadProgress progress) {
  12113. Request req;
  12114. req.method = "PATCH";
  12115. req.path = path;
  12116. req.headers = headers;
  12117. req.body = body;
  12118. req.content_receiver =
  12119. [content_receiver](const char *data, size_t data_length,
  12120. size_t /*offset*/, size_t /*total_length*/) {
  12121. return content_receiver(data, data_length);
  12122. };
  12123. req.download_progress = std::move(progress);
  12124. if (max_timeout_msec_ > 0) {
  12125. req.start_time_ = std::chrono::steady_clock::now();
  12126. }
  12127. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12128. return send_(std::move(req));
  12129. }
  12130. inline Result ClientImpl::Delete(const std::string &path,
  12131. DownloadProgress progress) {
  12132. return Delete(path, Headers(), std::string(), std::string(), progress);
  12133. }
  12134. inline Result ClientImpl::Delete(const std::string &path,
  12135. const Headers &headers,
  12136. DownloadProgress progress) {
  12137. return Delete(path, headers, std::string(), std::string(), progress);
  12138. }
  12139. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12140. size_t content_length,
  12141. const std::string &content_type,
  12142. DownloadProgress progress) {
  12143. return Delete(path, Headers(), body, content_length, content_type, progress);
  12144. }
  12145. inline Result ClientImpl::Delete(const std::string &path,
  12146. const std::string &body,
  12147. const std::string &content_type,
  12148. DownloadProgress progress) {
  12149. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12150. progress);
  12151. }
  12152. inline Result ClientImpl::Delete(const std::string &path,
  12153. const Headers &headers,
  12154. const std::string &body,
  12155. const std::string &content_type,
  12156. DownloadProgress progress) {
  12157. return Delete(path, headers, body.data(), body.size(), content_type,
  12158. progress);
  12159. }
  12160. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12161. DownloadProgress progress) {
  12162. return Delete(path, Headers(), params, progress);
  12163. }
  12164. inline Result ClientImpl::Delete(const std::string &path,
  12165. const Headers &headers, const Params &params,
  12166. DownloadProgress progress) {
  12167. auto query = detail::params_to_query_str(params);
  12168. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12169. progress);
  12170. }
  12171. inline Result ClientImpl::Delete(const std::string &path,
  12172. const Headers &headers, const char *body,
  12173. size_t content_length,
  12174. const std::string &content_type,
  12175. DownloadProgress progress) {
  12176. Request req;
  12177. req.method = "DELETE";
  12178. req.headers = headers;
  12179. req.path = path;
  12180. req.download_progress = std::move(progress);
  12181. if (max_timeout_msec_ > 0) {
  12182. req.start_time_ = std::chrono::steady_clock::now();
  12183. }
  12184. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12185. req.body.assign(body, content_length);
  12186. return send_(std::move(req));
  12187. }
  12188. inline Result ClientImpl::Options(const std::string &path) {
  12189. return Options(path, Headers());
  12190. }
  12191. inline Result ClientImpl::Options(const std::string &path,
  12192. const Headers &headers) {
  12193. Request req;
  12194. req.method = "OPTIONS";
  12195. req.headers = headers;
  12196. req.path = path;
  12197. if (max_timeout_msec_ > 0) {
  12198. req.start_time_ = std::chrono::steady_clock::now();
  12199. }
  12200. return send_(std::move(req));
  12201. }
  12202. inline void ClientImpl::stop() {
  12203. std::lock_guard<std::mutex> guard(socket_mutex_);
  12204. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12205. // do is to shutdown_socket, so that threads using this socket suddenly
  12206. // discover they can't read/write any more and error out. Everything else
  12207. // (closing the socket, shutting ssl down) is unsafe because these actions
  12208. // are not thread-safe.
  12209. if (socket_requests_in_flight_ > 0) {
  12210. shutdown_socket(socket_);
  12211. // Aside from that, we set a flag for the socket to be closed when we're
  12212. // done.
  12213. socket_should_be_closed_when_request_is_done_ = true;
  12214. return;
  12215. }
  12216. // Otherwise, still holding the mutex, we can shut everything down ourselves
  12217. shutdown_ssl(socket_, true);
  12218. shutdown_socket(socket_);
  12219. close_socket(socket_);
  12220. }
  12221. inline std::string ClientImpl::host() const { return host_; }
  12222. inline int ClientImpl::port() const { return port_; }
  12223. inline size_t ClientImpl::is_socket_open() const {
  12224. std::lock_guard<std::mutex> guard(socket_mutex_);
  12225. return socket_.is_open();
  12226. }
  12227. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12228. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12229. connection_timeout_sec_ = sec;
  12230. connection_timeout_usec_ = usec;
  12231. }
  12232. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12233. read_timeout_sec_ = sec;
  12234. read_timeout_usec_ = usec;
  12235. }
  12236. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12237. write_timeout_sec_ = sec;
  12238. write_timeout_usec_ = usec;
  12239. }
  12240. inline void ClientImpl::set_max_timeout(time_t msec) {
  12241. max_timeout_msec_ = msec;
  12242. }
  12243. inline void ClientImpl::set_basic_auth(const std::string &username,
  12244. const std::string &password) {
  12245. basic_auth_username_ = username;
  12246. basic_auth_password_ = password;
  12247. }
  12248. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12249. bearer_token_auth_token_ = token;
  12250. }
  12251. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12252. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12253. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12254. inline void
  12255. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12256. addr_map_ = std::move(addr_map);
  12257. }
  12258. inline void ClientImpl::set_default_headers(Headers headers) {
  12259. default_headers_ = std::move(headers);
  12260. }
  12261. inline void ClientImpl::set_header_writer(
  12262. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12263. header_writer_ = writer;
  12264. }
  12265. inline void ClientImpl::set_address_family(int family) {
  12266. address_family_ = family;
  12267. }
  12268. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12269. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12270. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12271. socket_options_ = std::move(socket_options);
  12272. }
  12273. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12274. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12275. inline void ClientImpl::set_payload_max_length(size_t length) {
  12276. payload_max_length_ = length;
  12277. has_payload_max_length_ = true;
  12278. }
  12279. inline void ClientImpl::set_interface(const std::string &intf) {
  12280. interface_ = intf;
  12281. }
  12282. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12283. proxy_host_ = host;
  12284. proxy_port_ = port;
  12285. }
  12286. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12287. const std::string &password) {
  12288. proxy_basic_auth_username_ = username;
  12289. proxy_basic_auth_password_ = password;
  12290. }
  12291. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12292. proxy_bearer_token_auth_token_ = token;
  12293. }
  12294. #ifdef CPPHTTPLIB_SSL_ENABLED
  12295. inline void ClientImpl::set_digest_auth(const std::string &username,
  12296. const std::string &password) {
  12297. digest_auth_username_ = username;
  12298. digest_auth_password_ = password;
  12299. }
  12300. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12301. const std::string &ca_cert_dir_path) {
  12302. ca_cert_file_path_ = ca_cert_file_path;
  12303. ca_cert_dir_path_ = ca_cert_dir_path;
  12304. }
  12305. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12306. const std::string &password) {
  12307. proxy_digest_auth_username_ = username;
  12308. proxy_digest_auth_password_ = password;
  12309. }
  12310. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12311. server_certificate_verification_ = enabled;
  12312. }
  12313. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12314. server_hostname_verification_ = enabled;
  12315. }
  12316. #endif
  12317. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  12318. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12319. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  12320. std::size_t size) const {
  12321. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  12322. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  12323. if (!mem) { return nullptr; }
  12324. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  12325. if (!inf) { return nullptr; }
  12326. auto cts = X509_STORE_new();
  12327. if (cts) {
  12328. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  12329. auto itmp = sk_X509_INFO_value(inf, i);
  12330. if (!itmp) { continue; }
  12331. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  12332. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  12333. }
  12334. }
  12335. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  12336. return cts;
  12337. }
  12338. inline void ClientImpl::set_server_certificate_verifier(
  12339. std::function<SSLVerifierResponse(SSL *ssl)> /*verifier*/) {
  12340. // Base implementation does nothing - SSLClient overrides this
  12341. }
  12342. #endif
  12343. inline void ClientImpl::set_logger(Logger logger) {
  12344. logger_ = std::move(logger);
  12345. }
  12346. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12347. error_logger_ = std::move(error_logger);
  12348. }
  12349. /*
  12350. * SSL/TLS Common Implementation
  12351. */
  12352. inline ClientConnection::~ClientConnection() {
  12353. #ifdef CPPHTTPLIB_SSL_ENABLED
  12354. if (session) {
  12355. tls::shutdown(session, true);
  12356. tls::free_session(session);
  12357. session = nullptr;
  12358. }
  12359. #endif
  12360. if (sock != INVALID_SOCKET) {
  12361. detail::close_socket(sock);
  12362. sock = INVALID_SOCKET;
  12363. }
  12364. }
  12365. // Universal client implementation
  12366. inline Client::Client(const std::string &scheme_host_port)
  12367. : Client(scheme_host_port, std::string(), std::string()) {}
  12368. inline Client::Client(const std::string &scheme_host_port,
  12369. const std::string &client_cert_path,
  12370. const std::string &client_key_path) {
  12371. const static std::regex re(
  12372. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  12373. std::smatch m;
  12374. if (std::regex_match(scheme_host_port, m, re)) {
  12375. auto scheme = m[1].str();
  12376. #ifdef CPPHTTPLIB_SSL_ENABLED
  12377. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12378. #else
  12379. if (!scheme.empty() && scheme != "http") {
  12380. #endif
  12381. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12382. std::string msg = "'" + scheme + "' scheme is not supported.";
  12383. throw std::invalid_argument(msg);
  12384. #endif
  12385. return;
  12386. }
  12387. auto is_ssl = scheme == "https";
  12388. auto host = m[2].str();
  12389. if (host.empty()) { host = m[3].str(); }
  12390. auto port_str = m[4].str();
  12391. auto port = is_ssl ? 443 : 80;
  12392. if (!port_str.empty() && !detail::parse_port(port_str, port)) { return; }
  12393. if (is_ssl) {
  12394. #ifdef CPPHTTPLIB_SSL_ENABLED
  12395. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12396. client_key_path);
  12397. is_ssl_ = is_ssl;
  12398. #endif
  12399. } else {
  12400. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12401. client_key_path);
  12402. }
  12403. } else {
  12404. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12405. // if port param below changes.
  12406. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12407. client_cert_path, client_key_path);
  12408. }
  12409. } // namespace detail
  12410. inline Client::Client(const std::string &host, int port)
  12411. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  12412. inline Client::Client(const std::string &host, int port,
  12413. const std::string &client_cert_path,
  12414. const std::string &client_key_path)
  12415. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12416. client_key_path)) {}
  12417. inline Client::~Client() = default;
  12418. inline bool Client::is_valid() const {
  12419. return cli_ != nullptr && cli_->is_valid();
  12420. }
  12421. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12422. return cli_->Get(path, std::move(progress));
  12423. }
  12424. inline Result Client::Get(const std::string &path, const Headers &headers,
  12425. DownloadProgress progress) {
  12426. return cli_->Get(path, headers, std::move(progress));
  12427. }
  12428. inline Result Client::Get(const std::string &path,
  12429. ContentReceiver content_receiver,
  12430. DownloadProgress progress) {
  12431. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12432. }
  12433. inline Result Client::Get(const std::string &path, const Headers &headers,
  12434. ContentReceiver content_receiver,
  12435. DownloadProgress progress) {
  12436. return cli_->Get(path, headers, std::move(content_receiver),
  12437. std::move(progress));
  12438. }
  12439. inline Result Client::Get(const std::string &path,
  12440. ResponseHandler response_handler,
  12441. ContentReceiver content_receiver,
  12442. DownloadProgress progress) {
  12443. return cli_->Get(path, std::move(response_handler),
  12444. std::move(content_receiver), std::move(progress));
  12445. }
  12446. inline Result Client::Get(const std::string &path, const Headers &headers,
  12447. ResponseHandler response_handler,
  12448. ContentReceiver content_receiver,
  12449. DownloadProgress progress) {
  12450. return cli_->Get(path, headers, std::move(response_handler),
  12451. std::move(content_receiver), std::move(progress));
  12452. }
  12453. inline Result Client::Get(const std::string &path, const Params &params,
  12454. const Headers &headers, DownloadProgress progress) {
  12455. return cli_->Get(path, params, headers, std::move(progress));
  12456. }
  12457. inline Result Client::Get(const std::string &path, const Params &params,
  12458. const Headers &headers,
  12459. ContentReceiver content_receiver,
  12460. DownloadProgress progress) {
  12461. return cli_->Get(path, params, headers, std::move(content_receiver),
  12462. std::move(progress));
  12463. }
  12464. inline Result Client::Get(const std::string &path, const Params &params,
  12465. const Headers &headers,
  12466. ResponseHandler response_handler,
  12467. ContentReceiver content_receiver,
  12468. DownloadProgress progress) {
  12469. return cli_->Get(path, params, headers, std::move(response_handler),
  12470. std::move(content_receiver), std::move(progress));
  12471. }
  12472. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12473. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12474. return cli_->Head(path, headers);
  12475. }
  12476. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12477. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12478. return cli_->Post(path, headers);
  12479. }
  12480. inline Result Client::Post(const std::string &path, const char *body,
  12481. size_t content_length,
  12482. const std::string &content_type,
  12483. UploadProgress progress) {
  12484. return cli_->Post(path, body, content_length, content_type, progress);
  12485. }
  12486. inline Result Client::Post(const std::string &path, const Headers &headers,
  12487. const char *body, size_t content_length,
  12488. const std::string &content_type,
  12489. UploadProgress progress) {
  12490. return cli_->Post(path, headers, body, content_length, content_type,
  12491. progress);
  12492. }
  12493. inline Result Client::Post(const std::string &path, const std::string &body,
  12494. const std::string &content_type,
  12495. UploadProgress progress) {
  12496. return cli_->Post(path, body, content_type, progress);
  12497. }
  12498. inline Result Client::Post(const std::string &path, const Headers &headers,
  12499. const std::string &body,
  12500. const std::string &content_type,
  12501. UploadProgress progress) {
  12502. return cli_->Post(path, headers, body, content_type, progress);
  12503. }
  12504. inline Result Client::Post(const std::string &path, size_t content_length,
  12505. ContentProvider content_provider,
  12506. const std::string &content_type,
  12507. UploadProgress progress) {
  12508. return cli_->Post(path, content_length, std::move(content_provider),
  12509. content_type, progress);
  12510. }
  12511. inline Result Client::Post(const std::string &path, size_t content_length,
  12512. ContentProvider content_provider,
  12513. const std::string &content_type,
  12514. ContentReceiver content_receiver,
  12515. UploadProgress progress) {
  12516. return cli_->Post(path, content_length, std::move(content_provider),
  12517. content_type, std::move(content_receiver), progress);
  12518. }
  12519. inline Result Client::Post(const std::string &path,
  12520. ContentProviderWithoutLength content_provider,
  12521. const std::string &content_type,
  12522. UploadProgress progress) {
  12523. return cli_->Post(path, std::move(content_provider), content_type, progress);
  12524. }
  12525. inline Result Client::Post(const std::string &path,
  12526. ContentProviderWithoutLength content_provider,
  12527. const std::string &content_type,
  12528. ContentReceiver content_receiver,
  12529. UploadProgress progress) {
  12530. return cli_->Post(path, std::move(content_provider), content_type,
  12531. std::move(content_receiver), progress);
  12532. }
  12533. inline Result Client::Post(const std::string &path, const Headers &headers,
  12534. size_t content_length,
  12535. ContentProvider content_provider,
  12536. const std::string &content_type,
  12537. UploadProgress progress) {
  12538. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12539. content_type, progress);
  12540. }
  12541. inline Result Client::Post(const std::string &path, const Headers &headers,
  12542. size_t content_length,
  12543. ContentProvider content_provider,
  12544. const std::string &content_type,
  12545. ContentReceiver content_receiver,
  12546. DownloadProgress progress) {
  12547. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12548. content_type, std::move(content_receiver), progress);
  12549. }
  12550. inline Result Client::Post(const std::string &path, const Headers &headers,
  12551. ContentProviderWithoutLength content_provider,
  12552. const std::string &content_type,
  12553. UploadProgress progress) {
  12554. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12555. progress);
  12556. }
  12557. inline Result Client::Post(const std::string &path, const Headers &headers,
  12558. ContentProviderWithoutLength content_provider,
  12559. const std::string &content_type,
  12560. ContentReceiver content_receiver,
  12561. DownloadProgress progress) {
  12562. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12563. std::move(content_receiver), progress);
  12564. }
  12565. inline Result Client::Post(const std::string &path, const Params &params) {
  12566. return cli_->Post(path, params);
  12567. }
  12568. inline Result Client::Post(const std::string &path, const Headers &headers,
  12569. const Params &params) {
  12570. return cli_->Post(path, headers, params);
  12571. }
  12572. inline Result Client::Post(const std::string &path,
  12573. const UploadFormDataItems &items,
  12574. UploadProgress progress) {
  12575. return cli_->Post(path, items, progress);
  12576. }
  12577. inline Result Client::Post(const std::string &path, const Headers &headers,
  12578. const UploadFormDataItems &items,
  12579. UploadProgress progress) {
  12580. return cli_->Post(path, headers, items, progress);
  12581. }
  12582. inline Result Client::Post(const std::string &path, const Headers &headers,
  12583. const UploadFormDataItems &items,
  12584. const std::string &boundary,
  12585. UploadProgress progress) {
  12586. return cli_->Post(path, headers, items, boundary, progress);
  12587. }
  12588. inline Result Client::Post(const std::string &path, const Headers &headers,
  12589. const UploadFormDataItems &items,
  12590. const FormDataProviderItems &provider_items,
  12591. UploadProgress progress) {
  12592. return cli_->Post(path, headers, items, provider_items, progress);
  12593. }
  12594. inline Result Client::Post(const std::string &path, const Headers &headers,
  12595. const std::string &body,
  12596. const std::string &content_type,
  12597. ContentReceiver content_receiver,
  12598. DownloadProgress progress) {
  12599. return cli_->Post(path, headers, body, content_type,
  12600. std::move(content_receiver), progress);
  12601. }
  12602. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  12603. inline Result Client::Put(const std::string &path, const Headers &headers) {
  12604. return cli_->Put(path, headers);
  12605. }
  12606. inline Result Client::Put(const std::string &path, const char *body,
  12607. size_t content_length,
  12608. const std::string &content_type,
  12609. UploadProgress progress) {
  12610. return cli_->Put(path, body, content_length, content_type, progress);
  12611. }
  12612. inline Result Client::Put(const std::string &path, const Headers &headers,
  12613. const char *body, size_t content_length,
  12614. const std::string &content_type,
  12615. UploadProgress progress) {
  12616. return cli_->Put(path, headers, body, content_length, content_type, progress);
  12617. }
  12618. inline Result Client::Put(const std::string &path, const std::string &body,
  12619. const std::string &content_type,
  12620. UploadProgress progress) {
  12621. return cli_->Put(path, body, content_type, progress);
  12622. }
  12623. inline Result Client::Put(const std::string &path, const Headers &headers,
  12624. const std::string &body,
  12625. const std::string &content_type,
  12626. UploadProgress progress) {
  12627. return cli_->Put(path, headers, body, content_type, progress);
  12628. }
  12629. inline Result Client::Put(const std::string &path, size_t content_length,
  12630. ContentProvider content_provider,
  12631. const std::string &content_type,
  12632. UploadProgress progress) {
  12633. return cli_->Put(path, content_length, std::move(content_provider),
  12634. content_type, progress);
  12635. }
  12636. inline Result Client::Put(const std::string &path, size_t content_length,
  12637. ContentProvider content_provider,
  12638. const std::string &content_type,
  12639. ContentReceiver content_receiver,
  12640. UploadProgress progress) {
  12641. return cli_->Put(path, content_length, std::move(content_provider),
  12642. content_type, std::move(content_receiver), progress);
  12643. }
  12644. inline Result Client::Put(const std::string &path,
  12645. ContentProviderWithoutLength content_provider,
  12646. const std::string &content_type,
  12647. UploadProgress progress) {
  12648. return cli_->Put(path, std::move(content_provider), content_type, progress);
  12649. }
  12650. inline Result Client::Put(const std::string &path,
  12651. ContentProviderWithoutLength content_provider,
  12652. const std::string &content_type,
  12653. ContentReceiver content_receiver,
  12654. UploadProgress progress) {
  12655. return cli_->Put(path, std::move(content_provider), content_type,
  12656. std::move(content_receiver), progress);
  12657. }
  12658. inline Result Client::Put(const std::string &path, const Headers &headers,
  12659. size_t content_length,
  12660. ContentProvider content_provider,
  12661. const std::string &content_type,
  12662. UploadProgress progress) {
  12663. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12664. content_type, progress);
  12665. }
  12666. inline Result Client::Put(const std::string &path, const Headers &headers,
  12667. size_t content_length,
  12668. ContentProvider content_provider,
  12669. const std::string &content_type,
  12670. ContentReceiver content_receiver,
  12671. UploadProgress progress) {
  12672. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12673. content_type, std::move(content_receiver), progress);
  12674. }
  12675. inline Result Client::Put(const std::string &path, const Headers &headers,
  12676. ContentProviderWithoutLength content_provider,
  12677. const std::string &content_type,
  12678. UploadProgress progress) {
  12679. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12680. progress);
  12681. }
  12682. inline Result Client::Put(const std::string &path, const Headers &headers,
  12683. ContentProviderWithoutLength content_provider,
  12684. const std::string &content_type,
  12685. ContentReceiver content_receiver,
  12686. UploadProgress progress) {
  12687. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12688. std::move(content_receiver), progress);
  12689. }
  12690. inline Result Client::Put(const std::string &path, const Params &params) {
  12691. return cli_->Put(path, params);
  12692. }
  12693. inline Result Client::Put(const std::string &path, const Headers &headers,
  12694. const Params &params) {
  12695. return cli_->Put(path, headers, params);
  12696. }
  12697. inline Result Client::Put(const std::string &path,
  12698. const UploadFormDataItems &items,
  12699. UploadProgress progress) {
  12700. return cli_->Put(path, items, progress);
  12701. }
  12702. inline Result Client::Put(const std::string &path, const Headers &headers,
  12703. const UploadFormDataItems &items,
  12704. UploadProgress progress) {
  12705. return cli_->Put(path, headers, items, progress);
  12706. }
  12707. inline Result Client::Put(const std::string &path, const Headers &headers,
  12708. const UploadFormDataItems &items,
  12709. const std::string &boundary,
  12710. UploadProgress progress) {
  12711. return cli_->Put(path, headers, items, boundary, progress);
  12712. }
  12713. inline Result Client::Put(const std::string &path, const Headers &headers,
  12714. const UploadFormDataItems &items,
  12715. const FormDataProviderItems &provider_items,
  12716. UploadProgress progress) {
  12717. return cli_->Put(path, headers, items, provider_items, progress);
  12718. }
  12719. inline Result Client::Put(const std::string &path, const Headers &headers,
  12720. const std::string &body,
  12721. const std::string &content_type,
  12722. ContentReceiver content_receiver,
  12723. DownloadProgress progress) {
  12724. return cli_->Put(path, headers, body, content_type, content_receiver,
  12725. progress);
  12726. }
  12727. inline Result Client::Patch(const std::string &path) {
  12728. return cli_->Patch(path);
  12729. }
  12730. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  12731. return cli_->Patch(path, headers);
  12732. }
  12733. inline Result Client::Patch(const std::string &path, const char *body,
  12734. size_t content_length,
  12735. const std::string &content_type,
  12736. UploadProgress progress) {
  12737. return cli_->Patch(path, body, content_length, content_type, progress);
  12738. }
  12739. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12740. const char *body, size_t content_length,
  12741. const std::string &content_type,
  12742. UploadProgress progress) {
  12743. return cli_->Patch(path, headers, body, content_length, content_type,
  12744. progress);
  12745. }
  12746. inline Result Client::Patch(const std::string &path, const std::string &body,
  12747. const std::string &content_type,
  12748. UploadProgress progress) {
  12749. return cli_->Patch(path, body, content_type, progress);
  12750. }
  12751. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12752. const std::string &body,
  12753. const std::string &content_type,
  12754. UploadProgress progress) {
  12755. return cli_->Patch(path, headers, body, content_type, progress);
  12756. }
  12757. inline Result Client::Patch(const std::string &path, size_t content_length,
  12758. ContentProvider content_provider,
  12759. const std::string &content_type,
  12760. UploadProgress progress) {
  12761. return cli_->Patch(path, content_length, std::move(content_provider),
  12762. content_type, progress);
  12763. }
  12764. inline Result Client::Patch(const std::string &path, size_t content_length,
  12765. ContentProvider content_provider,
  12766. const std::string &content_type,
  12767. ContentReceiver content_receiver,
  12768. UploadProgress progress) {
  12769. return cli_->Patch(path, content_length, std::move(content_provider),
  12770. content_type, std::move(content_receiver), progress);
  12771. }
  12772. inline Result Client::Patch(const std::string &path,
  12773. ContentProviderWithoutLength content_provider,
  12774. const std::string &content_type,
  12775. UploadProgress progress) {
  12776. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  12777. }
  12778. inline Result Client::Patch(const std::string &path,
  12779. ContentProviderWithoutLength content_provider,
  12780. const std::string &content_type,
  12781. ContentReceiver content_receiver,
  12782. UploadProgress progress) {
  12783. return cli_->Patch(path, std::move(content_provider), content_type,
  12784. std::move(content_receiver), progress);
  12785. }
  12786. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12787. size_t content_length,
  12788. ContentProvider content_provider,
  12789. const std::string &content_type,
  12790. UploadProgress progress) {
  12791. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12792. content_type, progress);
  12793. }
  12794. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12795. size_t content_length,
  12796. ContentProvider content_provider,
  12797. const std::string &content_type,
  12798. ContentReceiver content_receiver,
  12799. UploadProgress progress) {
  12800. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12801. content_type, std::move(content_receiver), progress);
  12802. }
  12803. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12804. ContentProviderWithoutLength content_provider,
  12805. const std::string &content_type,
  12806. UploadProgress progress) {
  12807. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12808. progress);
  12809. }
  12810. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12811. ContentProviderWithoutLength content_provider,
  12812. const std::string &content_type,
  12813. ContentReceiver content_receiver,
  12814. UploadProgress progress) {
  12815. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12816. std::move(content_receiver), progress);
  12817. }
  12818. inline Result Client::Patch(const std::string &path, const Params &params) {
  12819. return cli_->Patch(path, params);
  12820. }
  12821. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12822. const Params &params) {
  12823. return cli_->Patch(path, headers, params);
  12824. }
  12825. inline Result Client::Patch(const std::string &path,
  12826. const UploadFormDataItems &items,
  12827. UploadProgress progress) {
  12828. return cli_->Patch(path, items, progress);
  12829. }
  12830. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12831. const UploadFormDataItems &items,
  12832. UploadProgress progress) {
  12833. return cli_->Patch(path, headers, items, progress);
  12834. }
  12835. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12836. const UploadFormDataItems &items,
  12837. const std::string &boundary,
  12838. UploadProgress progress) {
  12839. return cli_->Patch(path, headers, items, boundary, progress);
  12840. }
  12841. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12842. const UploadFormDataItems &items,
  12843. const FormDataProviderItems &provider_items,
  12844. UploadProgress progress) {
  12845. return cli_->Patch(path, headers, items, provider_items, progress);
  12846. }
  12847. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12848. const std::string &body,
  12849. const std::string &content_type,
  12850. ContentReceiver content_receiver,
  12851. DownloadProgress progress) {
  12852. return cli_->Patch(path, headers, body, content_type, content_receiver,
  12853. progress);
  12854. }
  12855. inline Result Client::Delete(const std::string &path,
  12856. DownloadProgress progress) {
  12857. return cli_->Delete(path, progress);
  12858. }
  12859. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12860. DownloadProgress progress) {
  12861. return cli_->Delete(path, headers, progress);
  12862. }
  12863. inline Result Client::Delete(const std::string &path, const char *body,
  12864. size_t content_length,
  12865. const std::string &content_type,
  12866. DownloadProgress progress) {
  12867. return cli_->Delete(path, body, content_length, content_type, progress);
  12868. }
  12869. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12870. const char *body, size_t content_length,
  12871. const std::string &content_type,
  12872. DownloadProgress progress) {
  12873. return cli_->Delete(path, headers, body, content_length, content_type,
  12874. progress);
  12875. }
  12876. inline Result Client::Delete(const std::string &path, const std::string &body,
  12877. const std::string &content_type,
  12878. DownloadProgress progress) {
  12879. return cli_->Delete(path, body, content_type, progress);
  12880. }
  12881. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12882. const std::string &body,
  12883. const std::string &content_type,
  12884. DownloadProgress progress) {
  12885. return cli_->Delete(path, headers, body, content_type, progress);
  12886. }
  12887. inline Result Client::Delete(const std::string &path, const Params &params,
  12888. DownloadProgress progress) {
  12889. return cli_->Delete(path, params, progress);
  12890. }
  12891. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12892. const Params &params, DownloadProgress progress) {
  12893. return cli_->Delete(path, headers, params, progress);
  12894. }
  12895. inline Result Client::Options(const std::string &path) {
  12896. return cli_->Options(path);
  12897. }
  12898. inline Result Client::Options(const std::string &path, const Headers &headers) {
  12899. return cli_->Options(path, headers);
  12900. }
  12901. inline ClientImpl::StreamHandle
  12902. Client::open_stream(const std::string &method, const std::string &path,
  12903. const Params &params, const Headers &headers,
  12904. const std::string &body, const std::string &content_type) {
  12905. return cli_->open_stream(method, path, params, headers, body, content_type);
  12906. }
  12907. inline bool Client::send(Request &req, Response &res, Error &error) {
  12908. return cli_->send(req, res, error);
  12909. }
  12910. inline Result Client::send(const Request &req) { return cli_->send(req); }
  12911. inline void Client::stop() { cli_->stop(); }
  12912. inline std::string Client::host() const { return cli_->host(); }
  12913. inline int Client::port() const { return cli_->port(); }
  12914. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  12915. inline socket_t Client::socket() const { return cli_->socket(); }
  12916. inline void
  12917. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12918. cli_->set_hostname_addr_map(std::move(addr_map));
  12919. }
  12920. inline void Client::set_default_headers(Headers headers) {
  12921. cli_->set_default_headers(std::move(headers));
  12922. }
  12923. inline void Client::set_header_writer(
  12924. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12925. cli_->set_header_writer(writer);
  12926. }
  12927. inline void Client::set_address_family(int family) {
  12928. cli_->set_address_family(family);
  12929. }
  12930. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  12931. inline void Client::set_socket_options(SocketOptions socket_options) {
  12932. cli_->set_socket_options(std::move(socket_options));
  12933. }
  12934. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  12935. cli_->set_connection_timeout(sec, usec);
  12936. }
  12937. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  12938. cli_->set_read_timeout(sec, usec);
  12939. }
  12940. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  12941. cli_->set_write_timeout(sec, usec);
  12942. }
  12943. inline void Client::set_basic_auth(const std::string &username,
  12944. const std::string &password) {
  12945. cli_->set_basic_auth(username, password);
  12946. }
  12947. inline void Client::set_bearer_token_auth(const std::string &token) {
  12948. cli_->set_bearer_token_auth(token);
  12949. }
  12950. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  12951. inline void Client::set_follow_location(bool on) {
  12952. cli_->set_follow_location(on);
  12953. }
  12954. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  12955. [[deprecated("Use set_path_encode() instead. "
  12956. "This function will be removed by v1.0.0.")]]
  12957. inline void Client::set_url_encode(bool on) {
  12958. cli_->set_path_encode(on);
  12959. }
  12960. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  12961. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  12962. inline void Client::set_payload_max_length(size_t length) {
  12963. cli_->set_payload_max_length(length);
  12964. }
  12965. inline void Client::set_interface(const std::string &intf) {
  12966. cli_->set_interface(intf);
  12967. }
  12968. inline void Client::set_proxy(const std::string &host, int port) {
  12969. cli_->set_proxy(host, port);
  12970. }
  12971. inline void Client::set_proxy_basic_auth(const std::string &username,
  12972. const std::string &password) {
  12973. cli_->set_proxy_basic_auth(username, password);
  12974. }
  12975. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  12976. cli_->set_proxy_bearer_token_auth(token);
  12977. }
  12978. inline void Client::set_logger(Logger logger) {
  12979. cli_->set_logger(std::move(logger));
  12980. }
  12981. inline void Client::set_error_logger(ErrorLogger error_logger) {
  12982. cli_->set_error_logger(std::move(error_logger));
  12983. }
  12984. /*
  12985. * Group 6: SSL Server and Client implementation
  12986. */
  12987. #ifdef CPPHTTPLIB_SSL_ENABLED
  12988. // SSL HTTP server implementation
  12989. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  12990. const char *client_ca_cert_file_path,
  12991. const char *client_ca_cert_dir_path,
  12992. const char *private_key_password) {
  12993. using namespace tls;
  12994. ctx_ = create_server_context();
  12995. if (!ctx_) { return; }
  12996. // Load server certificate and private key
  12997. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  12998. private_key_password)) {
  12999. last_ssl_error_ = static_cast<int>(get_error());
  13000. free_context(ctx_);
  13001. ctx_ = nullptr;
  13002. return;
  13003. }
  13004. // Load client CA certificates for client authentication
  13005. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13006. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13007. client_ca_cert_dir_path)) {
  13008. last_ssl_error_ = static_cast<int>(get_error());
  13009. free_context(ctx_);
  13010. ctx_ = nullptr;
  13011. return;
  13012. }
  13013. // Enable client certificate verification
  13014. set_verify_client(ctx_, true);
  13015. }
  13016. }
  13017. inline SSLServer::SSLServer(const PemMemory &pem) {
  13018. using namespace tls;
  13019. ctx_ = create_server_context();
  13020. if (ctx_) {
  13021. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13022. pem.private_key_password)) {
  13023. last_ssl_error_ = static_cast<int>(get_error());
  13024. free_context(ctx_);
  13025. ctx_ = nullptr;
  13026. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13027. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13028. last_ssl_error_ = static_cast<int>(get_error());
  13029. free_context(ctx_);
  13030. ctx_ = nullptr;
  13031. } else {
  13032. set_verify_client(ctx_, true);
  13033. }
  13034. }
  13035. }
  13036. }
  13037. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13038. using namespace tls;
  13039. ctx_ = create_server_context();
  13040. if (ctx_) {
  13041. if (!setup_callback(ctx_)) {
  13042. free_context(ctx_);
  13043. ctx_ = nullptr;
  13044. }
  13045. }
  13046. }
  13047. inline SSLServer::~SSLServer() {
  13048. if (ctx_) { tls::free_context(ctx_); }
  13049. }
  13050. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13051. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13052. using namespace tls;
  13053. // Create TLS session with mutex protection
  13054. session_t session = nullptr;
  13055. {
  13056. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13057. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13058. }
  13059. if (!session) {
  13060. last_ssl_error_ = static_cast<int>(get_error());
  13061. detail::shutdown_socket(sock);
  13062. detail::close_socket(sock);
  13063. return false;
  13064. }
  13065. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13066. bool handshake_done = false;
  13067. bool ret = false;
  13068. bool websocket_upgraded = false;
  13069. auto cleanup = detail::scope_exit([&] {
  13070. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13071. free_session(session);
  13072. detail::shutdown_socket(sock);
  13073. detail::close_socket(sock);
  13074. });
  13075. // Perform TLS accept handshake with timeout
  13076. TlsError tls_err;
  13077. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13078. &tls_err)) {
  13079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13080. // Map TlsError to legacy ssl_error for backward compatibility
  13081. if (tls_err.code == ErrorCode::WantRead) {
  13082. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13083. } else if (tls_err.code == ErrorCode::WantWrite) {
  13084. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13085. } else {
  13086. last_ssl_error_ = SSL_ERROR_SSL;
  13087. }
  13088. #else
  13089. last_ssl_error_ = static_cast<int>(get_error());
  13090. #endif
  13091. return false;
  13092. }
  13093. handshake_done = true;
  13094. std::string remote_addr;
  13095. int remote_port = 0;
  13096. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13097. std::string local_addr;
  13098. int local_port = 0;
  13099. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13100. ret = detail::process_server_socket_ssl(
  13101. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13102. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13103. write_timeout_usec_,
  13104. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13105. return process_request(
  13106. strm, remote_addr, remote_port, local_addr, local_port,
  13107. close_connection, connection_closed,
  13108. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13109. });
  13110. return ret;
  13111. }
  13112. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13113. const char *key_pem,
  13114. const char *client_ca_pem,
  13115. const char *password) {
  13116. if (!ctx_) { return false; }
  13117. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13118. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13119. return false;
  13120. }
  13121. if (client_ca_pem) {
  13122. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13123. }
  13124. return true;
  13125. }
  13126. // SSL HTTP client implementation
  13127. inline SSLClient::~SSLClient() {
  13128. if (ctx_) { tls::free_context(ctx_); }
  13129. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13130. // base function rather than the derived function once we get to the
  13131. // base class destructor, and won't free the SSL (causing a leak).
  13132. shutdown_ssl_impl(socket_, true);
  13133. }
  13134. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13135. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13136. shutdown_ssl_impl(socket, shutdown_gracefully);
  13137. }
  13138. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13139. bool shutdown_gracefully) {
  13140. if (socket.sock == INVALID_SOCKET) {
  13141. assert(socket.ssl == nullptr);
  13142. return;
  13143. }
  13144. if (socket.ssl) {
  13145. tls::shutdown(socket.ssl, shutdown_gracefully);
  13146. {
  13147. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13148. tls::free_session(socket.ssl);
  13149. }
  13150. socket.ssl = nullptr;
  13151. }
  13152. assert(socket.ssl == nullptr);
  13153. }
  13154. inline bool SSLClient::process_socket(
  13155. const Socket &socket,
  13156. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13157. std::function<bool(Stream &strm)> callback) {
  13158. assert(socket.ssl);
  13159. return detail::process_client_socket_ssl(
  13160. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13161. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13162. std::move(callback));
  13163. }
  13164. inline bool SSLClient::is_ssl() const { return true; }
  13165. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13166. if (!is_valid()) {
  13167. error = Error::SSLConnection;
  13168. return false;
  13169. }
  13170. return ClientImpl::create_and_connect_socket(socket, error);
  13171. }
  13172. inline bool SSLClient::setup_proxy_connection(
  13173. Socket &socket,
  13174. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13175. Response &res, bool &success, Error &error) {
  13176. if (proxy_host_.empty() || proxy_port_ == -1) { return true; }
  13177. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13178. return false;
  13179. }
  13180. if (!initialize_ssl(socket, error)) {
  13181. success = false;
  13182. return false;
  13183. }
  13184. return true;
  13185. }
  13186. // Assumes that socket_mutex_ is locked and that there are no requests in
  13187. // flight
  13188. inline bool SSLClient::connect_with_proxy(
  13189. Socket &socket,
  13190. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13191. Response &res, bool &success, Error &error) {
  13192. success = true;
  13193. Response proxy_res;
  13194. if (!detail::process_client_socket(
  13195. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13196. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13197. start_time, [&](Stream &strm) {
  13198. Request req2;
  13199. req2.method = "CONNECT";
  13200. req2.path =
  13201. detail::make_host_and_port_string_always_port(host_, port_);
  13202. if (max_timeout_msec_ > 0) {
  13203. req2.start_time_ = std::chrono::steady_clock::now();
  13204. }
  13205. return process_request(strm, req2, proxy_res, false, error);
  13206. })) {
  13207. // Thread-safe to close everything because we are assuming there are no
  13208. // requests in flight
  13209. shutdown_ssl(socket, true);
  13210. shutdown_socket(socket);
  13211. close_socket(socket);
  13212. success = false;
  13213. return false;
  13214. }
  13215. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13216. if (!proxy_digest_auth_username_.empty() &&
  13217. !proxy_digest_auth_password_.empty()) {
  13218. std::map<std::string, std::string> auth;
  13219. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13220. // Close the current socket and create a new one for the authenticated
  13221. // request
  13222. shutdown_ssl(socket, true);
  13223. shutdown_socket(socket);
  13224. close_socket(socket);
  13225. // Create a new socket for the authenticated CONNECT request
  13226. if (!ensure_socket_connection(socket, error)) {
  13227. success = false;
  13228. output_error_log(error, nullptr);
  13229. return false;
  13230. }
  13231. proxy_res = Response();
  13232. if (!detail::process_client_socket(
  13233. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13234. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13235. start_time, [&](Stream &strm) {
  13236. Request req3;
  13237. req3.method = "CONNECT";
  13238. req3.path = detail::make_host_and_port_string_always_port(
  13239. host_, port_);
  13240. req3.headers.insert(detail::make_digest_authentication_header(
  13241. req3, auth, 1, detail::random_string(10),
  13242. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13243. true));
  13244. if (max_timeout_msec_ > 0) {
  13245. req3.start_time_ = std::chrono::steady_clock::now();
  13246. }
  13247. return process_request(strm, req3, proxy_res, false, error);
  13248. })) {
  13249. // Thread-safe to close everything because we are assuming there are
  13250. // no requests in flight
  13251. shutdown_ssl(socket, true);
  13252. shutdown_socket(socket);
  13253. close_socket(socket);
  13254. success = false;
  13255. return false;
  13256. }
  13257. }
  13258. }
  13259. }
  13260. // If status code is not 200, proxy request is failed.
  13261. // Set error to ProxyConnection and return proxy response
  13262. // as the response of the request
  13263. if (proxy_res.status != StatusCode::OK_200) {
  13264. error = Error::ProxyConnection;
  13265. output_error_log(error, nullptr);
  13266. res = std::move(proxy_res);
  13267. // Thread-safe to close everything because we are assuming there are
  13268. // no requests in flight
  13269. shutdown_ssl(socket, true);
  13270. shutdown_socket(socket);
  13271. close_socket(socket);
  13272. return false;
  13273. }
  13274. return true;
  13275. }
  13276. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13277. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13278. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  13279. if (!initialize_ssl(socket, error)) {
  13280. shutdown_socket(socket);
  13281. close_socket(socket);
  13282. return false;
  13283. }
  13284. return true;
  13285. }
  13286. // SSL HTTP client implementation
  13287. inline SSLClient::SSLClient(const std::string &host)
  13288. : SSLClient(host, 443, std::string(), std::string()) {}
  13289. inline SSLClient::SSLClient(const std::string &host, int port)
  13290. : SSLClient(host, port, std::string(), std::string()) {}
  13291. inline SSLClient::SSLClient(const std::string &host, int port,
  13292. const std::string &client_cert_path,
  13293. const std::string &client_key_path,
  13294. const std::string &private_key_password)
  13295. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13296. ctx_ = tls::create_client_context();
  13297. if (!ctx_) { return; }
  13298. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  13299. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13300. const char *password =
  13301. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13302. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13303. client_key_path.c_str(), password)) {
  13304. last_backend_error_ = tls::get_error();
  13305. tls::free_context(ctx_);
  13306. ctx_ = nullptr;
  13307. }
  13308. }
  13309. }
  13310. inline SSLClient::SSLClient(const std::string &host, int port,
  13311. const PemMemory &pem)
  13312. : ClientImpl(host, port) {
  13313. ctx_ = tls::create_client_context();
  13314. if (!ctx_) { return; }
  13315. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  13316. if (pem.cert_pem && pem.key_pem) {
  13317. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13318. pem.private_key_password)) {
  13319. last_backend_error_ = tls::get_error();
  13320. tls::free_context(ctx_);
  13321. ctx_ = nullptr;
  13322. }
  13323. }
  13324. }
  13325. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13326. if (ca_cert_store && ctx_) {
  13327. // set_ca_store takes ownership of ca_cert_store
  13328. tls::set_ca_store(ctx_, ca_cert_store);
  13329. } else if (ca_cert_store) {
  13330. tls::free_ca_store(ca_cert_store);
  13331. }
  13332. }
  13333. inline void
  13334. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13335. if (!ctx_) { return; }
  13336. tls::set_verify_callback(ctx_, verifier);
  13337. }
  13338. inline void SSLClient::set_session_verifier(
  13339. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13340. session_verifier_ = std::move(verifier);
  13341. }
  13342. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13343. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13344. enable_windows_cert_verification_ = enabled;
  13345. }
  13346. #endif
  13347. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13348. std::size_t size) {
  13349. if (ctx_ && ca_cert && size > 0) {
  13350. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13351. tls::load_ca_pem(ctx_, ca_cert, size);
  13352. }
  13353. }
  13354. inline bool SSLClient::load_certs() {
  13355. auto ret = true;
  13356. std::call_once(initialize_cert_, [&]() {
  13357. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13358. if (!ca_cert_file_path_.empty()) {
  13359. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13360. last_backend_error_ = tls::get_error();
  13361. ret = false;
  13362. }
  13363. } else if (!ca_cert_dir_path_.empty()) {
  13364. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13365. last_backend_error_ = tls::get_error();
  13366. ret = false;
  13367. }
  13368. } else if (ca_cert_pem_.empty()) {
  13369. if (!tls::load_system_certs(ctx_)) {
  13370. last_backend_error_ = tls::get_error();
  13371. }
  13372. }
  13373. });
  13374. return ret;
  13375. }
  13376. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13377. using namespace tls;
  13378. // Load CA certificates if server verification is enabled
  13379. if (server_certificate_verification_) {
  13380. if (!load_certs()) {
  13381. error = Error::SSLLoadingCerts;
  13382. output_error_log(error, nullptr);
  13383. return false;
  13384. }
  13385. }
  13386. bool is_ip = detail::is_ip_address(host_);
  13387. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13388. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13389. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13390. // For IP addresses with verification enabled, use OPTIONAL mode since
  13391. // these backends require hostname for strict verification.
  13392. if (is_ip && server_certificate_verification_) {
  13393. set_verify_client(ctx_, false);
  13394. } else {
  13395. set_verify_client(ctx_, server_certificate_verification_);
  13396. }
  13397. #endif
  13398. // Create TLS session
  13399. session_t session = nullptr;
  13400. {
  13401. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13402. session = create_session(ctx_, socket.sock);
  13403. }
  13404. if (!session) {
  13405. error = Error::SSLConnection;
  13406. last_backend_error_ = get_error();
  13407. return false;
  13408. }
  13409. // Use scope_exit to ensure session is freed on error paths
  13410. bool success = false;
  13411. auto session_guard = detail::scope_exit([&] {
  13412. if (!success) { free_session(session); }
  13413. });
  13414. // Set SNI extension (skip for IP addresses per RFC 6066).
  13415. // On MbedTLS, set_sni also enables hostname verification internally.
  13416. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13417. if (!is_ip) {
  13418. if (!set_sni(session, host_.c_str())) {
  13419. error = Error::SSLConnection;
  13420. last_backend_error_ = get_error();
  13421. return false;
  13422. }
  13423. }
  13424. // Perform non-blocking TLS handshake with timeout
  13425. TlsError tls_err;
  13426. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13427. connection_timeout_usec_, &tls_err)) {
  13428. last_ssl_error_ = static_cast<int>(tls_err.code);
  13429. last_backend_error_ = tls_err.backend_code;
  13430. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13431. error = Error::SSLServerVerification;
  13432. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13433. error = Error::SSLServerHostnameVerification;
  13434. } else {
  13435. error = Error::SSLConnection;
  13436. }
  13437. output_error_log(error, nullptr);
  13438. return false;
  13439. }
  13440. // Post-handshake session verifier callback
  13441. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13442. if (session_verifier_) { verification_status = session_verifier_(session); }
  13443. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13444. last_backend_error_ = get_error();
  13445. error = Error::SSLServerVerification;
  13446. output_error_log(error, nullptr);
  13447. return false;
  13448. }
  13449. // Default server certificate verification
  13450. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13451. server_certificate_verification_) {
  13452. verify_result_ = tls::get_verify_result(session);
  13453. if (verify_result_ != 0) {
  13454. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13455. error = Error::SSLServerVerification;
  13456. output_error_log(error, nullptr);
  13457. return false;
  13458. }
  13459. auto server_cert = get_peer_cert(session);
  13460. if (!server_cert) {
  13461. last_backend_error_ = get_error();
  13462. error = Error::SSLServerVerification;
  13463. output_error_log(error, nullptr);
  13464. return false;
  13465. }
  13466. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13467. // Hostname verification (post-handshake for all cases).
  13468. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13469. // On MbedTLS, set_sni already enabled hostname verification during
  13470. // handshake for non-IP hosts, but this check is still needed for IP
  13471. // addresses where SNI is not set.
  13472. if (server_hostname_verification_) {
  13473. if (!verify_hostname(server_cert, host_.c_str())) {
  13474. last_backend_error_ = hostname_mismatch_code();
  13475. error = Error::SSLServerHostnameVerification;
  13476. output_error_log(error, nullptr);
  13477. return false;
  13478. }
  13479. }
  13480. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13481. // Additional Windows Schannel verification.
  13482. // This provides real-time certificate validation with Windows Update
  13483. // integration, working with both OpenSSL and MbedTLS backends.
  13484. // Skip when a custom CA cert is specified, as the Windows certificate
  13485. // store would not know about user-provided CA certificates.
  13486. if (enable_windows_cert_verification_ && ca_cert_file_path_.empty() &&
  13487. ca_cert_dir_path_.empty() && ca_cert_pem_.empty()) {
  13488. std::vector<unsigned char> der;
  13489. if (get_cert_der(server_cert, der)) {
  13490. uint64_t wincrypt_error = 0;
  13491. if (!detail::verify_cert_with_windows_schannel(
  13492. der, host_, server_hostname_verification_, wincrypt_error)) {
  13493. last_backend_error_ = wincrypt_error;
  13494. error = Error::SSLServerVerification;
  13495. output_error_log(error, nullptr);
  13496. return false;
  13497. }
  13498. }
  13499. }
  13500. #endif
  13501. }
  13502. success = true;
  13503. socket.ssl = session;
  13504. return true;
  13505. }
  13506. inline void Client::set_digest_auth(const std::string &username,
  13507. const std::string &password) {
  13508. cli_->set_digest_auth(username, password);
  13509. }
  13510. inline void Client::set_proxy_digest_auth(const std::string &username,
  13511. const std::string &password) {
  13512. cli_->set_proxy_digest_auth(username, password);
  13513. }
  13514. inline void Client::enable_server_certificate_verification(bool enabled) {
  13515. cli_->enable_server_certificate_verification(enabled);
  13516. }
  13517. inline void Client::enable_server_hostname_verification(bool enabled) {
  13518. cli_->enable_server_hostname_verification(enabled);
  13519. }
  13520. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13521. inline void Client::enable_windows_certificate_verification(bool enabled) {
  13522. if (is_ssl_) {
  13523. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  13524. enabled);
  13525. }
  13526. }
  13527. #endif
  13528. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  13529. const std::string &ca_cert_dir_path) {
  13530. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  13531. }
  13532. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13533. if (is_ssl_) {
  13534. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  13535. } else if (ca_cert_store) {
  13536. tls::free_ca_store(ca_cert_store);
  13537. }
  13538. }
  13539. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  13540. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  13541. }
  13542. inline void
  13543. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13544. if (is_ssl_) {
  13545. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  13546. std::move(verifier));
  13547. }
  13548. }
  13549. inline void Client::set_session_verifier(
  13550. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13551. if (is_ssl_) {
  13552. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  13553. }
  13554. }
  13555. inline tls::ctx_t Client::tls_context() const {
  13556. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  13557. return nullptr;
  13558. }
  13559. #endif // CPPHTTPLIB_SSL_ENABLED
  13560. /*
  13561. * Group 7: TLS abstraction layer - Common API
  13562. */
  13563. #ifdef CPPHTTPLIB_SSL_ENABLED
  13564. namespace tls {
  13565. // Helper for PeerCert construction
  13566. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  13567. return PeerCert(get_peer_cert(session));
  13568. }
  13569. namespace impl {
  13570. inline VerifyCallback &get_verify_callback() {
  13571. static thread_local VerifyCallback callback;
  13572. return callback;
  13573. }
  13574. inline VerifyCallback &get_mbedtls_verify_callback() {
  13575. static thread_local VerifyCallback callback;
  13576. return callback;
  13577. }
  13578. // Check if a string is an IPv4 address
  13579. inline bool is_ipv4_address(const std::string &str) {
  13580. int dots = 0;
  13581. for (char c : str) {
  13582. if (c == '.') {
  13583. dots++;
  13584. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13585. return false;
  13586. }
  13587. }
  13588. return dots == 3;
  13589. }
  13590. // Parse IPv4 address string to bytes
  13591. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13592. const char *p = str.c_str();
  13593. for (int i = 0; i < 4; i++) {
  13594. if (i > 0) {
  13595. if (*p != '.') { return false; }
  13596. p++;
  13597. }
  13598. int val = 0;
  13599. int digits = 0;
  13600. while (*p >= '0' && *p <= '9') {
  13601. val = val * 10 + (*p - '0');
  13602. if (val > 255) { return false; }
  13603. p++;
  13604. digits++;
  13605. }
  13606. if (digits == 0) { return false; }
  13607. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  13608. if (digits > 1 && *(p - digits) == '0') { return false; }
  13609. out[i] = static_cast<unsigned char>(val);
  13610. }
  13611. return *p == '\0';
  13612. }
  13613. #ifdef _WIN32
  13614. // Enumerate Windows system certificates and call callback with DER data
  13615. template <typename Callback>
  13616. inline bool enumerate_windows_system_certs(Callback cb) {
  13617. bool loaded = false;
  13618. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13619. for (auto store_name : store_names) {
  13620. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  13621. if (hStore) {
  13622. PCCERT_CONTEXT pContext = nullptr;
  13623. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13624. nullptr) {
  13625. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  13626. loaded = true;
  13627. }
  13628. }
  13629. CertCloseStore(hStore, 0);
  13630. }
  13631. }
  13632. return loaded;
  13633. }
  13634. #endif
  13635. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  13636. // Enumerate macOS Keychain certificates and call callback with DER data
  13637. template <typename Callback>
  13638. inline bool enumerate_macos_keychain_certs(Callback cb) {
  13639. bool loaded = false;
  13640. CFArrayRef certs = nullptr;
  13641. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13642. if (status == errSecSuccess && certs) {
  13643. CFIndex count = CFArrayGetCount(certs);
  13644. for (CFIndex i = 0; i < count; i++) {
  13645. SecCertificateRef cert =
  13646. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13647. CFDataRef data = SecCertificateCopyData(cert);
  13648. if (data) {
  13649. if (cb(CFDataGetBytePtr(data),
  13650. static_cast<size_t>(CFDataGetLength(data)))) {
  13651. loaded = true;
  13652. }
  13653. CFRelease(data);
  13654. }
  13655. }
  13656. CFRelease(certs);
  13657. }
  13658. return loaded;
  13659. }
  13660. #endif
  13661. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  13662. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  13663. // Common CA certificate file paths on Linux/Unix
  13664. inline const char **system_ca_paths() {
  13665. static const char *paths[] = {
  13666. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13667. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13668. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13669. "/etc/pki/tls/cacert.pem", // OpenELEC
  13670. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13671. nullptr};
  13672. return paths;
  13673. }
  13674. // Common CA certificate directory paths on Linux/Unix
  13675. inline const char **system_ca_dirs() {
  13676. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13677. "/etc/pki/tls/certs", // RHEL/CentOS
  13678. "/usr/share/ca-certificates", // Other
  13679. nullptr};
  13680. return dirs;
  13681. }
  13682. #endif
  13683. } // namespace impl
  13684. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  13685. const char *ca_dir) {
  13686. if (!ctx) { return false; }
  13687. bool success = true;
  13688. if (ca_file && *ca_file) {
  13689. if (!load_ca_file(ctx, ca_file)) { success = false; }
  13690. }
  13691. if (ca_dir && *ca_dir) {
  13692. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  13693. }
  13694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13695. // Set CA list for client certificate request (CertificateRequest message)
  13696. if (ca_file && *ca_file) {
  13697. auto list = SSL_load_client_CA_file(ca_file);
  13698. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  13699. }
  13700. #endif
  13701. return success;
  13702. }
  13703. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13704. const char *password) {
  13705. return set_client_cert_pem(ctx, cert, key, password);
  13706. }
  13707. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  13708. const char *key_path, const char *password) {
  13709. return set_client_cert_file(ctx, cert_path, key_path, password);
  13710. }
  13711. // PeerCert implementation
  13712. inline PeerCert::PeerCert() = default;
  13713. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  13714. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  13715. other.cert_ = nullptr;
  13716. }
  13717. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  13718. if (this != &other) {
  13719. if (cert_) { free_cert(cert_); }
  13720. cert_ = other.cert_;
  13721. other.cert_ = nullptr;
  13722. }
  13723. return *this;
  13724. }
  13725. inline PeerCert::~PeerCert() {
  13726. if (cert_) { free_cert(cert_); }
  13727. }
  13728. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  13729. inline std::string PeerCert::subject_cn() const {
  13730. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  13731. }
  13732. inline std::string PeerCert::issuer_name() const {
  13733. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  13734. }
  13735. inline bool PeerCert::check_hostname(const char *hostname) const {
  13736. return cert_ ? verify_hostname(cert_, hostname) : false;
  13737. }
  13738. inline std::vector<SanEntry> PeerCert::sans() const {
  13739. std::vector<SanEntry> result;
  13740. if (cert_) { get_cert_sans(cert_, result); }
  13741. return result;
  13742. }
  13743. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  13744. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  13745. }
  13746. inline std::string PeerCert::serial() const {
  13747. return cert_ ? get_cert_serial(cert_) : std::string();
  13748. }
  13749. // VerifyContext method implementations
  13750. inline std::string VerifyContext::subject_cn() const {
  13751. return cert ? get_cert_subject_cn(cert) : std::string();
  13752. }
  13753. inline std::string VerifyContext::issuer_name() const {
  13754. return cert ? get_cert_issuer_name(cert) : std::string();
  13755. }
  13756. inline bool VerifyContext::check_hostname(const char *hostname) const {
  13757. return cert ? verify_hostname(cert, hostname) : false;
  13758. }
  13759. inline std::vector<SanEntry> VerifyContext::sans() const {
  13760. std::vector<SanEntry> result;
  13761. if (cert) { get_cert_sans(cert, result); }
  13762. return result;
  13763. }
  13764. inline bool VerifyContext::validity(time_t &not_before,
  13765. time_t &not_after) const {
  13766. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  13767. }
  13768. inline std::string VerifyContext::serial() const {
  13769. return cert ? get_cert_serial(cert) : std::string();
  13770. }
  13771. // TlsError static method implementation
  13772. inline std::string TlsError::verify_error_to_string(long error_code) {
  13773. return verify_error_string(error_code);
  13774. }
  13775. } // namespace tls
  13776. // Request::peer_cert() implementation
  13777. inline tls::PeerCert Request::peer_cert() const {
  13778. return tls::get_peer_cert_from_session(ssl);
  13779. }
  13780. // Request::sni() implementation
  13781. inline std::string Request::sni() const {
  13782. if (!ssl) { return std::string(); }
  13783. const char *s = tls::get_sni(ssl);
  13784. return s ? std::string(s) : std::string();
  13785. }
  13786. #endif // CPPHTTPLIB_SSL_ENABLED
  13787. /*
  13788. * Group 8: TLS abstraction layer - OpenSSL backend
  13789. */
  13790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13791. inline SSL_CTX *Client::ssl_context() const {
  13792. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  13793. return nullptr;
  13794. }
  13795. inline void Client::set_server_certificate_verifier(
  13796. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  13797. cli_->set_server_certificate_verifier(verifier);
  13798. }
  13799. inline long Client::get_verify_result() const {
  13800. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).get_verify_result(); }
  13801. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  13802. }
  13803. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13804. /*
  13805. * OpenSSL Backend Implementation
  13806. */
  13807. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13808. namespace tls {
  13809. namespace impl {
  13810. // OpenSSL-specific helpers for converting native types to PEM
  13811. inline std::string x509_to_pem(X509 *cert) {
  13812. if (!cert) return {};
  13813. BIO *bio = BIO_new(BIO_s_mem());
  13814. if (!bio) return {};
  13815. if (PEM_write_bio_X509(bio, cert) != 1) {
  13816. BIO_free(bio);
  13817. return {};
  13818. }
  13819. char *data = nullptr;
  13820. long len = BIO_get_mem_data(bio, &data);
  13821. std::string pem(data, static_cast<size_t>(len));
  13822. BIO_free(bio);
  13823. return pem;
  13824. }
  13825. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  13826. if (!key) return {};
  13827. BIO *bio = BIO_new(BIO_s_mem());
  13828. if (!bio) return {};
  13829. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  13830. nullptr) != 1) {
  13831. BIO_free(bio);
  13832. return {};
  13833. }
  13834. char *data = nullptr;
  13835. long len = BIO_get_mem_data(bio, &data);
  13836. std::string pem(data, static_cast<size_t>(len));
  13837. BIO_free(bio);
  13838. return pem;
  13839. }
  13840. inline std::string x509_store_to_pem(X509_STORE *store) {
  13841. if (!store) return {};
  13842. std::string pem;
  13843. auto objs = X509_STORE_get0_objects(store);
  13844. if (!objs) return {};
  13845. auto count = sk_X509_OBJECT_num(objs);
  13846. for (decltype(count) i = 0; i < count; i++) {
  13847. auto obj = sk_X509_OBJECT_value(objs, i);
  13848. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13849. auto cert = X509_OBJECT_get0_X509(obj);
  13850. if (cert) { pem += x509_to_pem(cert); }
  13851. }
  13852. }
  13853. return pem;
  13854. }
  13855. // Helper to map OpenSSL SSL_get_error to ErrorCode
  13856. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  13857. switch (ssl_error) {
  13858. case SSL_ERROR_NONE: return ErrorCode::Success;
  13859. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  13860. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  13861. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  13862. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  13863. case SSL_ERROR_SSL:
  13864. default: return ErrorCode::Fatal;
  13865. }
  13866. }
  13867. // Helper: Create client CA list from PEM string
  13868. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13869. // Caller takes ownership of returned list
  13870. inline STACK_OF(X509_NAME) *
  13871. create_client_ca_list_from_pem(const char *ca_pem) {
  13872. if (!ca_pem) { return nullptr; }
  13873. auto ca_list = sk_X509_NAME_new_null();
  13874. if (!ca_list) { return nullptr; }
  13875. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  13876. if (!bio) {
  13877. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  13878. return nullptr;
  13879. }
  13880. X509 *cert = nullptr;
  13881. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13882. nullptr) {
  13883. X509_NAME *name = X509_get_subject_name(cert);
  13884. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  13885. X509_free(cert);
  13886. }
  13887. BIO_free(bio);
  13888. return ca_list;
  13889. }
  13890. // Helper: Extract CA names from X509_STORE
  13891. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13892. // Caller takes ownership of returned list
  13893. inline STACK_OF(X509_NAME) *
  13894. extract_client_ca_list_from_store(X509_STORE *store) {
  13895. if (!store) { return nullptr; }
  13896. auto ca_list = sk_X509_NAME_new_null();
  13897. if (!ca_list) { return nullptr; }
  13898. auto objs = X509_STORE_get0_objects(store);
  13899. if (!objs) {
  13900. sk_X509_NAME_free(ca_list);
  13901. return nullptr;
  13902. }
  13903. auto count = sk_X509_OBJECT_num(objs);
  13904. for (decltype(count) i = 0; i < count; i++) {
  13905. auto obj = sk_X509_OBJECT_value(objs, i);
  13906. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13907. auto cert = X509_OBJECT_get0_X509(obj);
  13908. if (cert) {
  13909. auto subject = X509_get_subject_name(cert);
  13910. if (subject) {
  13911. auto name_dup = X509_NAME_dup(subject);
  13912. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  13913. }
  13914. }
  13915. }
  13916. }
  13917. if (sk_X509_NAME_num(ca_list) == 0) {
  13918. sk_X509_NAME_free(ca_list);
  13919. return nullptr;
  13920. }
  13921. return ca_list;
  13922. }
  13923. // OpenSSL verify callback wrapper
  13924. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  13925. auto &callback = get_verify_callback();
  13926. if (!callback) { return preverify_ok; }
  13927. // Get SSL object from X509_STORE_CTX
  13928. auto ssl = static_cast<SSL *>(
  13929. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  13930. if (!ssl) { return preverify_ok; }
  13931. // Get current certificate and depth
  13932. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  13933. int depth = X509_STORE_CTX_get_error_depth(ctx);
  13934. int error = X509_STORE_CTX_get_error(ctx);
  13935. // Build context
  13936. VerifyContext verify_ctx;
  13937. verify_ctx.session = static_cast<session_t>(ssl);
  13938. verify_ctx.cert = static_cast<cert_t>(cert);
  13939. verify_ctx.depth = depth;
  13940. verify_ctx.preverify_ok = (preverify_ok != 0);
  13941. verify_ctx.error_code = error;
  13942. verify_ctx.error_string =
  13943. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  13944. return callback(verify_ctx) ? 1 : 0;
  13945. }
  13946. } // namespace impl
  13947. inline ctx_t create_client_context() {
  13948. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  13949. if (ctx) {
  13950. // Disable auto-retry to properly handle non-blocking I/O
  13951. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  13952. // Set minimum TLS version
  13953. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  13954. }
  13955. return static_cast<ctx_t>(ctx);
  13956. }
  13957. inline void free_context(ctx_t ctx) {
  13958. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  13959. }
  13960. inline bool set_min_version(ctx_t ctx, Version version) {
  13961. if (!ctx) return false;
  13962. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  13963. static_cast<int>(version)) == 1;
  13964. }
  13965. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  13966. if (!ctx || !pem || len == 0) return false;
  13967. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13968. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13969. if (!store) return false;
  13970. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  13971. if (!bio) return false;
  13972. bool ok = true;
  13973. X509 *cert = nullptr;
  13974. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13975. nullptr) {
  13976. if (X509_STORE_add_cert(store, cert) != 1) {
  13977. // Ignore duplicate errors
  13978. auto err = ERR_peek_last_error();
  13979. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  13980. ok = false;
  13981. }
  13982. }
  13983. X509_free(cert);
  13984. if (!ok) break;
  13985. }
  13986. BIO_free(bio);
  13987. // Clear any "no more certificates" errors
  13988. ERR_clear_error();
  13989. return ok;
  13990. }
  13991. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  13992. if (!ctx || !file_path) return false;
  13993. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  13994. nullptr) == 1;
  13995. }
  13996. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  13997. if (!ctx || !dir_path) return false;
  13998. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  13999. dir_path) == 1;
  14000. }
  14001. inline bool load_system_certs(ctx_t ctx) {
  14002. if (!ctx) return false;
  14003. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14004. #ifdef _WIN32
  14005. // Windows: Load from system certificate store (ROOT and CA)
  14006. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14007. if (!store) return false;
  14008. bool loaded_any = false;
  14009. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14010. for (auto store_name : store_names) {
  14011. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14012. if (!hStore) continue;
  14013. PCCERT_CONTEXT pContext = nullptr;
  14014. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14015. nullptr) {
  14016. const unsigned char *data = pContext->pbCertEncoded;
  14017. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14018. if (x509) {
  14019. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14020. X509_free(x509);
  14021. }
  14022. }
  14023. CertCloseStore(hStore, 0);
  14024. }
  14025. return loaded_any;
  14026. #elif defined(__APPLE__)
  14027. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14028. // macOS: Load from Keychain
  14029. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14030. if (!store) return false;
  14031. CFArrayRef certs = nullptr;
  14032. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  14033. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14034. }
  14035. bool loaded_any = false;
  14036. auto count = CFArrayGetCount(certs);
  14037. for (CFIndex i = 0; i < count; i++) {
  14038. auto cert = reinterpret_cast<SecCertificateRef>(
  14039. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14040. CFDataRef der = SecCertificateCopyData(cert);
  14041. if (der) {
  14042. const unsigned char *data = CFDataGetBytePtr(der);
  14043. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14044. if (x509) {
  14045. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14046. X509_free(x509);
  14047. }
  14048. CFRelease(der);
  14049. }
  14050. }
  14051. CFRelease(certs);
  14052. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14053. #else
  14054. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14055. #endif
  14056. #else
  14057. // Other Unix: use default verify paths
  14058. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14059. #endif
  14060. }
  14061. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14062. const char *password) {
  14063. if (!ctx || !cert || !key) return false;
  14064. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14065. // Load certificate
  14066. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14067. if (!cert_bio) return false;
  14068. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14069. BIO_free(cert_bio);
  14070. if (!x509) return false;
  14071. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14072. X509_free(x509);
  14073. if (!cert_ok) return false;
  14074. // Load private key
  14075. auto key_bio = BIO_new_mem_buf(key, -1);
  14076. if (!key_bio) return false;
  14077. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14078. password ? const_cast<char *>(password)
  14079. : nullptr);
  14080. BIO_free(key_bio);
  14081. if (!pkey) return false;
  14082. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14083. EVP_PKEY_free(pkey);
  14084. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14085. }
  14086. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14087. const char *key_path, const char *password) {
  14088. if (!ctx || !cert_path || !key_path) return false;
  14089. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14090. if (password && password[0] != '\0') {
  14091. SSL_CTX_set_default_passwd_cb_userdata(
  14092. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14093. }
  14094. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14095. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14096. }
  14097. inline ctx_t create_server_context() {
  14098. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14099. if (ctx) {
  14100. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14101. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14102. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14103. }
  14104. return static_cast<ctx_t>(ctx);
  14105. }
  14106. inline void set_verify_client(ctx_t ctx, bool require) {
  14107. if (!ctx) return;
  14108. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14109. require
  14110. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14111. : SSL_VERIFY_NONE,
  14112. nullptr);
  14113. }
  14114. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14115. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14116. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14117. SSL *ssl = SSL_new(ssl_ctx);
  14118. if (!ssl) return nullptr;
  14119. // Disable auto-retry for proper non-blocking I/O handling
  14120. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14121. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14122. if (!bio) {
  14123. SSL_free(ssl);
  14124. return nullptr;
  14125. }
  14126. SSL_set_bio(ssl, bio, bio);
  14127. return static_cast<session_t>(ssl);
  14128. }
  14129. inline void free_session(session_t session) {
  14130. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14131. }
  14132. inline bool set_sni(session_t session, const char *hostname) {
  14133. if (!session || !hostname) return false;
  14134. auto ssl = static_cast<SSL *>(session);
  14135. // Set SNI (Server Name Indication) only - does not enable verification
  14136. #if defined(OPENSSL_IS_BORINGSSL)
  14137. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14138. #else
  14139. // Direct call instead of macro to suppress -Wold-style-cast warning
  14140. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14141. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14142. #endif
  14143. }
  14144. inline bool set_hostname(session_t session, const char *hostname) {
  14145. if (!session || !hostname) return false;
  14146. auto ssl = static_cast<SSL *>(session);
  14147. // Set SNI (Server Name Indication)
  14148. if (!set_sni(session, hostname)) { return false; }
  14149. // Enable hostname verification
  14150. auto param = SSL_get0_param(ssl);
  14151. if (!param) return false;
  14152. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14153. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14154. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14155. return true;
  14156. }
  14157. inline TlsError connect(session_t session) {
  14158. if (!session) { return TlsError(); }
  14159. auto ssl = static_cast<SSL *>(session);
  14160. auto ret = SSL_connect(ssl);
  14161. TlsError err;
  14162. if (ret == 1) {
  14163. err.code = ErrorCode::Success;
  14164. } else {
  14165. auto ssl_err = SSL_get_error(ssl, ret);
  14166. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14167. err.backend_code = ERR_get_error();
  14168. }
  14169. return err;
  14170. }
  14171. inline TlsError accept(session_t session) {
  14172. if (!session) { return TlsError(); }
  14173. auto ssl = static_cast<SSL *>(session);
  14174. auto ret = SSL_accept(ssl);
  14175. TlsError err;
  14176. if (ret == 1) {
  14177. err.code = ErrorCode::Success;
  14178. } else {
  14179. auto ssl_err = SSL_get_error(ssl, ret);
  14180. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14181. err.backend_code = ERR_get_error();
  14182. }
  14183. return err;
  14184. }
  14185. inline bool connect_nonblocking(session_t session, socket_t sock,
  14186. time_t timeout_sec, time_t timeout_usec,
  14187. TlsError *err) {
  14188. if (!session) {
  14189. if (err) { err->code = ErrorCode::Fatal; }
  14190. return false;
  14191. }
  14192. auto ssl = static_cast<SSL *>(session);
  14193. auto bio = SSL_get_rbio(ssl);
  14194. // Set non-blocking mode for handshake
  14195. detail::set_nonblocking(sock, true);
  14196. if (bio) { BIO_set_nbio(bio, 1); }
  14197. auto cleanup = detail::scope_exit([&]() {
  14198. // Restore blocking mode after handshake
  14199. if (bio) { BIO_set_nbio(bio, 0); }
  14200. detail::set_nonblocking(sock, false);
  14201. });
  14202. auto res = 0;
  14203. while ((res = SSL_connect(ssl)) != 1) {
  14204. auto ssl_err = SSL_get_error(ssl, res);
  14205. switch (ssl_err) {
  14206. case SSL_ERROR_WANT_READ:
  14207. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14208. continue;
  14209. }
  14210. break;
  14211. case SSL_ERROR_WANT_WRITE:
  14212. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14213. continue;
  14214. }
  14215. break;
  14216. default: break;
  14217. }
  14218. if (err) {
  14219. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14220. err->backend_code = ERR_get_error();
  14221. }
  14222. return false;
  14223. }
  14224. if (err) { err->code = ErrorCode::Success; }
  14225. return true;
  14226. }
  14227. inline bool accept_nonblocking(session_t session, socket_t sock,
  14228. time_t timeout_sec, time_t timeout_usec,
  14229. TlsError *err) {
  14230. if (!session) {
  14231. if (err) { err->code = ErrorCode::Fatal; }
  14232. return false;
  14233. }
  14234. auto ssl = static_cast<SSL *>(session);
  14235. auto bio = SSL_get_rbio(ssl);
  14236. // Set non-blocking mode for handshake
  14237. detail::set_nonblocking(sock, true);
  14238. if (bio) { BIO_set_nbio(bio, 1); }
  14239. auto cleanup = detail::scope_exit([&]() {
  14240. // Restore blocking mode after handshake
  14241. if (bio) { BIO_set_nbio(bio, 0); }
  14242. detail::set_nonblocking(sock, false);
  14243. });
  14244. auto res = 0;
  14245. while ((res = SSL_accept(ssl)) != 1) {
  14246. auto ssl_err = SSL_get_error(ssl, res);
  14247. switch (ssl_err) {
  14248. case SSL_ERROR_WANT_READ:
  14249. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14250. continue;
  14251. }
  14252. break;
  14253. case SSL_ERROR_WANT_WRITE:
  14254. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14255. continue;
  14256. }
  14257. break;
  14258. default: break;
  14259. }
  14260. if (err) {
  14261. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14262. err->backend_code = ERR_get_error();
  14263. }
  14264. return false;
  14265. }
  14266. if (err) { err->code = ErrorCode::Success; }
  14267. return true;
  14268. }
  14269. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14270. if (!session || !buf) {
  14271. err.code = ErrorCode::Fatal;
  14272. return -1;
  14273. }
  14274. auto ssl = static_cast<SSL *>(session);
  14275. constexpr auto max_len =
  14276. static_cast<size_t>((std::numeric_limits<int>::max)());
  14277. if (len > max_len) { len = max_len; }
  14278. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14279. if (ret > 0) {
  14280. err.code = ErrorCode::Success;
  14281. return ret;
  14282. }
  14283. auto ssl_err = SSL_get_error(ssl, ret);
  14284. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14285. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14286. return -1;
  14287. }
  14288. inline ssize_t write(session_t session, const void *buf, size_t len,
  14289. TlsError &err) {
  14290. if (!session || !buf) {
  14291. err.code = ErrorCode::Fatal;
  14292. return -1;
  14293. }
  14294. auto ssl = static_cast<SSL *>(session);
  14295. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14296. if (ret > 0) {
  14297. err.code = ErrorCode::Success;
  14298. return ret;
  14299. }
  14300. auto ssl_err = SSL_get_error(ssl, ret);
  14301. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14302. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14303. return -1;
  14304. }
  14305. inline int pending(const_session_t session) {
  14306. if (!session) return 0;
  14307. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14308. }
  14309. inline void shutdown(session_t session, bool graceful) {
  14310. if (!session) return;
  14311. auto ssl = static_cast<SSL *>(session);
  14312. if (graceful) {
  14313. // First call sends close_notify
  14314. if (SSL_shutdown(ssl) == 0) {
  14315. // Second call waits for peer's close_notify
  14316. SSL_shutdown(ssl);
  14317. }
  14318. }
  14319. }
  14320. inline bool is_peer_closed(session_t session, socket_t sock) {
  14321. if (!session) return true;
  14322. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14323. detail::set_nonblocking(sock, true);
  14324. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14325. auto ssl = static_cast<SSL *>(session);
  14326. char buf;
  14327. auto ret = SSL_peek(ssl, &buf, 1);
  14328. if (ret > 0) return false;
  14329. auto err = SSL_get_error(ssl, ret);
  14330. return err == SSL_ERROR_ZERO_RETURN;
  14331. }
  14332. inline cert_t get_peer_cert(const_session_t session) {
  14333. if (!session) return nullptr;
  14334. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14335. static_cast<SSL *>(const_cast<void *>(session))));
  14336. }
  14337. inline void free_cert(cert_t cert) {
  14338. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14339. }
  14340. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14341. if (!cert || !hostname) return false;
  14342. auto x509 = static_cast<X509 *>(cert);
  14343. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14344. if (detail::is_ip_address(hostname)) {
  14345. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14346. }
  14347. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14348. }
  14349. inline uint64_t hostname_mismatch_code() {
  14350. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14351. }
  14352. inline long get_verify_result(const_session_t session) {
  14353. if (!session) return X509_V_ERR_UNSPECIFIED;
  14354. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14355. }
  14356. inline std::string get_cert_subject_cn(cert_t cert) {
  14357. if (!cert) return "";
  14358. auto x509 = static_cast<X509 *>(cert);
  14359. auto subject_name = X509_get_subject_name(x509);
  14360. if (!subject_name) return "";
  14361. char buf[256];
  14362. auto len =
  14363. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  14364. if (len < 0) return "";
  14365. return std::string(buf, static_cast<size_t>(len));
  14366. }
  14367. inline std::string get_cert_issuer_name(cert_t cert) {
  14368. if (!cert) return "";
  14369. auto x509 = static_cast<X509 *>(cert);
  14370. auto issuer_name = X509_get_issuer_name(x509);
  14371. if (!issuer_name) return "";
  14372. char buf[256];
  14373. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14374. return std::string(buf);
  14375. }
  14376. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14377. sans.clear();
  14378. if (!cert) return false;
  14379. auto x509 = static_cast<X509 *>(cert);
  14380. auto names = static_cast<GENERAL_NAMES *>(
  14381. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14382. if (!names) return true; // No SANs is valid
  14383. auto count = sk_GENERAL_NAME_num(names);
  14384. for (decltype(count) i = 0; i < count; i++) {
  14385. auto gen = sk_GENERAL_NAME_value(names, i);
  14386. if (!gen) continue;
  14387. SanEntry entry;
  14388. switch (gen->type) {
  14389. case GEN_DNS:
  14390. entry.type = SanType::DNS;
  14391. if (gen->d.dNSName) {
  14392. entry.value = std::string(
  14393. reinterpret_cast<const char *>(
  14394. ASN1_STRING_get0_data(gen->d.dNSName)),
  14395. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14396. }
  14397. break;
  14398. case GEN_IPADD:
  14399. entry.type = SanType::IP;
  14400. if (gen->d.iPAddress) {
  14401. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14402. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14403. if (len == 4) {
  14404. // IPv4
  14405. char buf[INET_ADDRSTRLEN];
  14406. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14407. entry.value = buf;
  14408. } else if (len == 16) {
  14409. // IPv6
  14410. char buf[INET6_ADDRSTRLEN];
  14411. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14412. entry.value = buf;
  14413. }
  14414. }
  14415. break;
  14416. case GEN_EMAIL:
  14417. entry.type = SanType::EMAIL;
  14418. if (gen->d.rfc822Name) {
  14419. entry.value = std::string(
  14420. reinterpret_cast<const char *>(
  14421. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14422. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14423. }
  14424. break;
  14425. case GEN_URI:
  14426. entry.type = SanType::URI;
  14427. if (gen->d.uniformResourceIdentifier) {
  14428. entry.value = std::string(
  14429. reinterpret_cast<const char *>(
  14430. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14431. static_cast<size_t>(
  14432. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14433. }
  14434. break;
  14435. default: entry.type = SanType::OTHER; break;
  14436. }
  14437. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14438. }
  14439. GENERAL_NAMES_free(names);
  14440. return true;
  14441. }
  14442. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14443. time_t &not_after) {
  14444. if (!cert) return false;
  14445. auto x509 = static_cast<X509 *>(cert);
  14446. auto nb = X509_get0_notBefore(x509);
  14447. auto na = X509_get0_notAfter(x509);
  14448. if (!nb || !na) return false;
  14449. ASN1_TIME *epoch = ASN1_TIME_new();
  14450. if (!epoch) return false;
  14451. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14452. if (!ASN1_TIME_set(epoch, 0)) return false;
  14453. int pday, psec;
  14454. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14455. not_before = 86400 * (time_t)pday + psec;
  14456. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14457. not_after = 86400 * (time_t)pday + psec;
  14458. return true;
  14459. }
  14460. inline std::string get_cert_serial(cert_t cert) {
  14461. if (!cert) return "";
  14462. auto x509 = static_cast<X509 *>(cert);
  14463. auto serial = X509_get_serialNumber(x509);
  14464. if (!serial) return "";
  14465. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14466. if (!bn) return "";
  14467. auto hex = BN_bn2hex(bn);
  14468. BN_free(bn);
  14469. if (!hex) return "";
  14470. std::string result(hex);
  14471. OPENSSL_free(hex);
  14472. return result;
  14473. }
  14474. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14475. if (!cert) return false;
  14476. auto x509 = static_cast<X509 *>(cert);
  14477. auto len = i2d_X509(x509, nullptr);
  14478. if (len < 0) return false;
  14479. der.resize(static_cast<size_t>(len));
  14480. auto p = der.data();
  14481. i2d_X509(x509, &p);
  14482. return true;
  14483. }
  14484. inline const char *get_sni(const_session_t session) {
  14485. if (!session) return nullptr;
  14486. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14487. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14488. }
  14489. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14490. inline uint64_t get_error() { return ERR_get_error(); }
  14491. inline std::string error_string(uint64_t code) {
  14492. char buf[256];
  14493. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14494. return std::string(buf);
  14495. }
  14496. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14497. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14498. if (!mem) { return nullptr; }
  14499. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14500. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14501. if (!inf) { return nullptr; }
  14502. auto store = X509_STORE_new();
  14503. if (store) {
  14504. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14505. auto itmp = sk_X509_INFO_value(inf, i);
  14506. if (!itmp) { continue; }
  14507. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14508. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14509. }
  14510. }
  14511. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14512. return static_cast<ca_store_t>(store);
  14513. }
  14514. inline void free_ca_store(ca_store_t store) {
  14515. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  14516. }
  14517. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14518. if (!ctx || !store) { return false; }
  14519. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14520. auto x509_store = static_cast<X509_STORE *>(store);
  14521. // Check if same store is already set
  14522. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  14523. // SSL_CTX_set_cert_store takes ownership and frees the old store
  14524. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  14525. return true;
  14526. }
  14527. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14528. certs.clear();
  14529. if (!ctx) { return 0; }
  14530. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14531. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14532. if (!store) { return 0; }
  14533. auto objs = X509_STORE_get0_objects(store);
  14534. if (!objs) { return 0; }
  14535. auto count = sk_X509_OBJECT_num(objs);
  14536. for (decltype(count) i = 0; i < count; i++) {
  14537. auto obj = sk_X509_OBJECT_value(objs, i);
  14538. if (!obj) { continue; }
  14539. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14540. auto x509 = X509_OBJECT_get0_X509(obj);
  14541. if (x509) {
  14542. // Increment reference count so caller can free it
  14543. X509_up_ref(x509);
  14544. certs.push_back(static_cast<cert_t>(x509));
  14545. }
  14546. }
  14547. }
  14548. return certs.size();
  14549. }
  14550. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14551. std::vector<std::string> names;
  14552. if (!ctx) { return names; }
  14553. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14554. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14555. if (!store) { return names; }
  14556. auto objs = X509_STORE_get0_objects(store);
  14557. if (!objs) { return names; }
  14558. auto count = sk_X509_OBJECT_num(objs);
  14559. for (decltype(count) i = 0; i < count; i++) {
  14560. auto obj = sk_X509_OBJECT_value(objs, i);
  14561. if (!obj) { continue; }
  14562. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14563. auto x509 = X509_OBJECT_get0_X509(obj);
  14564. if (x509) {
  14565. auto subject = X509_get_subject_name(x509);
  14566. if (subject) {
  14567. char buf[512];
  14568. X509_NAME_oneline(subject, buf, sizeof(buf));
  14569. names.push_back(buf);
  14570. }
  14571. }
  14572. }
  14573. }
  14574. return names;
  14575. }
  14576. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14577. const char *key_pem, const char *password) {
  14578. if (!ctx || !cert_pem || !key_pem) { return false; }
  14579. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14580. // Load certificate from PEM
  14581. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  14582. if (!cert_bio) { return false; }
  14583. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14584. BIO_free(cert_bio);
  14585. if (!cert) { return false; }
  14586. // Load private key from PEM
  14587. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  14588. if (!key_bio) {
  14589. X509_free(cert);
  14590. return false;
  14591. }
  14592. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14593. password ? const_cast<char *>(password)
  14594. : nullptr);
  14595. BIO_free(key_bio);
  14596. if (!key) {
  14597. X509_free(cert);
  14598. return false;
  14599. }
  14600. // Update certificate and key
  14601. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  14602. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  14603. X509_free(cert);
  14604. EVP_PKEY_free(key);
  14605. return ret;
  14606. }
  14607. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14608. if (!ctx || !ca_pem) { return false; }
  14609. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14610. // Create new X509_STORE from PEM
  14611. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  14612. if (!store) { return false; }
  14613. // SSL_CTX_set_cert_store takes ownership
  14614. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  14615. // Set client CA list for client certificate request
  14616. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  14617. if (ca_list) {
  14618. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  14619. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  14620. }
  14621. return true;
  14622. }
  14623. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14624. if (!ctx) { return false; }
  14625. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14626. impl::get_verify_callback() = std::move(callback);
  14627. if (impl::get_verify_callback()) {
  14628. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  14629. } else {
  14630. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  14631. }
  14632. return true;
  14633. }
  14634. inline long get_verify_error(const_session_t session) {
  14635. if (!session) { return -1; }
  14636. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14637. return SSL_get_verify_result(ssl);
  14638. }
  14639. inline std::string verify_error_string(long error_code) {
  14640. if (error_code == X509_V_OK) { return ""; }
  14641. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  14642. return str ? str : "unknown error";
  14643. }
  14644. namespace impl {
  14645. // OpenSSL-specific helpers for public API wrappers
  14646. inline ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  14647. X509_STORE *client_ca_store,
  14648. int &out_error) {
  14649. out_error = 0;
  14650. auto cert_pem = x509_to_pem(cert);
  14651. auto key_pem = evp_pkey_to_pem(key);
  14652. if (cert_pem.empty() || key_pem.empty()) {
  14653. out_error = static_cast<int>(ERR_get_error());
  14654. return nullptr;
  14655. }
  14656. auto ctx = create_server_context();
  14657. if (!ctx) {
  14658. out_error = static_cast<int>(get_error());
  14659. return nullptr;
  14660. }
  14661. if (!set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr)) {
  14662. out_error = static_cast<int>(get_error());
  14663. free_context(ctx);
  14664. return nullptr;
  14665. }
  14666. if (client_ca_store) {
  14667. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  14668. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  14669. // Extract and set client CA list directly from store (more efficient than
  14670. // PEM conversion)
  14671. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  14672. if (ca_list) {
  14673. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  14674. }
  14675. set_verify_client(ctx, true);
  14676. }
  14677. return ctx;
  14678. }
  14679. inline void update_server_certs_from_x509(ctx_t ctx, X509 *cert, EVP_PKEY *key,
  14680. X509_STORE *client_ca_store) {
  14681. auto cert_pem = x509_to_pem(cert);
  14682. auto key_pem = evp_pkey_to_pem(key);
  14683. if (!cert_pem.empty() && !key_pem.empty()) {
  14684. update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  14685. }
  14686. if (client_ca_store) {
  14687. auto ca_pem = x509_store_to_pem(client_ca_store);
  14688. if (!ca_pem.empty()) { update_server_client_ca(ctx, ca_pem.c_str()); }
  14689. X509_STORE_free(client_ca_store);
  14690. }
  14691. }
  14692. inline ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  14693. const char *password,
  14694. uint64_t &out_error) {
  14695. out_error = 0;
  14696. auto ctx = create_client_context();
  14697. if (!ctx) {
  14698. out_error = get_error();
  14699. return nullptr;
  14700. }
  14701. if (cert && key) {
  14702. auto cert_pem = x509_to_pem(cert);
  14703. auto key_pem = evp_pkey_to_pem(key);
  14704. if (cert_pem.empty() || key_pem.empty()) {
  14705. out_error = ERR_get_error();
  14706. free_context(ctx);
  14707. return nullptr;
  14708. }
  14709. if (!set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  14710. password)) {
  14711. out_error = get_error();
  14712. free_context(ctx);
  14713. return nullptr;
  14714. }
  14715. }
  14716. return ctx;
  14717. }
  14718. } // namespace impl
  14719. } // namespace tls
  14720. // ClientImpl::set_ca_cert_store - defined here to use
  14721. // tls::impl::x509_store_to_pem Deprecated: converts X509_STORE to PEM and
  14722. // stores for redirect transfer
  14723. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  14724. if (ca_cert_store) {
  14725. ca_cert_pem_ = tls::impl::x509_store_to_pem(ca_cert_store);
  14726. }
  14727. }
  14728. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  14729. X509_STORE *client_ca_cert_store) {
  14730. ctx_ = tls::impl::create_server_context_from_x509(
  14731. cert, private_key, client_ca_cert_store, last_ssl_error_);
  14732. }
  14733. inline SSLServer::SSLServer(
  14734. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  14735. // Use abstract API to create context
  14736. ctx_ = tls::create_server_context();
  14737. if (ctx_) {
  14738. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  14739. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  14740. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  14741. tls::free_context(ctx_);
  14742. ctx_ = nullptr;
  14743. }
  14744. }
  14745. }
  14746. inline SSL_CTX *SSLServer::ssl_context() const {
  14747. return static_cast<SSL_CTX *>(ctx_);
  14748. }
  14749. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  14750. X509_STORE *client_ca_cert_store) {
  14751. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14752. tls::impl::update_server_certs_from_x509(ctx_, cert, private_key,
  14753. client_ca_cert_store);
  14754. }
  14755. inline SSLClient::SSLClient(const std::string &host, int port,
  14756. X509 *client_cert, EVP_PKEY *client_key,
  14757. const std::string &private_key_password)
  14758. : ClientImpl(host, port) {
  14759. const char *password =
  14760. private_key_password.empty() ? nullptr : private_key_password.c_str();
  14761. ctx_ = tls::impl::create_client_context_from_x509(
  14762. client_cert, client_key, password, last_backend_error_);
  14763. }
  14764. inline long SSLClient::get_verify_result() const { return verify_result_; }
  14765. inline void SSLClient::set_server_certificate_verifier(
  14766. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  14767. // Wrap SSL* callback into backend-independent session_verifier_
  14768. auto v = std::make_shared<std::function<SSLVerifierResponse(SSL *)>>(
  14769. std::move(verifier));
  14770. session_verifier_ = [v](tls::session_t session) {
  14771. return (*v)(static_cast<SSL *>(session));
  14772. };
  14773. }
  14774. inline SSL_CTX *SSLClient::ssl_context() const {
  14775. return static_cast<SSL_CTX *>(ctx_);
  14776. }
  14777. inline bool SSLClient::verify_host(X509 *server_cert) const {
  14778. /* Quote from RFC2818 section 3.1 "Server Identity"
  14779. If a subjectAltName extension of type dNSName is present, that MUST
  14780. be used as the identity. Otherwise, the (most specific) Common Name
  14781. field in the Subject field of the certificate MUST be used. Although
  14782. the use of the Common Name is existing practice, it is deprecated and
  14783. Certification Authorities are encouraged to use the dNSName instead.
  14784. Matching is performed using the matching rules specified by
  14785. [RFC2459]. If more than one identity of a given type is present in
  14786. the certificate (e.g., more than one dNSName name, a match in any one
  14787. of the set is considered acceptable.) Names may contain the wildcard
  14788. character * which is considered to match any single domain name
  14789. component or component fragment. E.g., *.a.com matches foo.a.com but
  14790. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  14791. In some cases, the URI is specified as an IP address rather than a
  14792. hostname. In this case, the iPAddress subjectAltName must be present
  14793. in the certificate and must exactly match the IP in the URI.
  14794. */
  14795. return verify_host_with_subject_alt_name(server_cert) ||
  14796. verify_host_with_common_name(server_cert);
  14797. }
  14798. inline bool
  14799. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  14800. auto ret = false;
  14801. auto type = GEN_DNS;
  14802. struct in6_addr addr6 = {};
  14803. struct in_addr addr = {};
  14804. size_t addr_len = 0;
  14805. #ifndef __MINGW32__
  14806. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  14807. type = GEN_IPADD;
  14808. addr_len = sizeof(struct in6_addr);
  14809. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  14810. type = GEN_IPADD;
  14811. addr_len = sizeof(struct in_addr);
  14812. }
  14813. #endif
  14814. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  14815. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  14816. if (alt_names) {
  14817. auto dsn_matched = false;
  14818. auto ip_matched = false;
  14819. auto count = sk_GENERAL_NAME_num(alt_names);
  14820. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  14821. auto val = sk_GENERAL_NAME_value(alt_names, i);
  14822. if (!val || val->type != type) { continue; }
  14823. auto name =
  14824. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  14825. if (name == nullptr) { continue; }
  14826. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  14827. switch (type) {
  14828. case GEN_DNS:
  14829. dsn_matched =
  14830. detail::match_hostname(std::string(name, name_len), host_);
  14831. break;
  14832. case GEN_IPADD:
  14833. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  14834. ip_matched = true;
  14835. }
  14836. break;
  14837. }
  14838. }
  14839. if (dsn_matched || ip_matched) { ret = true; }
  14840. }
  14841. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  14842. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  14843. return ret;
  14844. }
  14845. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  14846. const auto subject_name = X509_get_subject_name(server_cert);
  14847. if (subject_name != nullptr) {
  14848. char name[BUFSIZ];
  14849. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  14850. name, sizeof(name));
  14851. if (name_len != -1) {
  14852. return detail::match_hostname(
  14853. std::string(name, static_cast<size_t>(name_len)), host_);
  14854. }
  14855. }
  14856. return false;
  14857. }
  14858. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  14859. /*
  14860. * Group 9: TLS abstraction layer - Mbed TLS backend
  14861. */
  14862. /*
  14863. * Mbed TLS Backend Implementation
  14864. */
  14865. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14866. namespace tls {
  14867. namespace impl {
  14868. // Mbed TLS session wrapper
  14869. struct MbedTlsSession {
  14870. mbedtls_ssl_context ssl;
  14871. socket_t sock = INVALID_SOCKET;
  14872. std::string hostname; // For client: set via set_sni
  14873. std::string sni_hostname; // For server: received from client via SNI callback
  14874. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  14875. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  14876. MbedTlsSession(const MbedTlsSession &) = delete;
  14877. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  14878. };
  14879. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  14880. // queue)
  14881. inline int &mbedtls_last_error() {
  14882. static thread_local int err = 0;
  14883. return err;
  14884. }
  14885. // Helper to map Mbed TLS error to ErrorCode
  14886. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  14887. if (ret == 0) { return ErrorCode::Success; }
  14888. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  14889. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  14890. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  14891. return ErrorCode::PeerClosed;
  14892. }
  14893. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  14894. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  14895. out_errno = errno;
  14896. return ErrorCode::SyscallError;
  14897. }
  14898. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  14899. return ErrorCode::CertVerifyFailed;
  14900. }
  14901. return ErrorCode::Fatal;
  14902. }
  14903. // BIO-like send callback for Mbed TLS
  14904. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  14905. size_t len) {
  14906. auto sock = *static_cast<socket_t *>(ctx);
  14907. #ifdef _WIN32
  14908. auto ret =
  14909. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  14910. if (ret == SOCKET_ERROR) {
  14911. int err = WSAGetLastError();
  14912. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  14913. return MBEDTLS_ERR_NET_SEND_FAILED;
  14914. }
  14915. #else
  14916. auto ret = send(sock, buf, len, 0);
  14917. if (ret < 0) {
  14918. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14919. return MBEDTLS_ERR_SSL_WANT_WRITE;
  14920. }
  14921. return MBEDTLS_ERR_NET_SEND_FAILED;
  14922. }
  14923. #endif
  14924. return static_cast<int>(ret);
  14925. }
  14926. // BIO-like recv callback for Mbed TLS
  14927. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  14928. auto sock = *static_cast<socket_t *>(ctx);
  14929. #ifdef _WIN32
  14930. auto ret =
  14931. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  14932. if (ret == SOCKET_ERROR) {
  14933. int err = WSAGetLastError();
  14934. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  14935. return MBEDTLS_ERR_NET_RECV_FAILED;
  14936. }
  14937. #else
  14938. auto ret = recv(sock, buf, len, 0);
  14939. if (ret < 0) {
  14940. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14941. return MBEDTLS_ERR_SSL_WANT_READ;
  14942. }
  14943. return MBEDTLS_ERR_NET_RECV_FAILED;
  14944. }
  14945. #endif
  14946. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  14947. return static_cast<int>(ret);
  14948. }
  14949. // MbedTlsContext constructor/destructor implementations
  14950. inline MbedTlsContext::MbedTlsContext() {
  14951. mbedtls_ssl_config_init(&conf);
  14952. mbedtls_entropy_init(&entropy);
  14953. mbedtls_ctr_drbg_init(&ctr_drbg);
  14954. mbedtls_x509_crt_init(&ca_chain);
  14955. mbedtls_x509_crt_init(&own_cert);
  14956. mbedtls_pk_init(&own_key);
  14957. }
  14958. inline MbedTlsContext::~MbedTlsContext() {
  14959. mbedtls_pk_free(&own_key);
  14960. mbedtls_x509_crt_free(&own_cert);
  14961. mbedtls_x509_crt_free(&ca_chain);
  14962. mbedtls_ctr_drbg_free(&ctr_drbg);
  14963. mbedtls_entropy_free(&entropy);
  14964. mbedtls_ssl_config_free(&conf);
  14965. }
  14966. // Thread-local storage for SNI captured during handshake
  14967. // This is needed because the SNI callback doesn't have a way to pass
  14968. // session-specific data before the session is fully set up
  14969. inline std::string &mbedpending_sni() {
  14970. static thread_local std::string sni;
  14971. return sni;
  14972. }
  14973. // SNI callback for Mbed TLS server to capture client's SNI hostname
  14974. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  14975. const unsigned char *name, size_t name_len) {
  14976. (void)p_ctx;
  14977. (void)ssl;
  14978. // Store SNI name in thread-local storage
  14979. // It will be retrieved and stored in the session after handshake
  14980. if (name && name_len > 0) {
  14981. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  14982. } else {
  14983. mbedpending_sni().clear();
  14984. }
  14985. return 0; // Accept any SNI
  14986. }
  14987. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  14988. int cert_depth, uint32_t *flags);
  14989. // MbedTLS verify callback wrapper
  14990. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  14991. int cert_depth, uint32_t *flags) {
  14992. auto &callback = get_verify_callback();
  14993. if (!callback) { return 0; } // Continue with default verification
  14994. // data points to the MbedTlsSession
  14995. auto *session = static_cast<MbedTlsSession *>(data);
  14996. // Build context
  14997. VerifyContext verify_ctx;
  14998. verify_ctx.session = static_cast<session_t>(session);
  14999. verify_ctx.cert = static_cast<cert_t>(crt);
  15000. verify_ctx.depth = cert_depth;
  15001. verify_ctx.preverify_ok = (*flags == 0);
  15002. verify_ctx.error_code = static_cast<long>(*flags);
  15003. // Convert Mbed TLS flags to error string
  15004. static thread_local char error_buf[256];
  15005. if (*flags != 0) {
  15006. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15007. verify_ctx.error_string = error_buf;
  15008. } else {
  15009. verify_ctx.error_string = nullptr;
  15010. }
  15011. bool accepted = callback(verify_ctx);
  15012. if (accepted) {
  15013. *flags = 0; // Clear all error flags
  15014. return 0;
  15015. }
  15016. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15017. }
  15018. } // namespace impl
  15019. inline ctx_t create_client_context() {
  15020. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15021. if (!ctx) { return nullptr; }
  15022. ctx->is_server = false;
  15023. // Seed the random number generator
  15024. const char *pers = "httplib_client";
  15025. int ret = mbedtls_ctr_drbg_seed(
  15026. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15027. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15028. if (ret != 0) {
  15029. impl::mbedtls_last_error() = ret;
  15030. delete ctx;
  15031. return nullptr;
  15032. }
  15033. // Set up SSL config for client
  15034. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15035. MBEDTLS_SSL_TRANSPORT_STREAM,
  15036. MBEDTLS_SSL_PRESET_DEFAULT);
  15037. if (ret != 0) {
  15038. impl::mbedtls_last_error() = ret;
  15039. delete ctx;
  15040. return nullptr;
  15041. }
  15042. // Set random number generator
  15043. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15044. // Default: verify peer certificate
  15045. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15046. // Set minimum TLS version to 1.2
  15047. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15048. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15049. #else
  15050. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15051. MBEDTLS_SSL_MINOR_VERSION_3);
  15052. #endif
  15053. return static_cast<ctx_t>(ctx);
  15054. }
  15055. inline ctx_t create_server_context() {
  15056. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15057. if (!ctx) { return nullptr; }
  15058. ctx->is_server = true;
  15059. // Seed the random number generator
  15060. const char *pers = "httplib_server";
  15061. int ret = mbedtls_ctr_drbg_seed(
  15062. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15063. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15064. if (ret != 0) {
  15065. impl::mbedtls_last_error() = ret;
  15066. delete ctx;
  15067. return nullptr;
  15068. }
  15069. // Set up SSL config for server
  15070. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15071. MBEDTLS_SSL_TRANSPORT_STREAM,
  15072. MBEDTLS_SSL_PRESET_DEFAULT);
  15073. if (ret != 0) {
  15074. impl::mbedtls_last_error() = ret;
  15075. delete ctx;
  15076. return nullptr;
  15077. }
  15078. // Set random number generator
  15079. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15080. // Default: don't verify client
  15081. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15082. // Set minimum TLS version to 1.2
  15083. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15084. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15085. #else
  15086. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15087. MBEDTLS_SSL_MINOR_VERSION_3);
  15088. #endif
  15089. // Set SNI callback to capture client's SNI hostname
  15090. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15091. return static_cast<ctx_t>(ctx);
  15092. }
  15093. inline void free_context(ctx_t ctx) {
  15094. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15095. }
  15096. inline bool set_min_version(ctx_t ctx, Version version) {
  15097. if (!ctx) { return false; }
  15098. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15099. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15100. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15101. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15102. if (version >= Version::TLS1_3) {
  15103. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15104. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15105. #endif
  15106. }
  15107. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15108. #else
  15109. // Mbed TLS 2.x uses major/minor version numbers
  15110. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15111. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15112. if (version >= Version::TLS1_3) {
  15113. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15114. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15115. #else
  15116. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15117. #endif
  15118. }
  15119. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15120. #endif
  15121. return true;
  15122. }
  15123. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15124. if (!ctx || !pem) { return false; }
  15125. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15126. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15127. // Add null terminator if not present
  15128. std::string pem_str(pem, len);
  15129. int ret = mbedtls_x509_crt_parse(
  15130. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15131. pem_str.size() + 1);
  15132. if (ret != 0) {
  15133. impl::mbedtls_last_error() = ret;
  15134. return false;
  15135. }
  15136. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15137. return true;
  15138. }
  15139. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15140. if (!ctx || !file_path) { return false; }
  15141. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15142. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15143. if (ret != 0) {
  15144. impl::mbedtls_last_error() = ret;
  15145. return false;
  15146. }
  15147. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15148. return true;
  15149. }
  15150. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15151. if (!ctx || !dir_path) { return false; }
  15152. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15153. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15154. if (ret < 0) { // Returns number of certs on success, negative on error
  15155. impl::mbedtls_last_error() = ret;
  15156. return false;
  15157. }
  15158. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15159. return true;
  15160. }
  15161. inline bool load_system_certs(ctx_t ctx) {
  15162. if (!ctx) { return false; }
  15163. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15164. bool loaded = false;
  15165. #ifdef _WIN32
  15166. loaded = impl::enumerate_windows_system_certs(
  15167. [&](const unsigned char *data, size_t len) {
  15168. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15169. });
  15170. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15171. loaded = impl::enumerate_macos_keychain_certs(
  15172. [&](const unsigned char *data, size_t len) {
  15173. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15174. });
  15175. #else
  15176. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15177. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15178. loaded = true;
  15179. break;
  15180. }
  15181. }
  15182. if (!loaded) {
  15183. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15184. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15185. loaded = true;
  15186. break;
  15187. }
  15188. }
  15189. }
  15190. #endif
  15191. if (loaded) {
  15192. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15193. }
  15194. return loaded;
  15195. }
  15196. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15197. const char *password) {
  15198. if (!ctx || !cert || !key) { return false; }
  15199. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15200. // Parse certificate
  15201. std::string cert_str(cert);
  15202. int ret = mbedtls_x509_crt_parse(
  15203. &mctx->own_cert,
  15204. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15205. cert_str.size() + 1);
  15206. if (ret != 0) {
  15207. impl::mbedtls_last_error() = ret;
  15208. return false;
  15209. }
  15210. // Parse private key
  15211. std::string key_str(key);
  15212. const unsigned char *pwd =
  15213. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15214. size_t pwd_len = password ? strlen(password) : 0;
  15215. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15216. ret = mbedtls_pk_parse_key(
  15217. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15218. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15219. &mctx->ctr_drbg);
  15220. #else
  15221. ret = mbedtls_pk_parse_key(
  15222. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15223. key_str.size() + 1, pwd, pwd_len);
  15224. #endif
  15225. if (ret != 0) {
  15226. impl::mbedtls_last_error() = ret;
  15227. return false;
  15228. }
  15229. // Verify that the certificate and private key match
  15230. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15231. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15232. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15233. #else
  15234. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15235. #endif
  15236. if (ret != 0) {
  15237. impl::mbedtls_last_error() = ret;
  15238. return false;
  15239. }
  15240. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15241. if (ret != 0) {
  15242. impl::mbedtls_last_error() = ret;
  15243. return false;
  15244. }
  15245. return true;
  15246. }
  15247. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15248. const char *key_path, const char *password) {
  15249. if (!ctx || !cert_path || !key_path) { return false; }
  15250. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15251. // Parse certificate file
  15252. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15253. if (ret != 0) {
  15254. impl::mbedtls_last_error() = ret;
  15255. return false;
  15256. }
  15257. // Parse private key file
  15258. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15259. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15260. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15261. #else
  15262. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15263. #endif
  15264. if (ret != 0) {
  15265. impl::mbedtls_last_error() = ret;
  15266. return false;
  15267. }
  15268. // Verify that the certificate and private key match
  15269. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15270. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15271. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15272. #else
  15273. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15274. #endif
  15275. if (ret != 0) {
  15276. impl::mbedtls_last_error() = ret;
  15277. return false;
  15278. }
  15279. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15280. if (ret != 0) {
  15281. impl::mbedtls_last_error() = ret;
  15282. return false;
  15283. }
  15284. return true;
  15285. }
  15286. inline void set_verify_client(ctx_t ctx, bool require) {
  15287. if (!ctx) { return; }
  15288. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15289. mctx->verify_client = require;
  15290. if (require) {
  15291. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15292. } else {
  15293. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15294. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15295. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15296. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15297. : MBEDTLS_SSL_VERIFY_NONE);
  15298. }
  15299. }
  15300. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15301. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15302. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15303. auto session = new (std::nothrow) impl::MbedTlsSession();
  15304. if (!session) { return nullptr; }
  15305. session->sock = sock;
  15306. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15307. if (ret != 0) {
  15308. impl::mbedtls_last_error() = ret;
  15309. delete session;
  15310. return nullptr;
  15311. }
  15312. // Set BIO callbacks
  15313. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15314. impl::mbedtls_net_recv_cb, nullptr);
  15315. // Set per-session verify callback with session pointer if callback is
  15316. // registered
  15317. if (mctx->has_verify_callback) {
  15318. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15319. session);
  15320. }
  15321. return static_cast<session_t>(session);
  15322. }
  15323. inline void free_session(session_t session) {
  15324. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15325. }
  15326. inline bool set_sni(session_t session, const char *hostname) {
  15327. if (!session || !hostname) { return false; }
  15328. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15329. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15330. if (ret != 0) {
  15331. impl::mbedtls_last_error() = ret;
  15332. return false;
  15333. }
  15334. msession->hostname = hostname;
  15335. return true;
  15336. }
  15337. inline bool set_hostname(session_t session, const char *hostname) {
  15338. // In Mbed TLS, set_hostname also sets up hostname verification
  15339. return set_sni(session, hostname);
  15340. }
  15341. inline TlsError connect(session_t session) {
  15342. TlsError err;
  15343. if (!session) {
  15344. err.code = ErrorCode::Fatal;
  15345. return err;
  15346. }
  15347. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15348. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15349. if (ret == 0) {
  15350. err.code = ErrorCode::Success;
  15351. } else {
  15352. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15353. err.backend_code = static_cast<uint64_t>(-ret);
  15354. impl::mbedtls_last_error() = ret;
  15355. }
  15356. return err;
  15357. }
  15358. inline TlsError accept(session_t session) {
  15359. // Same as connect for Mbed TLS - handshake works for both client and server
  15360. auto result = connect(session);
  15361. // After successful handshake, capture SNI from thread-local storage
  15362. if (result.code == ErrorCode::Success && session) {
  15363. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15364. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15365. impl::mbedpending_sni().clear();
  15366. }
  15367. return result;
  15368. }
  15369. inline bool connect_nonblocking(session_t session, socket_t sock,
  15370. time_t timeout_sec, time_t timeout_usec,
  15371. TlsError *err) {
  15372. if (!session) {
  15373. if (err) { err->code = ErrorCode::Fatal; }
  15374. return false;
  15375. }
  15376. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15377. // Set socket to non-blocking mode
  15378. detail::set_nonblocking(sock, true);
  15379. auto cleanup =
  15380. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15381. int ret;
  15382. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15383. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15384. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15385. continue;
  15386. }
  15387. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15388. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15389. continue;
  15390. }
  15391. }
  15392. // TlsError or timeout
  15393. if (err) {
  15394. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15395. err->backend_code = static_cast<uint64_t>(-ret);
  15396. }
  15397. impl::mbedtls_last_error() = ret;
  15398. return false;
  15399. }
  15400. if (err) { err->code = ErrorCode::Success; }
  15401. return true;
  15402. }
  15403. inline bool accept_nonblocking(session_t session, socket_t sock,
  15404. time_t timeout_sec, time_t timeout_usec,
  15405. TlsError *err) {
  15406. // Same implementation as connect for Mbed TLS
  15407. bool result =
  15408. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15409. // After successful handshake, capture SNI from thread-local storage
  15410. if (result && session) {
  15411. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15412. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15413. impl::mbedpending_sni().clear();
  15414. }
  15415. return result;
  15416. }
  15417. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15418. if (!session || !buf) {
  15419. err.code = ErrorCode::Fatal;
  15420. return -1;
  15421. }
  15422. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15423. int ret =
  15424. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15425. if (ret > 0) {
  15426. err.code = ErrorCode::Success;
  15427. return static_cast<ssize_t>(ret);
  15428. }
  15429. if (ret == 0) {
  15430. err.code = ErrorCode::PeerClosed;
  15431. return 0;
  15432. }
  15433. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15434. err.backend_code = static_cast<uint64_t>(-ret);
  15435. impl::mbedtls_last_error() = ret;
  15436. return -1;
  15437. }
  15438. inline ssize_t write(session_t session, const void *buf, size_t len,
  15439. TlsError &err) {
  15440. if (!session || !buf) {
  15441. err.code = ErrorCode::Fatal;
  15442. return -1;
  15443. }
  15444. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15445. int ret = mbedtls_ssl_write(&msession->ssl,
  15446. static_cast<const unsigned char *>(buf), len);
  15447. if (ret > 0) {
  15448. err.code = ErrorCode::Success;
  15449. return static_cast<ssize_t>(ret);
  15450. }
  15451. if (ret == 0) {
  15452. err.code = ErrorCode::PeerClosed;
  15453. return 0;
  15454. }
  15455. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15456. err.backend_code = static_cast<uint64_t>(-ret);
  15457. impl::mbedtls_last_error() = ret;
  15458. return -1;
  15459. }
  15460. inline int pending(const_session_t session) {
  15461. if (!session) { return 0; }
  15462. auto msession =
  15463. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15464. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15465. }
  15466. inline void shutdown(session_t session, bool graceful) {
  15467. if (!session) { return; }
  15468. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15469. if (graceful) {
  15470. // Try to send close_notify, but don't block forever
  15471. int ret;
  15472. int attempts = 0;
  15473. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15474. attempts < 3) {
  15475. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15476. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15477. break;
  15478. }
  15479. attempts++;
  15480. }
  15481. }
  15482. }
  15483. inline bool is_peer_closed(session_t session, socket_t sock) {
  15484. if (!session || sock == INVALID_SOCKET) { return true; }
  15485. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15486. // Check if there's already decrypted data available in the TLS buffer
  15487. // If so, the connection is definitely alive
  15488. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15489. // Set socket to non-blocking to avoid blocking on read
  15490. detail::set_nonblocking(sock, true);
  15491. auto cleanup =
  15492. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15493. // Try a 1-byte read to check connection status
  15494. // Note: This will consume the byte if data is available, but for the
  15495. // purpose of checking if peer is closed, this should be acceptable
  15496. // since we're only called when we expect the connection might be closing
  15497. unsigned char buf;
  15498. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15499. // If we got data or WANT_READ (would block), connection is alive
  15500. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15501. // If we get a peer close notify or a connection reset, the peer is closed
  15502. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15503. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15504. }
  15505. inline cert_t get_peer_cert(const_session_t session) {
  15506. if (!session) { return nullptr; }
  15507. auto msession =
  15508. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15509. // Mbed TLS returns a pointer to the internal peer cert chain.
  15510. // WARNING: This pointer is only valid while the session is active.
  15511. // Do not use the certificate after calling free_session().
  15512. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15513. return const_cast<mbedtls_x509_crt *>(cert);
  15514. }
  15515. inline void free_cert(cert_t cert) {
  15516. // Mbed TLS: peer certificate is owned by the SSL context.
  15517. // No-op here, but callers should still call this for cross-backend
  15518. // portability.
  15519. (void)cert;
  15520. }
  15521. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15522. if (!cert || !hostname) { return false; }
  15523. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15524. std::string host_str(hostname);
  15525. // Check if hostname is an IP address
  15526. bool is_ip = impl::is_ipv4_address(host_str);
  15527. unsigned char ip_bytes[4];
  15528. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  15529. // Check Subject Alternative Names (SAN)
  15530. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15531. // - DNS names: raw string bytes
  15532. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15533. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15534. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15535. const unsigned char *p = san->buf.p;
  15536. size_t len = san->buf.len;
  15537. if (is_ip) {
  15538. // Check if this SAN is an IPv4 address (4 bytes)
  15539. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  15540. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  15541. } else {
  15542. // Check if this SAN is a DNS name (printable ASCII string)
  15543. bool is_dns = len > 0;
  15544. for (size_t i = 0; i < len && is_dns; i++) {
  15545. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15546. }
  15547. if (is_dns) {
  15548. std::string san_name(reinterpret_cast<const char *>(p), len);
  15549. if (detail::match_hostname(san_name, host_str)) { return true; }
  15550. }
  15551. }
  15552. san = san->next;
  15553. }
  15554. // Fallback: Check Common Name (CN) in subject
  15555. char cn[256];
  15556. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15557. if (ret > 0) {
  15558. std::string cn_str(cn);
  15559. // Look for "CN=" in the DN string
  15560. size_t cn_pos = cn_str.find("CN=");
  15561. if (cn_pos != std::string::npos) {
  15562. size_t start = cn_pos + 3;
  15563. size_t end = cn_str.find(',', start);
  15564. std::string cn_value =
  15565. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15566. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15567. }
  15568. }
  15569. return false;
  15570. }
  15571. inline uint64_t hostname_mismatch_code() {
  15572. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15573. }
  15574. inline long get_verify_result(const_session_t session) {
  15575. if (!session) { return -1; }
  15576. auto msession =
  15577. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15578. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15579. // Return 0 (X509_V_OK equivalent) if verification passed
  15580. return flags == 0 ? 0 : static_cast<long>(flags);
  15581. }
  15582. inline std::string get_cert_subject_cn(cert_t cert) {
  15583. if (!cert) return "";
  15584. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15585. // Find the CN in the subject
  15586. const mbedtls_x509_name *name = &x509->subject;
  15587. while (name != nullptr) {
  15588. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15589. return std::string(reinterpret_cast<const char *>(name->val.p),
  15590. name->val.len);
  15591. }
  15592. name = name->next;
  15593. }
  15594. return "";
  15595. }
  15596. inline std::string get_cert_issuer_name(cert_t cert) {
  15597. if (!cert) return "";
  15598. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15599. // Build a human-readable issuer name string
  15600. char buf[512];
  15601. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15602. if (ret < 0) return "";
  15603. return std::string(buf);
  15604. }
  15605. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15606. sans.clear();
  15607. if (!cert) return false;
  15608. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15609. // Parse the Subject Alternative Name extension
  15610. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15611. while (cur != nullptr) {
  15612. if (cur->buf.len > 0) {
  15613. // Mbed TLS stores SAN as ASN.1 sequences
  15614. // The tag byte indicates the type
  15615. const unsigned char *p = cur->buf.p;
  15616. size_t len = cur->buf.len;
  15617. // First byte is the tag
  15618. unsigned char tag = *p;
  15619. p++;
  15620. len--;
  15621. // Parse length (simple single-byte length assumed)
  15622. if (len > 0 && *p < 0x80) {
  15623. size_t value_len = *p;
  15624. p++;
  15625. len--;
  15626. if (value_len <= len) {
  15627. SanEntry entry;
  15628. // ASN.1 context tags for GeneralName
  15629. switch (tag & 0x1F) {
  15630. case 2: // dNSName
  15631. entry.type = SanType::DNS;
  15632. entry.value =
  15633. std::string(reinterpret_cast<const char *>(p), value_len);
  15634. break;
  15635. case 7: // iPAddress
  15636. entry.type = SanType::IP;
  15637. if (value_len == 4) {
  15638. // IPv4
  15639. char buf[16];
  15640. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15641. entry.value = buf;
  15642. } else if (value_len == 16) {
  15643. // IPv6
  15644. char buf[64];
  15645. snprintf(buf, sizeof(buf),
  15646. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15647. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15648. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15649. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15650. entry.value = buf;
  15651. }
  15652. break;
  15653. case 1: // rfc822Name (email)
  15654. entry.type = SanType::EMAIL;
  15655. entry.value =
  15656. std::string(reinterpret_cast<const char *>(p), value_len);
  15657. break;
  15658. case 6: // uniformResourceIdentifier
  15659. entry.type = SanType::URI;
  15660. entry.value =
  15661. std::string(reinterpret_cast<const char *>(p), value_len);
  15662. break;
  15663. default: entry.type = SanType::OTHER; break;
  15664. }
  15665. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15666. }
  15667. }
  15668. }
  15669. cur = cur->next;
  15670. }
  15671. return true;
  15672. }
  15673. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15674. time_t &not_after) {
  15675. if (!cert) return false;
  15676. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15677. // Convert mbedtls_x509_time to time_t
  15678. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15679. struct tm tm_time = {};
  15680. tm_time.tm_year = t.year - 1900;
  15681. tm_time.tm_mon = t.mon - 1;
  15682. tm_time.tm_mday = t.day;
  15683. tm_time.tm_hour = t.hour;
  15684. tm_time.tm_min = t.min;
  15685. tm_time.tm_sec = t.sec;
  15686. #ifdef _WIN32
  15687. return _mkgmtime(&tm_time);
  15688. #else
  15689. return timegm(&tm_time);
  15690. #endif
  15691. };
  15692. not_before = to_time_t(x509->valid_from);
  15693. not_after = to_time_t(x509->valid_to);
  15694. return true;
  15695. }
  15696. inline std::string get_cert_serial(cert_t cert) {
  15697. if (!cert) return "";
  15698. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15699. // Convert serial number to hex string
  15700. std::string result;
  15701. result.reserve(x509->serial.len * 2);
  15702. for (size_t i = 0; i < x509->serial.len; i++) {
  15703. char hex[3];
  15704. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15705. result += hex;
  15706. }
  15707. return result;
  15708. }
  15709. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15710. if (!cert) return false;
  15711. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  15712. if (!crt->raw.p || crt->raw.len == 0) return false;
  15713. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  15714. return true;
  15715. }
  15716. inline const char *get_sni(const_session_t session) {
  15717. if (!session) return nullptr;
  15718. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  15719. // For server: return SNI received from client during handshake
  15720. if (!msession->sni_hostname.empty()) {
  15721. return msession->sni_hostname.c_str();
  15722. }
  15723. // For client: return the hostname set via set_sni
  15724. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  15725. return nullptr;
  15726. }
  15727. inline uint64_t peek_error() {
  15728. // Mbed TLS doesn't have an error queue, return the last error
  15729. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  15730. }
  15731. inline uint64_t get_error() {
  15732. // Mbed TLS doesn't have an error queue, return and clear the last error
  15733. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  15734. impl::mbedtls_last_error() = 0;
  15735. return err;
  15736. }
  15737. inline std::string error_string(uint64_t code) {
  15738. char buf[256];
  15739. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  15740. return std::string(buf);
  15741. }
  15742. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15743. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  15744. if (!ca_chain) { return nullptr; }
  15745. mbedtls_x509_crt_init(ca_chain);
  15746. // mbedtls_x509_crt_parse expects null-terminated PEM
  15747. int ret = mbedtls_x509_crt_parse(ca_chain,
  15748. reinterpret_cast<const unsigned char *>(pem),
  15749. len + 1); // +1 for null terminator
  15750. if (ret != 0) {
  15751. // Try without +1 in case PEM is already null-terminated
  15752. ret = mbedtls_x509_crt_parse(
  15753. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  15754. if (ret != 0) {
  15755. mbedtls_x509_crt_free(ca_chain);
  15756. delete ca_chain;
  15757. return nullptr;
  15758. }
  15759. }
  15760. return static_cast<ca_store_t>(ca_chain);
  15761. }
  15762. inline void free_ca_store(ca_store_t store) {
  15763. if (store) {
  15764. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15765. mbedtls_x509_crt_free(ca_chain);
  15766. delete ca_chain;
  15767. }
  15768. }
  15769. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15770. if (!ctx || !store) { return false; }
  15771. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15772. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15773. // Free existing CA chain
  15774. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15775. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15776. // Copy the CA chain (deep copy)
  15777. // Parse from the raw data of the source cert
  15778. mbedtls_x509_crt *src = ca_chain;
  15779. while (src != nullptr) {
  15780. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  15781. src->raw.len);
  15782. if (ret != 0) { return false; }
  15783. src = src->next;
  15784. }
  15785. // Update the SSL config to use the new CA chain
  15786. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15787. return true;
  15788. }
  15789. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15790. certs.clear();
  15791. if (!ctx) { return 0; }
  15792. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15793. // Iterate through the CA chain
  15794. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15795. while (cert != nullptr && cert->raw.len > 0) {
  15796. // Create a copy of the certificate for the caller
  15797. auto *copy = new mbedtls_x509_crt;
  15798. mbedtls_x509_crt_init(copy);
  15799. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  15800. if (ret == 0) {
  15801. certs.push_back(static_cast<cert_t>(copy));
  15802. } else {
  15803. mbedtls_x509_crt_free(copy);
  15804. delete copy;
  15805. }
  15806. cert = cert->next;
  15807. }
  15808. return certs.size();
  15809. }
  15810. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15811. std::vector<std::string> names;
  15812. if (!ctx) { return names; }
  15813. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15814. // Iterate through the CA chain
  15815. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15816. while (cert != nullptr && cert->raw.len > 0) {
  15817. char buf[512];
  15818. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  15819. if (ret > 0) { names.push_back(buf); }
  15820. cert = cert->next;
  15821. }
  15822. return names;
  15823. }
  15824. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15825. const char *key_pem, const char *password) {
  15826. if (!ctx || !cert_pem || !key_pem) { return false; }
  15827. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15828. // Free existing certificate and key
  15829. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  15830. mbedtls_pk_free(&mbed_ctx->own_key);
  15831. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  15832. mbedtls_pk_init(&mbed_ctx->own_key);
  15833. // Parse certificate PEM
  15834. int ret = mbedtls_x509_crt_parse(
  15835. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  15836. strlen(cert_pem) + 1);
  15837. if (ret != 0) {
  15838. impl::mbedtls_last_error() = ret;
  15839. return false;
  15840. }
  15841. // Parse private key PEM
  15842. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15843. ret = mbedtls_pk_parse_key(
  15844. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15845. strlen(key_pem) + 1,
  15846. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15847. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  15848. &mbed_ctx->ctr_drbg);
  15849. #else
  15850. ret = mbedtls_pk_parse_key(
  15851. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15852. strlen(key_pem) + 1,
  15853. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15854. password ? strlen(password) : 0);
  15855. #endif
  15856. if (ret != 0) {
  15857. impl::mbedtls_last_error() = ret;
  15858. return false;
  15859. }
  15860. // Configure SSL to use the new certificate and key
  15861. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  15862. &mbed_ctx->own_key);
  15863. if (ret != 0) {
  15864. impl::mbedtls_last_error() = ret;
  15865. return false;
  15866. }
  15867. return true;
  15868. }
  15869. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15870. if (!ctx || !ca_pem) { return false; }
  15871. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15872. // Free existing CA chain
  15873. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15874. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15875. // Parse CA PEM
  15876. int ret = mbedtls_x509_crt_parse(
  15877. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  15878. strlen(ca_pem) + 1);
  15879. if (ret != 0) {
  15880. impl::mbedtls_last_error() = ret;
  15881. return false;
  15882. }
  15883. // Update SSL config to use new CA chain
  15884. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15885. return true;
  15886. }
  15887. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15888. if (!ctx) { return false; }
  15889. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15890. impl::get_verify_callback() = std::move(callback);
  15891. mbed_ctx->has_verify_callback =
  15892. static_cast<bool>(impl::get_verify_callback());
  15893. if (mbed_ctx->has_verify_callback) {
  15894. // Set OPTIONAL mode to ensure callback is called even when verification
  15895. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  15896. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  15897. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  15898. nullptr);
  15899. } else {
  15900. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  15901. }
  15902. return true;
  15903. }
  15904. inline long get_verify_error(const_session_t session) {
  15905. if (!session) { return -1; }
  15906. auto *msession =
  15907. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15908. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  15909. }
  15910. inline std::string verify_error_string(long error_code) {
  15911. if (error_code == 0) { return ""; }
  15912. char buf[256];
  15913. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  15914. static_cast<uint32_t>(error_code));
  15915. // Remove trailing newline if present
  15916. std::string result(buf);
  15917. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  15918. result.pop_back();
  15919. }
  15920. return result;
  15921. }
  15922. } // namespace tls
  15923. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  15924. /*
  15925. * Group 10: TLS abstraction layer - wolfSSL backend
  15926. */
  15927. /*
  15928. * wolfSSL Backend Implementation
  15929. */
  15930. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  15931. namespace tls {
  15932. namespace impl {
  15933. // wolfSSL session wrapper
  15934. struct WolfSSLSession {
  15935. WOLFSSL *ssl = nullptr;
  15936. socket_t sock = INVALID_SOCKET;
  15937. std::string hostname; // For client: set via set_sni
  15938. std::string sni_hostname; // For server: received from client via SNI callback
  15939. WolfSSLSession() = default;
  15940. ~WolfSSLSession() {
  15941. if (ssl) { wolfSSL_free(ssl); }
  15942. }
  15943. WolfSSLSession(const WolfSSLSession &) = delete;
  15944. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  15945. };
  15946. // Thread-local error code accessor for wolfSSL
  15947. inline uint64_t &wolfssl_last_error() {
  15948. static thread_local uint64_t err = 0;
  15949. return err;
  15950. }
  15951. // Helper to map wolfSSL error to ErrorCode.
  15952. // ssl_error is the value from wolfSSL_get_error().
  15953. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  15954. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  15955. int &out_errno) {
  15956. switch (ssl_error) {
  15957. case SSL_ERROR_NONE: return ErrorCode::Success;
  15958. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  15959. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  15960. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  15961. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  15962. default:
  15963. if (ssl) {
  15964. // wolfSSL stores the low-level error code as a negative value.
  15965. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  15966. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  15967. if (low_err == DOMAIN_NAME_MISMATCH) {
  15968. return ErrorCode::HostnameMismatch;
  15969. }
  15970. // Check verify result to distinguish cert verification from generic SSL
  15971. // errors.
  15972. long vr = wolfSSL_get_verify_result(ssl);
  15973. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  15974. }
  15975. return ErrorCode::Fatal;
  15976. }
  15977. }
  15978. // WolfSSLContext constructor/destructor implementations
  15979. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  15980. inline WolfSSLContext::~WolfSSLContext() {
  15981. if (ctx) { wolfSSL_CTX_free(ctx); }
  15982. }
  15983. // Thread-local storage for SNI captured during handshake
  15984. inline std::string &wolfssl_pending_sni() {
  15985. static thread_local std::string sni;
  15986. return sni;
  15987. }
  15988. // SNI callback for wolfSSL server to capture client's SNI hostname
  15989. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  15990. (void)ret;
  15991. (void)exArg;
  15992. void *name_data = nullptr;
  15993. unsigned short name_len =
  15994. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  15995. if (name_data && name_len > 0) {
  15996. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  15997. name_len);
  15998. } else {
  15999. wolfssl_pending_sni().clear();
  16000. }
  16001. return 0; // Continue regardless
  16002. }
  16003. // wolfSSL verify callback wrapper
  16004. inline int wolfssl_verify_callback(int preverify_ok,
  16005. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16006. auto &callback = get_verify_callback();
  16007. if (!callback) { return preverify_ok; }
  16008. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16009. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16010. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16011. // Get the WOLFSSL object from the X509_STORE_CTX
  16012. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16013. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16014. VerifyContext verify_ctx;
  16015. verify_ctx.session = static_cast<session_t>(ssl);
  16016. verify_ctx.cert = static_cast<cert_t>(cert);
  16017. verify_ctx.depth = depth;
  16018. verify_ctx.preverify_ok = (preverify_ok != 0);
  16019. verify_ctx.error_code = static_cast<long>(err);
  16020. if (err != 0) {
  16021. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16022. } else {
  16023. verify_ctx.error_string = nullptr;
  16024. }
  16025. bool accepted = callback(verify_ctx);
  16026. return accepted ? 1 : 0;
  16027. }
  16028. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16029. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16030. wolfSSL_CTX_set_default_passwd_cb(
  16031. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16032. auto *pwd = static_cast<const char *>(userdata);
  16033. if (!pwd) return 0;
  16034. auto len = static_cast<int>(strlen(pwd));
  16035. if (len > size) len = size;
  16036. memcpy(buf, pwd, static_cast<size_t>(len));
  16037. return len;
  16038. });
  16039. }
  16040. } // namespace impl
  16041. inline ctx_t create_client_context() {
  16042. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16043. if (!ctx) { return nullptr; }
  16044. ctx->is_server = false;
  16045. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16046. if (!method) {
  16047. delete ctx;
  16048. return nullptr;
  16049. }
  16050. ctx->ctx = wolfSSL_CTX_new(method);
  16051. if (!ctx->ctx) {
  16052. delete ctx;
  16053. return nullptr;
  16054. }
  16055. // Default: verify peer certificate
  16056. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16057. return static_cast<ctx_t>(ctx);
  16058. }
  16059. inline ctx_t create_server_context() {
  16060. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16061. if (!ctx) { return nullptr; }
  16062. ctx->is_server = true;
  16063. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16064. if (!method) {
  16065. delete ctx;
  16066. return nullptr;
  16067. }
  16068. ctx->ctx = wolfSSL_CTX_new(method);
  16069. if (!ctx->ctx) {
  16070. delete ctx;
  16071. return nullptr;
  16072. }
  16073. // Default: don't verify client
  16074. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16075. // Enable SNI on server
  16076. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16077. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16078. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16079. return static_cast<ctx_t>(ctx);
  16080. }
  16081. inline void free_context(ctx_t ctx) {
  16082. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16083. }
  16084. inline bool set_min_version(ctx_t ctx, Version version) {
  16085. if (!ctx) { return false; }
  16086. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16087. int min_ver = WOLFSSL_TLSV1_2;
  16088. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16089. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16090. }
  16091. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16092. if (!ctx || !pem) { return false; }
  16093. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16094. int ret = wolfSSL_CTX_load_verify_buffer(
  16095. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16096. static_cast<long>(len), SSL_FILETYPE_PEM);
  16097. if (ret != SSL_SUCCESS) {
  16098. impl::wolfssl_last_error() =
  16099. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16100. return false;
  16101. }
  16102. wctx->ca_pem_data_.append(pem, len);
  16103. return true;
  16104. }
  16105. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16106. if (!ctx || !file_path) { return false; }
  16107. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16108. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16109. if (ret != SSL_SUCCESS) {
  16110. impl::wolfssl_last_error() =
  16111. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16112. return false;
  16113. }
  16114. return true;
  16115. }
  16116. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16117. if (!ctx || !dir_path) { return false; }
  16118. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16119. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16120. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16121. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16122. // immediately. Return true even on failure since the CA file may have
  16123. // already been loaded, matching OpenSSL's lenient behavior.
  16124. (void)ret;
  16125. return true;
  16126. }
  16127. inline bool load_system_certs(ctx_t ctx) {
  16128. if (!ctx) { return false; }
  16129. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16130. bool loaded = false;
  16131. #ifdef _WIN32
  16132. loaded = impl::enumerate_windows_system_certs(
  16133. [&](const unsigned char *data, size_t len) {
  16134. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16135. static_cast<long>(len),
  16136. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16137. });
  16138. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16139. loaded = impl::enumerate_macos_keychain_certs(
  16140. [&](const unsigned char *data, size_t len) {
  16141. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16142. static_cast<long>(len),
  16143. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16144. });
  16145. #else
  16146. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16147. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16148. SSL_SUCCESS) {
  16149. loaded = true;
  16150. break;
  16151. }
  16152. }
  16153. if (!loaded) {
  16154. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16155. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16156. SSL_SUCCESS) {
  16157. loaded = true;
  16158. break;
  16159. }
  16160. }
  16161. }
  16162. #endif
  16163. return loaded;
  16164. }
  16165. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16166. const char *password) {
  16167. if (!ctx || !cert || !key) { return false; }
  16168. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16169. // Load certificate
  16170. int ret = wolfSSL_CTX_use_certificate_buffer(
  16171. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16172. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16173. if (ret != SSL_SUCCESS) {
  16174. impl::wolfssl_last_error() =
  16175. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16176. return false;
  16177. }
  16178. // Set password callback if password is provided
  16179. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16180. // Load private key
  16181. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16182. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16183. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16184. if (ret != SSL_SUCCESS) {
  16185. impl::wolfssl_last_error() =
  16186. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16187. return false;
  16188. }
  16189. // Verify that the certificate and private key match
  16190. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16191. }
  16192. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16193. const char *key_path, const char *password) {
  16194. if (!ctx || !cert_path || !key_path) { return false; }
  16195. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16196. // Load certificate file
  16197. int ret =
  16198. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16199. if (ret != SSL_SUCCESS) {
  16200. impl::wolfssl_last_error() =
  16201. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16202. return false;
  16203. }
  16204. // Set password callback if password is provided
  16205. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16206. // Load private key file
  16207. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16208. if (ret != SSL_SUCCESS) {
  16209. impl::wolfssl_last_error() =
  16210. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16211. return false;
  16212. }
  16213. // Verify that the certificate and private key match
  16214. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16215. }
  16216. inline void set_verify_client(ctx_t ctx, bool require) {
  16217. if (!ctx) { return; }
  16218. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16219. wctx->verify_client = require;
  16220. if (require) {
  16221. wolfSSL_CTX_set_verify(
  16222. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16223. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16224. } else {
  16225. if (wctx->has_verify_callback) {
  16226. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16227. impl::wolfssl_verify_callback);
  16228. } else {
  16229. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16230. }
  16231. }
  16232. }
  16233. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16234. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16235. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16236. auto session = new (std::nothrow) impl::WolfSSLSession();
  16237. if (!session) { return nullptr; }
  16238. session->sock = sock;
  16239. session->ssl = wolfSSL_new(wctx->ctx);
  16240. if (!session->ssl) {
  16241. impl::wolfssl_last_error() =
  16242. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16243. delete session;
  16244. return nullptr;
  16245. }
  16246. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16247. return static_cast<session_t>(session);
  16248. }
  16249. inline void free_session(session_t session) {
  16250. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16251. }
  16252. inline bool set_sni(session_t session, const char *hostname) {
  16253. if (!session || !hostname) { return false; }
  16254. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16255. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16256. static_cast<word16>(strlen(hostname)));
  16257. if (ret != WOLFSSL_SUCCESS) {
  16258. impl::wolfssl_last_error() =
  16259. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16260. return false;
  16261. }
  16262. // Also set hostname for verification
  16263. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16264. wsession->hostname = hostname;
  16265. return true;
  16266. }
  16267. inline bool set_hostname(session_t session, const char *hostname) {
  16268. // In wolfSSL, set_hostname also sets up hostname verification
  16269. return set_sni(session, hostname);
  16270. }
  16271. inline TlsError connect(session_t session) {
  16272. TlsError err;
  16273. if (!session) {
  16274. err.code = ErrorCode::Fatal;
  16275. return err;
  16276. }
  16277. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16278. int ret = wolfSSL_connect(wsession->ssl);
  16279. if (ret == SSL_SUCCESS) {
  16280. err.code = ErrorCode::Success;
  16281. } else {
  16282. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16283. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16284. err.backend_code = static_cast<uint64_t>(ssl_error);
  16285. impl::wolfssl_last_error() = err.backend_code;
  16286. }
  16287. return err;
  16288. }
  16289. inline TlsError accept(session_t session) {
  16290. TlsError err;
  16291. if (!session) {
  16292. err.code = ErrorCode::Fatal;
  16293. return err;
  16294. }
  16295. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16296. int ret = wolfSSL_accept(wsession->ssl);
  16297. if (ret == SSL_SUCCESS) {
  16298. err.code = ErrorCode::Success;
  16299. // Capture SNI from thread-local storage after successful handshake
  16300. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16301. impl::wolfssl_pending_sni().clear();
  16302. } else {
  16303. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16304. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16305. err.backend_code = static_cast<uint64_t>(ssl_error);
  16306. impl::wolfssl_last_error() = err.backend_code;
  16307. }
  16308. return err;
  16309. }
  16310. inline bool connect_nonblocking(session_t session, socket_t sock,
  16311. time_t timeout_sec, time_t timeout_usec,
  16312. TlsError *err) {
  16313. if (!session) {
  16314. if (err) { err->code = ErrorCode::Fatal; }
  16315. return false;
  16316. }
  16317. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16318. // Set socket to non-blocking mode
  16319. detail::set_nonblocking(sock, true);
  16320. auto cleanup =
  16321. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16322. int ret;
  16323. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16324. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16325. if (ssl_error == SSL_ERROR_WANT_READ) {
  16326. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16327. continue;
  16328. }
  16329. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16330. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16331. continue;
  16332. }
  16333. }
  16334. // Error or timeout
  16335. if (err) {
  16336. err->code =
  16337. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16338. err->backend_code = static_cast<uint64_t>(ssl_error);
  16339. }
  16340. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16341. return false;
  16342. }
  16343. if (err) { err->code = ErrorCode::Success; }
  16344. return true;
  16345. }
  16346. inline bool accept_nonblocking(session_t session, socket_t sock,
  16347. time_t timeout_sec, time_t timeout_usec,
  16348. TlsError *err) {
  16349. if (!session) {
  16350. if (err) { err->code = ErrorCode::Fatal; }
  16351. return false;
  16352. }
  16353. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16354. // Set socket to non-blocking mode
  16355. detail::set_nonblocking(sock, true);
  16356. auto cleanup =
  16357. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16358. int ret;
  16359. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16360. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16361. if (ssl_error == SSL_ERROR_WANT_READ) {
  16362. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16363. continue;
  16364. }
  16365. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16366. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16367. continue;
  16368. }
  16369. }
  16370. // Error or timeout
  16371. if (err) {
  16372. err->code =
  16373. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16374. err->backend_code = static_cast<uint64_t>(ssl_error);
  16375. }
  16376. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16377. return false;
  16378. }
  16379. if (err) { err->code = ErrorCode::Success; }
  16380. // Capture SNI from thread-local storage after successful handshake
  16381. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16382. impl::wolfssl_pending_sni().clear();
  16383. return true;
  16384. }
  16385. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16386. if (!session || !buf) {
  16387. err.code = ErrorCode::Fatal;
  16388. return -1;
  16389. }
  16390. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16391. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16392. if (ret > 0) {
  16393. err.code = ErrorCode::Success;
  16394. return static_cast<ssize_t>(ret);
  16395. }
  16396. if (ret == 0) {
  16397. err.code = ErrorCode::PeerClosed;
  16398. return 0;
  16399. }
  16400. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16401. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16402. err.backend_code = static_cast<uint64_t>(ssl_error);
  16403. impl::wolfssl_last_error() = err.backend_code;
  16404. return -1;
  16405. }
  16406. inline ssize_t write(session_t session, const void *buf, size_t len,
  16407. TlsError &err) {
  16408. if (!session || !buf) {
  16409. err.code = ErrorCode::Fatal;
  16410. return -1;
  16411. }
  16412. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16413. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16414. if (ret > 0) {
  16415. err.code = ErrorCode::Success;
  16416. return static_cast<ssize_t>(ret);
  16417. }
  16418. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16419. // Treat this as an error (return -1) so callers don't spin in a
  16420. // write loop adding zero to the offset.
  16421. if (ret == 0) {
  16422. err.code = ErrorCode::PeerClosed;
  16423. return -1;
  16424. }
  16425. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16426. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16427. err.backend_code = static_cast<uint64_t>(ssl_error);
  16428. impl::wolfssl_last_error() = err.backend_code;
  16429. return -1;
  16430. }
  16431. inline int pending(const_session_t session) {
  16432. if (!session) { return 0; }
  16433. auto wsession =
  16434. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16435. return wolfSSL_pending(wsession->ssl);
  16436. }
  16437. inline void shutdown(session_t session, bool graceful) {
  16438. if (!session) { return; }
  16439. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16440. if (graceful) {
  16441. int ret;
  16442. int attempts = 0;
  16443. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16444. attempts < 3) {
  16445. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16446. if (ssl_error != SSL_ERROR_WANT_READ &&
  16447. ssl_error != SSL_ERROR_WANT_WRITE) {
  16448. break;
  16449. }
  16450. attempts++;
  16451. }
  16452. } else {
  16453. wolfSSL_shutdown(wsession->ssl);
  16454. }
  16455. }
  16456. inline bool is_peer_closed(session_t session, socket_t sock) {
  16457. if (!session || sock == INVALID_SOCKET) { return true; }
  16458. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16459. // Check if there's already decrypted data available
  16460. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16461. // Set socket to non-blocking to avoid blocking on read
  16462. detail::set_nonblocking(sock, true);
  16463. auto cleanup =
  16464. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16465. // Peek 1 byte to check connection status without consuming data
  16466. unsigned char buf;
  16467. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16468. // If we got data or WANT_READ (would block), connection is alive
  16469. if (ret > 0) { return false; }
  16470. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16471. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16472. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16473. ret == 0;
  16474. }
  16475. inline cert_t get_peer_cert(const_session_t session) {
  16476. if (!session) { return nullptr; }
  16477. auto wsession =
  16478. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16479. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16480. return static_cast<cert_t>(cert);
  16481. }
  16482. inline void free_cert(cert_t cert) {
  16483. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16484. }
  16485. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16486. if (!cert || !hostname) { return false; }
  16487. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16488. std::string host_str(hostname);
  16489. // Check if hostname is an IP address
  16490. bool is_ip = impl::is_ipv4_address(host_str);
  16491. unsigned char ip_bytes[4];
  16492. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  16493. // Check Subject Alternative Names
  16494. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16495. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16496. if (san_names) {
  16497. int san_count = wolfSSL_sk_num(san_names);
  16498. for (int i = 0; i < san_count; i++) {
  16499. auto *names =
  16500. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16501. if (!names) continue;
  16502. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16503. // DNS name
  16504. unsigned char *dns_name = nullptr;
  16505. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16506. if (dns_name && dns_len > 0) {
  16507. std::string san_name(reinterpret_cast<char *>(dns_name),
  16508. static_cast<size_t>(dns_len));
  16509. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16510. if (detail::match_hostname(san_name, host_str)) {
  16511. wolfSSL_sk_free(san_names);
  16512. return true;
  16513. }
  16514. }
  16515. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16516. // IP address
  16517. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16518. int ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16519. if (ip_data && ip_len == 4 && memcmp(ip_data, ip_bytes, 4) == 0) {
  16520. wolfSSL_sk_free(san_names);
  16521. return true;
  16522. }
  16523. }
  16524. }
  16525. wolfSSL_sk_free(san_names);
  16526. }
  16527. // Fallback: Check Common Name (CN) in subject
  16528. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16529. if (subject) {
  16530. char cn[256] = {};
  16531. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16532. sizeof(cn));
  16533. if (cn_len > 0) {
  16534. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16535. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16536. }
  16537. }
  16538. return false;
  16539. }
  16540. inline uint64_t hostname_mismatch_code() {
  16541. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16542. }
  16543. inline long get_verify_result(const_session_t session) {
  16544. if (!session) { return -1; }
  16545. auto wsession =
  16546. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16547. long result = wolfSSL_get_verify_result(wsession->ssl);
  16548. return result;
  16549. }
  16550. inline std::string get_cert_subject_cn(cert_t cert) {
  16551. if (!cert) return "";
  16552. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16553. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16554. if (!subject) return "";
  16555. char cn[256] = {};
  16556. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16557. sizeof(cn));
  16558. if (cn_len <= 0) return "";
  16559. return std::string(cn, static_cast<size_t>(cn_len));
  16560. }
  16561. inline std::string get_cert_issuer_name(cert_t cert) {
  16562. if (!cert) return "";
  16563. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16564. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16565. if (!issuer) return "";
  16566. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16567. if (!name_str) return "";
  16568. std::string result(name_str);
  16569. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16570. return result;
  16571. }
  16572. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16573. sans.clear();
  16574. if (!cert) return false;
  16575. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16576. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16577. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16578. if (!san_names) return true; // No SANs is not an error
  16579. int count = wolfSSL_sk_num(san_names);
  16580. for (int i = 0; i < count; i++) {
  16581. auto *name =
  16582. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16583. if (!name) continue;
  16584. SanEntry entry;
  16585. switch (name->type) {
  16586. case WOLFSSL_GEN_DNS: {
  16587. entry.type = SanType::DNS;
  16588. unsigned char *dns_name = nullptr;
  16589. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16590. if (dns_name && dns_len > 0) {
  16591. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16592. static_cast<size_t>(dns_len));
  16593. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16594. }
  16595. break;
  16596. }
  16597. case WOLFSSL_GEN_IPADD: {
  16598. entry.type = SanType::IP;
  16599. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16600. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16601. if (ip_data && ip_len == 4) {
  16602. char buf[16];
  16603. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16604. ip_data[2], ip_data[3]);
  16605. entry.value = buf;
  16606. } else if (ip_data && ip_len == 16) {
  16607. char buf[64];
  16608. snprintf(buf, sizeof(buf),
  16609. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16610. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16611. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16612. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16613. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16614. ip_data[14], ip_data[15]);
  16615. entry.value = buf;
  16616. }
  16617. break;
  16618. }
  16619. case WOLFSSL_GEN_EMAIL:
  16620. entry.type = SanType::EMAIL;
  16621. {
  16622. unsigned char *email = nullptr;
  16623. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16624. if (email && email_len > 0) {
  16625. entry.value = std::string(reinterpret_cast<char *>(email),
  16626. static_cast<size_t>(email_len));
  16627. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16628. }
  16629. }
  16630. break;
  16631. case WOLFSSL_GEN_URI:
  16632. entry.type = SanType::URI;
  16633. {
  16634. unsigned char *uri = nullptr;
  16635. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16636. &uri, name->d.uniformResourceIdentifier);
  16637. if (uri && uri_len > 0) {
  16638. entry.value = std::string(reinterpret_cast<char *>(uri),
  16639. static_cast<size_t>(uri_len));
  16640. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16641. }
  16642. }
  16643. break;
  16644. default: entry.type = SanType::OTHER; break;
  16645. }
  16646. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16647. }
  16648. wolfSSL_sk_free(san_names);
  16649. return true;
  16650. }
  16651. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16652. time_t &not_after) {
  16653. if (!cert) return false;
  16654. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16655. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16656. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16657. if (!nb || !na) return false;
  16658. // wolfSSL_ASN1_TIME_to_tm is available
  16659. struct tm tm_nb = {}, tm_na = {};
  16660. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16661. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16662. #ifdef _WIN32
  16663. not_before = _mkgmtime(&tm_nb);
  16664. not_after = _mkgmtime(&tm_na);
  16665. #else
  16666. not_before = timegm(&tm_nb);
  16667. not_after = timegm(&tm_na);
  16668. #endif
  16669. return true;
  16670. }
  16671. inline std::string get_cert_serial(cert_t cert) {
  16672. if (!cert) return "";
  16673. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16674. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16675. if (!serial_asn1) return "";
  16676. // Get the serial number data
  16677. int len = serial_asn1->length;
  16678. unsigned char *data = serial_asn1->data;
  16679. if (!data || len <= 0) return "";
  16680. std::string result;
  16681. result.reserve(static_cast<size_t>(len) * 2);
  16682. for (int i = 0; i < len; i++) {
  16683. char hex[3];
  16684. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16685. result += hex;
  16686. }
  16687. return result;
  16688. }
  16689. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16690. if (!cert) return false;
  16691. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16692. int der_len = 0;
  16693. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16694. if (!der_data || der_len <= 0) return false;
  16695. der.assign(der_data, der_data + der_len);
  16696. return true;
  16697. }
  16698. inline const char *get_sni(const_session_t session) {
  16699. if (!session) return nullptr;
  16700. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  16701. // For server: return SNI received from client during handshake
  16702. if (!wsession->sni_hostname.empty()) {
  16703. return wsession->sni_hostname.c_str();
  16704. }
  16705. // For client: return the hostname set via set_sni
  16706. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  16707. return nullptr;
  16708. }
  16709. inline uint64_t peek_error() {
  16710. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16711. }
  16712. inline uint64_t get_error() {
  16713. uint64_t err = impl::wolfssl_last_error();
  16714. impl::wolfssl_last_error() = 0;
  16715. return err;
  16716. }
  16717. inline std::string error_string(uint64_t code) {
  16718. char buf[256];
  16719. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  16720. return std::string(buf);
  16721. }
  16722. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16723. if (!pem || len == 0) { return nullptr; }
  16724. // Validate by attempting to load into a temporary ctx
  16725. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  16726. if (!tmp_ctx) { return nullptr; }
  16727. int ret = wolfSSL_CTX_load_verify_buffer(
  16728. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  16729. static_cast<long>(len), SSL_FILETYPE_PEM);
  16730. wolfSSL_CTX_free(tmp_ctx);
  16731. if (ret != SSL_SUCCESS) { return nullptr; }
  16732. return static_cast<ca_store_t>(
  16733. new impl::WolfSSLCAStore{std::string(pem, len)});
  16734. }
  16735. inline void free_ca_store(ca_store_t store) {
  16736. delete static_cast<impl::WolfSSLCAStore *>(store);
  16737. }
  16738. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16739. if (!ctx || !store) { return false; }
  16740. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16741. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  16742. int ret = wolfSSL_CTX_load_verify_buffer(
  16743. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  16744. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  16745. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  16746. return ret == SSL_SUCCESS;
  16747. }
  16748. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16749. certs.clear();
  16750. if (!ctx) { return 0; }
  16751. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16752. if (wctx->ca_pem_data_.empty()) { return 0; }
  16753. const std::string &pem = wctx->ca_pem_data_;
  16754. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16755. const std::string end_marker = "-----END CERTIFICATE-----";
  16756. size_t pos = 0;
  16757. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16758. size_t end_pos = pem.find(end_marker, pos);
  16759. if (end_pos == std::string::npos) { break; }
  16760. end_pos += end_marker.size();
  16761. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16762. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16763. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16764. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16765. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  16766. pos = end_pos;
  16767. }
  16768. return certs.size();
  16769. }
  16770. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16771. std::vector<std::string> names;
  16772. if (!ctx) { return names; }
  16773. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16774. if (wctx->ca_pem_data_.empty()) { return names; }
  16775. const std::string &pem = wctx->ca_pem_data_;
  16776. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16777. const std::string end_marker = "-----END CERTIFICATE-----";
  16778. size_t pos = 0;
  16779. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16780. size_t end_pos = pem.find(end_marker, pos);
  16781. if (end_pos == std::string::npos) { break; }
  16782. end_pos += end_marker.size();
  16783. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16784. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16785. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16786. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16787. if (x509) {
  16788. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16789. if (subject) {
  16790. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  16791. if (name_str) {
  16792. names.push_back(name_str);
  16793. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16794. }
  16795. }
  16796. wolfSSL_X509_free(x509);
  16797. }
  16798. pos = end_pos;
  16799. }
  16800. return names;
  16801. }
  16802. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16803. const char *key_pem, const char *password) {
  16804. if (!ctx || !cert_pem || !key_pem) { return false; }
  16805. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16806. // Load new certificate
  16807. int ret = wolfSSL_CTX_use_certificate_buffer(
  16808. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  16809. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  16810. if (ret != SSL_SUCCESS) {
  16811. impl::wolfssl_last_error() =
  16812. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16813. return false;
  16814. }
  16815. // Set password if provided
  16816. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16817. // Load new private key
  16818. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16819. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  16820. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  16821. if (ret != SSL_SUCCESS) {
  16822. impl::wolfssl_last_error() =
  16823. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16824. return false;
  16825. }
  16826. return true;
  16827. }
  16828. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16829. if (!ctx || !ca_pem) { return false; }
  16830. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16831. int ret = wolfSSL_CTX_load_verify_buffer(
  16832. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  16833. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  16834. if (ret != SSL_SUCCESS) {
  16835. impl::wolfssl_last_error() =
  16836. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16837. return false;
  16838. }
  16839. return true;
  16840. }
  16841. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16842. if (!ctx) { return false; }
  16843. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16844. impl::get_verify_callback() = std::move(callback);
  16845. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  16846. if (wctx->has_verify_callback) {
  16847. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16848. impl::wolfssl_verify_callback);
  16849. } else {
  16850. wolfSSL_CTX_set_verify(
  16851. wctx->ctx,
  16852. wctx->verify_client
  16853. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16854. : SSL_VERIFY_NONE,
  16855. nullptr);
  16856. }
  16857. return true;
  16858. }
  16859. inline long get_verify_error(const_session_t session) {
  16860. if (!session) { return -1; }
  16861. auto *wsession =
  16862. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16863. return wolfSSL_get_verify_result(wsession->ssl);
  16864. }
  16865. inline std::string verify_error_string(long error_code) {
  16866. if (error_code == 0) { return ""; }
  16867. const char *str =
  16868. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  16869. return str ? std::string(str) : std::string();
  16870. }
  16871. } // namespace tls
  16872. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  16873. // WebSocket implementation
  16874. namespace ws {
  16875. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  16876. bool fin) {
  16877. std::lock_guard<std::mutex> lock(write_mutex_);
  16878. if (closed_) { return false; }
  16879. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  16880. }
  16881. inline ReadResult WebSocket::read(std::string &msg) {
  16882. while (!closed_) {
  16883. Opcode opcode;
  16884. std::string payload;
  16885. bool fin;
  16886. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  16887. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16888. closed_ = true;
  16889. return Fail;
  16890. }
  16891. switch (opcode) {
  16892. case Opcode::Ping: {
  16893. std::lock_guard<std::mutex> lock(write_mutex_);
  16894. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  16895. payload.size(), true, !is_server_);
  16896. continue;
  16897. }
  16898. case Opcode::Pong: continue;
  16899. case Opcode::Close: {
  16900. if (!closed_.exchange(true)) {
  16901. // Echo close frame back
  16902. std::lock_guard<std::mutex> lock(write_mutex_);
  16903. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16904. payload.size(), true, !is_server_);
  16905. }
  16906. return Fail;
  16907. }
  16908. case Opcode::Text:
  16909. case Opcode::Binary: {
  16910. auto result = opcode == Opcode::Text ? Text : Binary;
  16911. msg = std::move(payload);
  16912. // Handle fragmentation
  16913. if (!fin) {
  16914. while (true) {
  16915. Opcode cont_opcode;
  16916. std::string cont_payload;
  16917. bool cont_fin;
  16918. if (!impl::read_websocket_frame(
  16919. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  16920. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16921. closed_ = true;
  16922. return Fail;
  16923. }
  16924. if (cont_opcode == Opcode::Ping) {
  16925. std::lock_guard<std::mutex> lock(write_mutex_);
  16926. detail::write_websocket_frame(
  16927. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  16928. true, !is_server_);
  16929. continue;
  16930. }
  16931. if (cont_opcode == Opcode::Pong) { continue; }
  16932. if (cont_opcode == Opcode::Close) {
  16933. if (!closed_.exchange(true)) {
  16934. std::lock_guard<std::mutex> lock(write_mutex_);
  16935. detail::write_websocket_frame(
  16936. strm_, Opcode::Close, cont_payload.data(),
  16937. cont_payload.size(), true, !is_server_);
  16938. }
  16939. return Fail;
  16940. }
  16941. // RFC 6455: continuation frames must use opcode 0x0
  16942. if (cont_opcode != Opcode::Continuation) {
  16943. closed_ = true;
  16944. return Fail;
  16945. }
  16946. msg += cont_payload;
  16947. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  16948. closed_ = true;
  16949. return Fail;
  16950. }
  16951. if (cont_fin) { break; }
  16952. }
  16953. }
  16954. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  16955. if (result == Text && !impl::is_valid_utf8(msg)) {
  16956. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  16957. return Fail;
  16958. }
  16959. return result;
  16960. }
  16961. default: closed_ = true; return Fail;
  16962. }
  16963. }
  16964. return Fail;
  16965. }
  16966. inline bool WebSocket::send(const std::string &data) {
  16967. return send_frame(Opcode::Text, data.data(), data.size());
  16968. }
  16969. inline bool WebSocket::send(const char *data, size_t len) {
  16970. return send_frame(Opcode::Binary, data, len);
  16971. }
  16972. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  16973. if (closed_.exchange(true)) { return; }
  16974. ping_cv_.notify_all();
  16975. std::string payload;
  16976. auto code = static_cast<uint16_t>(status);
  16977. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  16978. payload.push_back(static_cast<char>(code & 0xFF));
  16979. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  16980. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  16981. payload += reason.substr(0, 123);
  16982. {
  16983. std::lock_guard<std::mutex> lock(write_mutex_);
  16984. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16985. payload.size(), true, !is_server_);
  16986. }
  16987. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  16988. // Close response before closing the TCP connection. Use a short timeout to
  16989. // avoid hanging if the peer doesn't respond.
  16990. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  16991. Opcode op;
  16992. std::string resp;
  16993. bool fin;
  16994. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  16995. if (op == Opcode::Close) { break; }
  16996. }
  16997. }
  16998. inline WebSocket::~WebSocket() {
  16999. {
  17000. std::lock_guard<std::mutex> lock(ping_mutex_);
  17001. closed_ = true;
  17002. }
  17003. ping_cv_.notify_all();
  17004. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17005. }
  17006. inline void WebSocket::start_heartbeat() {
  17007. if (ping_interval_sec_ == 0) { return; }
  17008. ping_thread_ = std::thread([this]() {
  17009. std::unique_lock<std::mutex> lock(ping_mutex_);
  17010. while (!closed_) {
  17011. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17012. if (closed_) { break; }
  17013. lock.unlock();
  17014. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17015. closed_ = true;
  17016. break;
  17017. }
  17018. lock.lock();
  17019. }
  17020. });
  17021. }
  17022. inline const Request &WebSocket::request() const { return req_; }
  17023. inline bool WebSocket::is_open() const { return !closed_; }
  17024. // WebSocketClient implementation
  17025. inline WebSocketClient::WebSocketClient(
  17026. const std::string &scheme_host_port_path, const Headers &headers)
  17027. : headers_(headers) {
  17028. const static std::regex re(
  17029. R"(([a-z]+):\/\/(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?(\/.*))");
  17030. std::smatch m;
  17031. if (std::regex_match(scheme_host_port_path, m, re)) {
  17032. auto scheme = m[1].str();
  17033. #ifdef CPPHTTPLIB_SSL_ENABLED
  17034. if (scheme != "ws" && scheme != "wss") {
  17035. #else
  17036. if (scheme != "ws") {
  17037. #endif
  17038. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17039. std::string msg = "'" + scheme + "' scheme is not supported.";
  17040. throw std::invalid_argument(msg);
  17041. #endif
  17042. return;
  17043. }
  17044. auto is_ssl = scheme == "wss";
  17045. host_ = m[2].str();
  17046. if (host_.empty()) { host_ = m[3].str(); }
  17047. auto port_str = m[4].str();
  17048. port_ = is_ssl ? 443 : 80;
  17049. if (!port_str.empty() && !detail::parse_port(port_str, port_)) { return; }
  17050. path_ = m[5].str();
  17051. #ifdef CPPHTTPLIB_SSL_ENABLED
  17052. is_ssl_ = is_ssl;
  17053. #else
  17054. if (is_ssl) { return; }
  17055. #endif
  17056. is_valid_ = true;
  17057. }
  17058. }
  17059. inline WebSocketClient::~WebSocketClient() { shutdown_and_close(); }
  17060. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17061. inline void WebSocketClient::shutdown_and_close() {
  17062. #ifdef CPPHTTPLIB_SSL_ENABLED
  17063. if (is_ssl_) {
  17064. if (tls_session_) {
  17065. tls::shutdown(tls_session_, true);
  17066. tls::free_session(tls_session_);
  17067. tls_session_ = nullptr;
  17068. }
  17069. if (tls_ctx_) {
  17070. tls::free_context(tls_ctx_);
  17071. tls_ctx_ = nullptr;
  17072. }
  17073. }
  17074. #endif
  17075. if (ws_ && ws_->is_open()) { ws_->close(); }
  17076. ws_.reset();
  17077. if (sock_ != INVALID_SOCKET) {
  17078. detail::shutdown_socket(sock_);
  17079. detail::close_socket(sock_);
  17080. sock_ = INVALID_SOCKET;
  17081. }
  17082. }
  17083. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17084. #ifdef CPPHTTPLIB_SSL_ENABLED
  17085. if (is_ssl_) {
  17086. if (!detail::setup_client_tls_session(
  17087. host_, tls_ctx_, tls_session_, sock_,
  17088. server_certificate_verification_, ca_cert_file_path_,
  17089. ca_cert_store_, read_timeout_sec_, read_timeout_usec_)) {
  17090. return false;
  17091. }
  17092. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17093. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17094. write_timeout_sec_, write_timeout_usec_));
  17095. return true;
  17096. }
  17097. #endif
  17098. strm = std::unique_ptr<Stream>(
  17099. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17100. write_timeout_sec_, write_timeout_usec_));
  17101. return true;
  17102. }
  17103. inline bool WebSocketClient::connect() {
  17104. if (!is_valid_) { return false; }
  17105. shutdown_and_close();
  17106. Error error;
  17107. sock_ = detail::create_client_socket(
  17108. host_, std::string(), port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17109. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17110. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17111. write_timeout_usec_, interface_, error);
  17112. if (sock_ == INVALID_SOCKET) { return false; }
  17113. std::unique_ptr<Stream> strm;
  17114. if (!create_stream(strm)) {
  17115. shutdown_and_close();
  17116. return false;
  17117. }
  17118. std::string selected_subprotocol;
  17119. if (!detail::perform_websocket_handshake(*strm, host_, port_, path_, headers_,
  17120. selected_subprotocol)) {
  17121. shutdown_and_close();
  17122. return false;
  17123. }
  17124. subprotocol_ = std::move(selected_subprotocol);
  17125. Request req;
  17126. req.method = "GET";
  17127. req.path = path_;
  17128. ws_ = std::unique_ptr<WebSocket>(
  17129. new WebSocket(std::move(strm), req, false, websocket_ping_interval_sec_));
  17130. return true;
  17131. }
  17132. inline ReadResult WebSocketClient::read(std::string &msg) {
  17133. if (!ws_) { return Fail; }
  17134. return ws_->read(msg);
  17135. }
  17136. inline bool WebSocketClient::send(const std::string &data) {
  17137. if (!ws_) { return false; }
  17138. return ws_->send(data);
  17139. }
  17140. inline bool WebSocketClient::send(const char *data, size_t len) {
  17141. if (!ws_) { return false; }
  17142. return ws_->send(data, len);
  17143. }
  17144. inline void WebSocketClient::close(CloseStatus status,
  17145. const std::string &reason) {
  17146. if (ws_) { ws_->close(status, reason); }
  17147. }
  17148. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17149. inline const std::string &WebSocketClient::subprotocol() const {
  17150. return subprotocol_;
  17151. }
  17152. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17153. read_timeout_sec_ = sec;
  17154. read_timeout_usec_ = usec;
  17155. }
  17156. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17157. write_timeout_sec_ = sec;
  17158. write_timeout_usec_ = usec;
  17159. }
  17160. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17161. websocket_ping_interval_sec_ = sec;
  17162. }
  17163. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17164. inline void WebSocketClient::set_address_family(int family) {
  17165. address_family_ = family;
  17166. }
  17167. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17168. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17169. socket_options_ = std::move(socket_options);
  17170. }
  17171. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17172. connection_timeout_sec_ = sec;
  17173. connection_timeout_usec_ = usec;
  17174. }
  17175. inline void WebSocketClient::set_interface(const std::string &intf) {
  17176. interface_ = intf;
  17177. }
  17178. #ifdef CPPHTTPLIB_SSL_ENABLED
  17179. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17180. ca_cert_file_path_ = path;
  17181. }
  17182. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17183. ca_cert_store_ = store;
  17184. }
  17185. inline void
  17186. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17187. server_certificate_verification_ = enabled;
  17188. }
  17189. #endif // CPPHTTPLIB_SSL_ENABLED
  17190. } // namespace ws
  17191. // ----------------------------------------------------------------------------
  17192. } // namespace httplib
  17193. #endif // CPPHTTPLIB_HTTPLIB_H